1 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
2 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
3 //! claim outputs on-chain.
5 use chain::transaction::OutPoint;
6 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
7 use chain::chaininterface;
8 use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
9 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
10 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
11 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
12 use ln::channelmonitor;
13 use ln::channel::{Channel, ChannelError};
14 use ln::{chan_utils, onion_utils};
15 use routing::router::{Route, RouteHop, get_route};
16 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
18 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
19 use util::enforcing_trait_impls::EnforcingChannelKeys;
20 use util::{byte_utils, test_utils};
21 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
22 use util::errors::APIError;
23 use util::ser::{Writeable, Writer, ReadableArgs};
24 use util::config::UserConfig;
25 use util::logger::Logger;
27 use bitcoin::util::hash::BitcoinHash;
28 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
29 use bitcoin::hash_types::{Txid, BlockHash};
30 use bitcoin::util::bip143;
31 use bitcoin::util::address::Address;
32 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
33 use bitcoin::blockdata::block::{Block, BlockHeader};
34 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
35 use bitcoin::blockdata::script::{Builder, Script};
36 use bitcoin::blockdata::opcodes;
37 use bitcoin::blockdata::constants::genesis_block;
38 use bitcoin::network::constants::Network;
40 use bitcoin::hashes::sha256::Hash as Sha256;
41 use bitcoin::hashes::Hash;
43 use bitcoin::secp256k1::{Secp256k1, Message};
44 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
46 use std::collections::{BTreeSet, HashMap, HashSet};
47 use std::default::Default;
48 use std::sync::{Arc, Mutex};
49 use std::sync::atomic::Ordering;
52 use rand::{thread_rng, Rng};
54 use ln::functional_test_utils::*;
57 fn test_insane_channel_opens() {
58 // Stand up a network of 2 nodes
59 let chanmon_cfgs = create_chanmon_cfgs(2);
60 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
61 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
62 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
64 // Instantiate channel parameters where we push the maximum msats given our
66 let channel_value_sat = 31337; // same as funding satoshis
67 let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_remote_channel_reserve_satoshis(channel_value_sat);
68 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
70 // Have node0 initiate a channel to node1 with aforementioned parameters
71 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
73 // Extract the channel open message from node0 to node1
74 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
76 // Test helper that asserts we get the correct error string given a mutator
77 // that supposedly makes the channel open message insane
78 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
79 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
80 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
81 assert_eq!(msg_events.len(), 1);
82 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
84 &ErrorAction::SendErrorMessage { .. } => {
85 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
87 _ => panic!("unexpected event!"),
89 } else { assert!(false); }
92 use ln::channel::MAX_FUNDING_SATOSHIS;
93 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
95 // Test all mutations that would make the channel open message insane
96 insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
98 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
100 insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
102 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
104 insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
106 insane_open_helper("Minimum htlc value is full channel value", |mut msg| { msg.htlc_minimum_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000; msg });
108 insane_open_helper("They wanted our payments to be delayed by a needlessly long period", |mut msg| { msg.to_self_delay = MAX_LOCAL_BREAKDOWN_TIMEOUT + 1; msg });
110 insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
112 insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
116 fn test_async_inbound_update_fee() {
117 let chanmon_cfgs = create_chanmon_cfgs(2);
118 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
119 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
120 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
121 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
122 let logger = Arc::new(test_utils::TestLogger::new());
123 let channel_id = chan.2;
126 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
130 // send (1) commitment_signed -.
131 // <- update_add_htlc/commitment_signed
132 // send (2) RAA (awaiting remote revoke) -.
133 // (1) commitment_signed is delivered ->
134 // .- send (3) RAA (awaiting remote revoke)
135 // (2) RAA is delivered ->
136 // .- send (4) commitment_signed
137 // <- (3) RAA is delivered
138 // send (5) commitment_signed -.
139 // <- (4) commitment_signed is delivered
141 // (5) commitment_signed is delivered ->
143 // (6) RAA is delivered ->
145 // First nodes[0] generates an update_fee
146 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
147 check_added_monitors!(nodes[0], 1);
149 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
150 assert_eq!(events_0.len(), 1);
151 let (update_msg, commitment_signed) = match events_0[0] { // (1)
152 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
153 (update_fee.as_ref(), commitment_signed)
155 _ => panic!("Unexpected event"),
158 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
160 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
161 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
162 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
163 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, logger.clone()).unwrap(), our_payment_hash, &None).unwrap();
164 check_added_monitors!(nodes[1], 1);
166 let payment_event = {
167 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
168 assert_eq!(events_1.len(), 1);
169 SendEvent::from_event(events_1.remove(0))
171 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
172 assert_eq!(payment_event.msgs.len(), 1);
174 // ...now when the messages get delivered everyone should be happy
175 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
176 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
177 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
178 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
179 check_added_monitors!(nodes[0], 1);
181 // deliver(1), generate (3):
182 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
183 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
184 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
185 check_added_monitors!(nodes[1], 1);
187 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
188 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
189 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
190 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
191 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
192 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
193 assert!(bs_update.update_fee.is_none()); // (4)
194 check_added_monitors!(nodes[1], 1);
196 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
197 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
198 assert!(as_update.update_add_htlcs.is_empty()); // (5)
199 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
200 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
201 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
202 assert!(as_update.update_fee.is_none()); // (5)
203 check_added_monitors!(nodes[0], 1);
205 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
206 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
207 // only (6) so get_event_msg's assert(len == 1) passes
208 check_added_monitors!(nodes[0], 1);
210 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
211 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
212 check_added_monitors!(nodes[1], 1);
214 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
215 check_added_monitors!(nodes[0], 1);
217 let events_2 = nodes[0].node.get_and_clear_pending_events();
218 assert_eq!(events_2.len(), 1);
220 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
221 _ => panic!("Unexpected event"),
224 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
225 check_added_monitors!(nodes[1], 1);
229 fn test_update_fee_unordered_raa() {
230 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
231 // crash in an earlier version of the update_fee patch)
232 let chanmon_cfgs = create_chanmon_cfgs(2);
233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
235 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
236 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
237 let channel_id = chan.2;
238 let logger = Arc::new(test_utils::TestLogger::new());
241 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
243 // First nodes[0] generates an update_fee
244 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
245 check_added_monitors!(nodes[0], 1);
247 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
248 assert_eq!(events_0.len(), 1);
249 let update_msg = match events_0[0] { // (1)
250 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
253 _ => panic!("Unexpected event"),
256 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
258 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
259 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
260 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
261 nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, logger.clone()).unwrap(), our_payment_hash, &None).unwrap();
262 check_added_monitors!(nodes[1], 1);
264 let payment_event = {
265 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
266 assert_eq!(events_1.len(), 1);
267 SendEvent::from_event(events_1.remove(0))
269 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
270 assert_eq!(payment_event.msgs.len(), 1);
272 // ...now when the messages get delivered everyone should be happy
273 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
274 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
275 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
276 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
277 check_added_monitors!(nodes[0], 1);
279 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
280 check_added_monitors!(nodes[1], 1);
282 // We can't continue, sadly, because our (1) now has a bogus signature
286 fn test_multi_flight_update_fee() {
287 let chanmon_cfgs = create_chanmon_cfgs(2);
288 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
289 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
290 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
291 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
292 let channel_id = chan.2;
295 // update_fee/commitment_signed ->
296 // .- send (1) RAA and (2) commitment_signed
297 // update_fee (never committed) ->
299 // We have to manually generate the above update_fee, it is allowed by the protocol but we
300 // don't track which updates correspond to which revoke_and_ack responses so we're in
301 // AwaitingRAA mode and will not generate the update_fee yet.
302 // <- (1) RAA delivered
303 // (3) is generated and send (4) CS -.
304 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
305 // know the per_commitment_point to use for it.
306 // <- (2) commitment_signed delivered
308 // B should send no response here
309 // (4) commitment_signed delivered ->
310 // <- RAA/commitment_signed delivered
313 // First nodes[0] generates an update_fee
314 let initial_feerate = get_feerate!(nodes[0], channel_id);
315 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
316 check_added_monitors!(nodes[0], 1);
318 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
319 assert_eq!(events_0.len(), 1);
320 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
321 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
322 (update_fee.as_ref().unwrap(), commitment_signed)
324 _ => panic!("Unexpected event"),
327 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
328 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
329 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
330 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
331 check_added_monitors!(nodes[1], 1);
333 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
335 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
336 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
337 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
339 // Create the (3) update_fee message that nodes[0] will generate before it does...
340 let mut update_msg_2 = msgs::UpdateFee {
341 channel_id: update_msg_1.channel_id.clone(),
342 feerate_per_kw: (initial_feerate + 30) as u32,
345 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
347 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
349 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
351 // Deliver (1), generating (3) and (4)
352 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
353 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
354 check_added_monitors!(nodes[0], 1);
355 assert!(as_second_update.update_add_htlcs.is_empty());
356 assert!(as_second_update.update_fulfill_htlcs.is_empty());
357 assert!(as_second_update.update_fail_htlcs.is_empty());
358 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
359 // Check that the update_fee newly generated matches what we delivered:
360 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
361 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
363 // Deliver (2) commitment_signed
364 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
365 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
366 check_added_monitors!(nodes[0], 1);
367 // No commitment_signed so get_event_msg's assert(len == 1) passes
369 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
370 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
371 check_added_monitors!(nodes[1], 1);
374 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
375 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
376 check_added_monitors!(nodes[1], 1);
378 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
379 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
380 check_added_monitors!(nodes[0], 1);
382 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
383 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
384 // No commitment_signed so get_event_msg's assert(len == 1) passes
385 check_added_monitors!(nodes[0], 1);
387 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
388 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
389 check_added_monitors!(nodes[1], 1);
393 fn test_1_conf_open() {
394 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
395 // tests that we properly send one in that case.
396 let mut alice_config = UserConfig::default();
397 alice_config.own_channel_config.minimum_depth = 1;
398 alice_config.channel_options.announced_channel = true;
399 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
400 let mut bob_config = UserConfig::default();
401 bob_config.own_channel_config.minimum_depth = 1;
402 bob_config.channel_options.announced_channel = true;
403 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
404 let chanmon_cfgs = create_chanmon_cfgs(2);
405 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
406 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
407 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
409 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
410 assert!(nodes[0].chain_monitor.does_match_tx(&tx));
411 assert!(nodes[1].chain_monitor.does_match_tx(&tx));
413 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
414 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
415 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
417 nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
418 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
419 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
422 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
423 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
424 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
428 fn do_test_sanity_on_in_flight_opens(steps: u8) {
429 // Previously, we had issues deserializing channels when we hadn't connected the first block
430 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
431 // serialization round-trips and simply do steps towards opening a channel and then drop the
434 let chanmon_cfgs = create_chanmon_cfgs(2);
435 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
436 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
437 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
439 if steps & 0b1000_0000 != 0{
440 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
441 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
442 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
445 if steps & 0x0f == 0 { return; }
446 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
447 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
449 if steps & 0x0f == 1 { return; }
450 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
451 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
453 if steps & 0x0f == 2 { return; }
454 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
456 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
458 if steps & 0x0f == 3 { return; }
459 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
460 check_added_monitors!(nodes[0], 0);
461 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
463 if steps & 0x0f == 4 { return; }
464 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
466 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
467 assert_eq!(added_monitors.len(), 1);
468 assert_eq!(added_monitors[0].0, funding_output);
469 added_monitors.clear();
471 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
473 if steps & 0x0f == 5 { return; }
474 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
476 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
477 assert_eq!(added_monitors.len(), 1);
478 assert_eq!(added_monitors[0].0, funding_output);
479 added_monitors.clear();
482 let events_4 = nodes[0].node.get_and_clear_pending_events();
483 assert_eq!(events_4.len(), 1);
485 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
486 assert_eq!(user_channel_id, 42);
487 assert_eq!(*funding_txo, funding_output);
489 _ => panic!("Unexpected event"),
492 if steps & 0x0f == 6 { return; }
493 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
495 if steps & 0x0f == 7 { return; }
496 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
497 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
501 fn test_sanity_on_in_flight_opens() {
502 do_test_sanity_on_in_flight_opens(0);
503 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
504 do_test_sanity_on_in_flight_opens(1);
505 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
506 do_test_sanity_on_in_flight_opens(2);
507 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
508 do_test_sanity_on_in_flight_opens(3);
509 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
510 do_test_sanity_on_in_flight_opens(4);
511 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
512 do_test_sanity_on_in_flight_opens(5);
513 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
514 do_test_sanity_on_in_flight_opens(6);
515 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
516 do_test_sanity_on_in_flight_opens(7);
517 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
518 do_test_sanity_on_in_flight_opens(8);
519 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
523 fn test_update_fee_vanilla() {
524 let chanmon_cfgs = create_chanmon_cfgs(2);
525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
527 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
528 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
529 let channel_id = chan.2;
531 let feerate = get_feerate!(nodes[0], channel_id);
532 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
533 check_added_monitors!(nodes[0], 1);
535 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
536 assert_eq!(events_0.len(), 1);
537 let (update_msg, commitment_signed) = match events_0[0] {
538 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
539 (update_fee.as_ref(), commitment_signed)
541 _ => panic!("Unexpected event"),
543 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
545 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
546 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
547 check_added_monitors!(nodes[1], 1);
549 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
550 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
551 check_added_monitors!(nodes[0], 1);
553 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
554 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
555 // No commitment_signed so get_event_msg's assert(len == 1) passes
556 check_added_monitors!(nodes[0], 1);
558 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
559 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
560 check_added_monitors!(nodes[1], 1);
564 fn test_update_fee_that_funder_cannot_afford() {
565 let chanmon_cfgs = create_chanmon_cfgs(2);
566 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
567 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
568 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
569 let channel_value = 1888;
570 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
571 let channel_id = chan.2;
574 nodes[0].node.update_fee(channel_id, feerate).unwrap();
575 check_added_monitors!(nodes[0], 1);
576 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
578 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
580 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
582 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
583 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
585 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
587 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
588 let num_htlcs = commitment_tx.output.len() - 2;
589 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
590 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
591 actual_fee = channel_value - actual_fee;
592 assert_eq!(total_fee, actual_fee);
595 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
596 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
597 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
598 check_added_monitors!(nodes[0], 1);
600 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
602 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
604 //While producing the commitment_signed response after handling a received update_fee request the
605 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
606 //Should produce and error.
607 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
608 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
609 check_added_monitors!(nodes[1], 1);
610 check_closed_broadcast!(nodes[1], true);
614 fn test_update_fee_with_fundee_update_add_htlc() {
615 let chanmon_cfgs = create_chanmon_cfgs(2);
616 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
617 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
618 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
619 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
620 let channel_id = chan.2;
621 let logger = Arc::new(test_utils::TestLogger::new());
624 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
626 let feerate = get_feerate!(nodes[0], channel_id);
627 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
628 check_added_monitors!(nodes[0], 1);
630 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
631 assert_eq!(events_0.len(), 1);
632 let (update_msg, commitment_signed) = match events_0[0] {
633 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
634 (update_fee.as_ref(), commitment_signed)
636 _ => panic!("Unexpected event"),
638 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
639 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
640 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
641 check_added_monitors!(nodes[1], 1);
643 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
644 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
645 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV, logger.clone()).unwrap();
647 // nothing happens since node[1] is in AwaitingRemoteRevoke
648 nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
650 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
651 assert_eq!(added_monitors.len(), 0);
652 added_monitors.clear();
654 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
655 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
656 // node[1] has nothing to do
658 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
659 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
660 check_added_monitors!(nodes[0], 1);
662 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
663 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
664 // No commitment_signed so get_event_msg's assert(len == 1) passes
665 check_added_monitors!(nodes[0], 1);
666 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
667 check_added_monitors!(nodes[1], 1);
668 // AwaitingRemoteRevoke ends here
670 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
671 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
672 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
673 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
674 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
675 assert_eq!(commitment_update.update_fee.is_none(), true);
677 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
678 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
679 check_added_monitors!(nodes[0], 1);
680 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
682 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
683 check_added_monitors!(nodes[1], 1);
684 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
686 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
687 check_added_monitors!(nodes[1], 1);
688 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
689 // No commitment_signed so get_event_msg's assert(len == 1) passes
691 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
692 check_added_monitors!(nodes[0], 1);
693 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
695 expect_pending_htlcs_forwardable!(nodes[0]);
697 let events = nodes[0].node.get_and_clear_pending_events();
698 assert_eq!(events.len(), 1);
700 Event::PaymentReceived { .. } => { },
701 _ => panic!("Unexpected event"),
704 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
706 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
707 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
708 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
712 fn test_update_fee() {
713 let chanmon_cfgs = create_chanmon_cfgs(2);
714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
716 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
717 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
718 let channel_id = chan.2;
721 // (1) update_fee/commitment_signed ->
722 // <- (2) revoke_and_ack
723 // .- send (3) commitment_signed
724 // (4) update_fee/commitment_signed ->
725 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
726 // <- (3) commitment_signed delivered
727 // send (6) revoke_and_ack -.
728 // <- (5) deliver revoke_and_ack
729 // (6) deliver revoke_and_ack ->
730 // .- send (7) commitment_signed in response to (4)
731 // <- (7) deliver commitment_signed
734 // Create and deliver (1)...
735 let feerate = get_feerate!(nodes[0], channel_id);
736 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
737 check_added_monitors!(nodes[0], 1);
739 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
740 assert_eq!(events_0.len(), 1);
741 let (update_msg, commitment_signed) = match events_0[0] {
742 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
743 (update_fee.as_ref(), commitment_signed)
745 _ => panic!("Unexpected event"),
747 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
749 // Generate (2) and (3):
750 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
751 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
752 check_added_monitors!(nodes[1], 1);
755 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
756 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
757 check_added_monitors!(nodes[0], 1);
759 // Create and deliver (4)...
760 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
761 check_added_monitors!(nodes[0], 1);
762 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
763 assert_eq!(events_0.len(), 1);
764 let (update_msg, commitment_signed) = match events_0[0] {
765 MessageSendEvent::UpdateHTLCs { node_id:_, updates: msgs::CommitmentUpdate { update_add_htlcs:_, update_fulfill_htlcs:_, update_fail_htlcs:_, update_fail_malformed_htlcs:_, ref update_fee, ref commitment_signed } } => {
766 (update_fee.as_ref(), commitment_signed)
768 _ => panic!("Unexpected event"),
771 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
772 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
773 check_added_monitors!(nodes[1], 1);
775 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
776 // No commitment_signed so get_event_msg's assert(len == 1) passes
778 // Handle (3), creating (6):
779 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
780 check_added_monitors!(nodes[0], 1);
781 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
782 // No commitment_signed so get_event_msg's assert(len == 1) passes
785 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
786 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
787 check_added_monitors!(nodes[0], 1);
789 // Deliver (6), creating (7):
790 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
791 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
792 assert!(commitment_update.update_add_htlcs.is_empty());
793 assert!(commitment_update.update_fulfill_htlcs.is_empty());
794 assert!(commitment_update.update_fail_htlcs.is_empty());
795 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
796 assert!(commitment_update.update_fee.is_none());
797 check_added_monitors!(nodes[1], 1);
800 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
801 check_added_monitors!(nodes[0], 1);
802 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
803 // No commitment_signed so get_event_msg's assert(len == 1) passes
805 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
806 check_added_monitors!(nodes[1], 1);
807 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
809 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
810 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
811 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
815 fn pre_funding_lock_shutdown_test() {
816 // Test sending a shutdown prior to funding_locked after funding generation
817 let chanmon_cfgs = create_chanmon_cfgs(2);
818 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
819 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
820 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
821 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
822 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
823 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
824 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
826 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
827 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
828 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
829 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
830 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
832 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
833 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
834 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
835 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
836 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
837 assert!(node_0_none.is_none());
839 assert!(nodes[0].node.list_channels().is_empty());
840 assert!(nodes[1].node.list_channels().is_empty());
844 fn updates_shutdown_wait() {
845 // Test sending a shutdown with outstanding updates pending
846 let chanmon_cfgs = create_chanmon_cfgs(3);
847 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
848 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
849 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
850 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
851 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
852 let logger = Arc::new(test_utils::TestLogger::new());
854 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
856 nodes[0].node.close_channel(&chan_1.2).unwrap();
857 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
858 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
859 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
860 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
862 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
863 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
865 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
867 let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
868 let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
869 let route_1 = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler0, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
870 let route_2 = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler1, &nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
871 unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
872 unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
874 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
875 check_added_monitors!(nodes[2], 1);
876 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
877 assert!(updates.update_add_htlcs.is_empty());
878 assert!(updates.update_fail_htlcs.is_empty());
879 assert!(updates.update_fail_malformed_htlcs.is_empty());
880 assert!(updates.update_fee.is_none());
881 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
882 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
883 check_added_monitors!(nodes[1], 1);
884 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
885 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
887 assert!(updates_2.update_add_htlcs.is_empty());
888 assert!(updates_2.update_fail_htlcs.is_empty());
889 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
890 assert!(updates_2.update_fee.is_none());
891 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
892 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
893 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
895 let events = nodes[0].node.get_and_clear_pending_events();
896 assert_eq!(events.len(), 1);
898 Event::PaymentSent { ref payment_preimage } => {
899 assert_eq!(our_payment_preimage, *payment_preimage);
901 _ => panic!("Unexpected event"),
904 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
905 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
906 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
907 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
908 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
909 assert!(node_0_none.is_none());
911 assert!(nodes[0].node.list_channels().is_empty());
913 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
914 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
915 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
916 assert!(nodes[1].node.list_channels().is_empty());
917 assert!(nodes[2].node.list_channels().is_empty());
921 fn htlc_fail_async_shutdown() {
922 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
923 let chanmon_cfgs = create_chanmon_cfgs(3);
924 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
925 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
926 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
927 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
928 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
929 let logger = Arc::new(test_utils::TestLogger::new());
931 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
932 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
933 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
934 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
935 check_added_monitors!(nodes[0], 1);
936 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
937 assert_eq!(updates.update_add_htlcs.len(), 1);
938 assert!(updates.update_fulfill_htlcs.is_empty());
939 assert!(updates.update_fail_htlcs.is_empty());
940 assert!(updates.update_fail_malformed_htlcs.is_empty());
941 assert!(updates.update_fee.is_none());
943 nodes[1].node.close_channel(&chan_1.2).unwrap();
944 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
945 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
946 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
948 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
949 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
950 check_added_monitors!(nodes[1], 1);
951 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
952 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
954 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
955 assert!(updates_2.update_add_htlcs.is_empty());
956 assert!(updates_2.update_fulfill_htlcs.is_empty());
957 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
958 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
959 assert!(updates_2.update_fee.is_none());
961 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
962 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
964 expect_payment_failed!(nodes[0], our_payment_hash, false);
966 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
967 assert_eq!(msg_events.len(), 2);
968 let node_0_closing_signed = match msg_events[0] {
969 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
970 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
973 _ => panic!("Unexpected event"),
975 match msg_events[1] {
976 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
977 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
979 _ => panic!("Unexpected event"),
982 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
983 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
984 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
985 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
986 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
987 assert!(node_0_none.is_none());
989 assert!(nodes[0].node.list_channels().is_empty());
991 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
992 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
993 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
994 assert!(nodes[1].node.list_channels().is_empty());
995 assert!(nodes[2].node.list_channels().is_empty());
998 fn do_test_shutdown_rebroadcast(recv_count: u8) {
999 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1000 // messages delivered prior to disconnect
1001 let chanmon_cfgs = create_chanmon_cfgs(3);
1002 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1003 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1004 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1005 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1006 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1008 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1010 nodes[1].node.close_channel(&chan_1.2).unwrap();
1011 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1013 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1014 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1016 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1020 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1021 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1023 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1024 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1025 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1026 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1028 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1029 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1030 assert!(node_1_shutdown == node_1_2nd_shutdown);
1032 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1033 let node_0_2nd_shutdown = if recv_count > 0 {
1034 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1035 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1038 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1039 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1040 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1042 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1044 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1045 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1047 assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1048 check_added_monitors!(nodes[2], 1);
1049 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1050 assert!(updates.update_add_htlcs.is_empty());
1051 assert!(updates.update_fail_htlcs.is_empty());
1052 assert!(updates.update_fail_malformed_htlcs.is_empty());
1053 assert!(updates.update_fee.is_none());
1054 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1055 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1056 check_added_monitors!(nodes[1], 1);
1057 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1058 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1060 assert!(updates_2.update_add_htlcs.is_empty());
1061 assert!(updates_2.update_fail_htlcs.is_empty());
1062 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1063 assert!(updates_2.update_fee.is_none());
1064 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1065 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1066 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1068 let events = nodes[0].node.get_and_clear_pending_events();
1069 assert_eq!(events.len(), 1);
1071 Event::PaymentSent { ref payment_preimage } => {
1072 assert_eq!(our_payment_preimage, *payment_preimage);
1074 _ => panic!("Unexpected event"),
1077 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1079 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1080 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1081 assert!(node_1_closing_signed.is_some());
1084 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1085 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1087 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1088 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1089 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1090 if recv_count == 0 {
1091 // If all closing_signeds weren't delivered we can just resume where we left off...
1092 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1094 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1095 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1096 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1098 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1099 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1100 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1102 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1103 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1105 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1106 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1107 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1109 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1110 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1111 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1112 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1113 assert!(node_0_none.is_none());
1115 // If one node, however, received + responded with an identical closing_signed we end
1116 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1117 // There isn't really anything better we can do simply, but in the future we might
1118 // explore storing a set of recently-closed channels that got disconnected during
1119 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1120 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1122 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1124 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1125 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1126 assert_eq!(msg_events.len(), 1);
1127 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1129 &ErrorAction::SendErrorMessage { ref msg } => {
1130 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1131 assert_eq!(msg.channel_id, chan_1.2);
1133 _ => panic!("Unexpected event!"),
1135 } else { panic!("Needed SendErrorMessage close"); }
1137 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1138 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1139 // closing_signed so we do it ourselves
1140 check_closed_broadcast!(nodes[0], false);
1141 check_added_monitors!(nodes[0], 1);
1144 assert!(nodes[0].node.list_channels().is_empty());
1146 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1147 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1148 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1149 assert!(nodes[1].node.list_channels().is_empty());
1150 assert!(nodes[2].node.list_channels().is_empty());
1154 fn test_shutdown_rebroadcast() {
1155 do_test_shutdown_rebroadcast(0);
1156 do_test_shutdown_rebroadcast(1);
1157 do_test_shutdown_rebroadcast(2);
1161 fn fake_network_test() {
1162 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1163 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1164 let chanmon_cfgs = create_chanmon_cfgs(4);
1165 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1166 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1167 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1169 // Create some initial channels
1170 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1171 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1172 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1174 // Rebalance the network a bit by relaying one payment through all the channels...
1175 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1176 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1177 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1178 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1180 // Send some more payments
1181 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1182 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1183 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1185 // Test failure packets
1186 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1187 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1189 // Add a new channel that skips 3
1190 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1192 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1193 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1194 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1195 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1196 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1197 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1198 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1200 // Do some rebalance loop payments, simultaneously
1201 let mut hops = Vec::with_capacity(3);
1202 hops.push(RouteHop {
1203 pubkey: nodes[2].node.get_our_node_id(),
1204 node_features: NodeFeatures::empty(),
1205 short_channel_id: chan_2.0.contents.short_channel_id,
1206 channel_features: ChannelFeatures::empty(),
1208 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1210 hops.push(RouteHop {
1211 pubkey: nodes[3].node.get_our_node_id(),
1212 node_features: NodeFeatures::empty(),
1213 short_channel_id: chan_3.0.contents.short_channel_id,
1214 channel_features: ChannelFeatures::empty(),
1216 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1218 hops.push(RouteHop {
1219 pubkey: nodes[1].node.get_our_node_id(),
1220 node_features: NodeFeatures::empty(),
1221 short_channel_id: chan_4.0.contents.short_channel_id,
1222 channel_features: ChannelFeatures::empty(),
1224 cltv_expiry_delta: TEST_FINAL_CLTV,
1226 hops[1].fee_msat = chan_4.1.contents.fee_base_msat as u64 + chan_4.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1227 hops[0].fee_msat = chan_3.0.contents.fee_base_msat as u64 + chan_3.0.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1228 let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1230 let mut hops = Vec::with_capacity(3);
1231 hops.push(RouteHop {
1232 pubkey: nodes[3].node.get_our_node_id(),
1233 node_features: NodeFeatures::empty(),
1234 short_channel_id: chan_4.0.contents.short_channel_id,
1235 channel_features: ChannelFeatures::empty(),
1237 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1239 hops.push(RouteHop {
1240 pubkey: nodes[2].node.get_our_node_id(),
1241 node_features: NodeFeatures::empty(),
1242 short_channel_id: chan_3.0.contents.short_channel_id,
1243 channel_features: ChannelFeatures::empty(),
1245 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1247 hops.push(RouteHop {
1248 pubkey: nodes[1].node.get_our_node_id(),
1249 node_features: NodeFeatures::empty(),
1250 short_channel_id: chan_2.0.contents.short_channel_id,
1251 channel_features: ChannelFeatures::empty(),
1253 cltv_expiry_delta: TEST_FINAL_CLTV,
1255 hops[1].fee_msat = chan_2.1.contents.fee_base_msat as u64 + chan_2.1.contents.fee_proportional_millionths as u64 * hops[2].fee_msat as u64 / 1000000;
1256 hops[0].fee_msat = chan_3.1.contents.fee_base_msat as u64 + chan_3.1.contents.fee_proportional_millionths as u64 * hops[1].fee_msat as u64 / 1000000;
1257 let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1259 // Claim the rebalances...
1260 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1261 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1263 // Add a duplicate new channel from 2 to 4
1264 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1266 // Send some payments across both channels
1267 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1268 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1269 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1272 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1273 let events = nodes[0].node.get_and_clear_pending_msg_events();
1274 assert_eq!(events.len(), 0);
1275 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1277 //TODO: Test that routes work again here as we've been notified that the channel is full
1279 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1280 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1281 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1283 // Close down the channels...
1284 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1285 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1286 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1287 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1288 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1292 fn holding_cell_htlc_counting() {
1293 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1294 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1295 // commitment dance rounds.
1296 let chanmon_cfgs = create_chanmon_cfgs(3);
1297 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1298 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1299 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1300 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1301 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1302 let logger = Arc::new(test_utils::TestLogger::new());
1304 let mut payments = Vec::new();
1305 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1306 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1307 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1308 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1309 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1310 payments.push((payment_preimage, payment_hash));
1312 check_added_monitors!(nodes[1], 1);
1314 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1315 assert_eq!(events.len(), 1);
1316 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1317 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1319 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1320 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1322 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1324 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1325 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1326 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { err },
1327 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
1328 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1329 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1332 // This should also be true if we try to forward a payment.
1333 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1335 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1336 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1337 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1338 check_added_monitors!(nodes[0], 1);
1341 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1342 assert_eq!(events.len(), 1);
1343 let payment_event = SendEvent::from_event(events.pop().unwrap());
1344 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1346 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1347 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1348 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1349 // fails), the second will process the resulting failure and fail the HTLC backward.
1350 expect_pending_htlcs_forwardable!(nodes[1]);
1351 expect_pending_htlcs_forwardable!(nodes[1]);
1352 check_added_monitors!(nodes[1], 1);
1354 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1355 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1356 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1358 let events = nodes[0].node.get_and_clear_pending_msg_events();
1359 assert_eq!(events.len(), 1);
1361 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1362 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1364 _ => panic!("Unexpected event"),
1367 expect_payment_failed!(nodes[0], payment_hash_2, false);
1369 // Now forward all the pending HTLCs and claim them back
1370 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1371 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1372 check_added_monitors!(nodes[2], 1);
1374 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1375 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1376 check_added_monitors!(nodes[1], 1);
1377 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1379 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1380 check_added_monitors!(nodes[1], 1);
1381 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1383 for ref update in as_updates.update_add_htlcs.iter() {
1384 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1386 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1387 check_added_monitors!(nodes[2], 1);
1388 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1389 check_added_monitors!(nodes[2], 1);
1390 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1392 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1393 check_added_monitors!(nodes[1], 1);
1394 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1395 check_added_monitors!(nodes[1], 1);
1396 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1398 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1399 check_added_monitors!(nodes[2], 1);
1401 expect_pending_htlcs_forwardable!(nodes[2]);
1403 let events = nodes[2].node.get_and_clear_pending_events();
1404 assert_eq!(events.len(), payments.len());
1405 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1407 &Event::PaymentReceived { ref payment_hash, .. } => {
1408 assert_eq!(*payment_hash, *hash);
1410 _ => panic!("Unexpected event"),
1414 for (preimage, _) in payments.drain(..) {
1415 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1418 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1422 fn duplicate_htlc_test() {
1423 // Test that we accept duplicate payment_hash HTLCs across the network and that
1424 // claiming/failing them are all separate and don't affect each other
1425 let chanmon_cfgs = create_chanmon_cfgs(6);
1426 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1427 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1428 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1430 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1431 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1432 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1433 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1434 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1435 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1437 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1439 *nodes[0].network_payment_count.borrow_mut() -= 1;
1440 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1442 *nodes[0].network_payment_count.borrow_mut() -= 1;
1443 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1445 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1446 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1447 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1451 fn test_duplicate_htlc_different_direction_onchain() {
1452 // Test that ChannelMonitor doesn't generate 2 preimage txn
1453 // when we have 2 HTLCs with same preimage that go across a node
1454 // in opposite directions.
1455 let chanmon_cfgs = create_chanmon_cfgs(2);
1456 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1457 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1458 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1460 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1461 let logger = Arc::new(test_utils::TestLogger::new());
1464 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1466 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1468 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1469 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1470 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1472 // Provide preimage to node 0 by claiming payment
1473 nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1474 check_added_monitors!(nodes[0], 1);
1476 // Broadcast node 1 commitment txn
1477 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1479 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1480 let mut has_both_htlcs = 0; // check htlcs match ones committed
1481 for outp in remote_txn[0].output.iter() {
1482 if outp.value == 800_000 / 1000 {
1483 has_both_htlcs += 1;
1484 } else if outp.value == 900_000 / 1000 {
1485 has_both_htlcs += 1;
1488 assert_eq!(has_both_htlcs, 2);
1490 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1491 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1492 check_added_monitors!(nodes[0], 1);
1494 // Check we only broadcast 1 timeout tx
1495 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1496 let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1497 assert_eq!(claim_txn.len(), 5);
1498 check_spends!(claim_txn[2], chan_1.3);
1499 check_spends!(claim_txn[3], claim_txn[2]);
1500 assert_eq!(htlc_pair.0.input.len(), 1);
1501 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1502 check_spends!(htlc_pair.0, remote_txn[0]);
1503 assert_eq!(htlc_pair.1.input.len(), 1);
1504 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1505 check_spends!(htlc_pair.1, remote_txn[0]);
1507 let events = nodes[0].node.get_and_clear_pending_msg_events();
1508 assert_eq!(events.len(), 2);
1511 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1512 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1513 assert!(update_add_htlcs.is_empty());
1514 assert!(update_fail_htlcs.is_empty());
1515 assert_eq!(update_fulfill_htlcs.len(), 1);
1516 assert!(update_fail_malformed_htlcs.is_empty());
1517 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1519 _ => panic!("Unexpected event"),
1524 fn do_channel_reserve_test(test_recv: bool) {
1526 let chanmon_cfgs = create_chanmon_cfgs(3);
1527 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1528 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1529 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1530 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1531 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1532 let logger = Arc::new(test_utils::TestLogger::new());
1534 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1535 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1537 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1538 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1540 macro_rules! get_route_and_payment_hash {
1541 ($recv_value: expr) => {{
1542 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1543 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1544 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, logger.clone()).unwrap();
1545 (route, payment_hash, payment_preimage)
1549 macro_rules! expect_forward {
1551 let mut events = $node.node.get_and_clear_pending_msg_events();
1552 assert_eq!(events.len(), 1);
1553 check_added_monitors!($node, 1);
1554 let payment_event = SendEvent::from_event(events.remove(0));
1559 let feemsat = 239; // somehow we know?
1560 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1562 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1564 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1566 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1567 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1568 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1569 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
1570 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1571 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1574 let mut htlc_id = 0;
1575 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1576 // nodes[0]'s wealth
1578 let amt_msat = recv_value_0 + total_fee_msat;
1579 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1582 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1585 let (stat01_, stat11_, stat12_, stat22_) = (
1586 get_channel_value_stat!(nodes[0], chan_1.2),
1587 get_channel_value_stat!(nodes[1], chan_1.2),
1588 get_channel_value_stat!(nodes[1], chan_2.2),
1589 get_channel_value_stat!(nodes[2], chan_2.2),
1592 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1593 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1594 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1595 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1596 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1600 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1601 // attempt to get channel_reserve violation
1602 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1603 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1604 assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1605 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1606 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 1);
1609 // adding pending output
1610 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1611 let amt_msat_1 = recv_value_1 + total_fee_msat;
1613 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1614 let payment_event_1 = {
1615 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1616 check_added_monitors!(nodes[0], 1);
1618 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1619 assert_eq!(events.len(), 1);
1620 SendEvent::from_event(events.remove(0))
1622 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1624 // channel reserve test with htlc pending output > 0
1625 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1627 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1628 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1629 assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1630 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1631 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 2);
1635 // test channel_reserve test on nodes[1] side
1636 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1638 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1639 let secp_ctx = Secp256k1::new();
1640 let session_priv = SecretKey::from_slice(&{
1641 let mut session_key = [0; 32];
1642 let mut rng = thread_rng();
1643 rng.fill_bytes(&mut session_key);
1645 }).expect("RNG is bad!");
1647 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1648 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1649 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], recv_value_2 + 1, &None, cur_height).unwrap();
1650 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1651 let msg = msgs::UpdateAddHTLC {
1652 channel_id: chan_1.2,
1654 amount_msat: htlc_msat,
1655 payment_hash: our_payment_hash,
1656 cltv_expiry: htlc_cltv,
1657 onion_routing_packet: onion_packet,
1661 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1662 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1663 assert_eq!(nodes[1].node.list_channels().len(), 1);
1664 assert_eq!(nodes[1].node.list_channels().len(), 1);
1665 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1666 assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
1667 check_added_monitors!(nodes[1], 1);
1672 // split the rest to test holding cell
1673 let recv_value_21 = recv_value_2/2;
1674 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1676 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1677 assert_eq!(stat.value_to_self_msat - (stat.pending_outbound_htlcs_amount_msat + recv_value_21 + recv_value_22 + total_fee_msat + total_fee_msat), stat.channel_reserve_msat);
1680 // now see if they go through on both sides
1681 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1682 // but this will stuck in the holding cell
1683 nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
1684 check_added_monitors!(nodes[0], 0);
1685 let events = nodes[0].node.get_and_clear_pending_events();
1686 assert_eq!(events.len(), 0);
1688 // test with outbound holding cell amount > 0
1690 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1691 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1692 assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1693 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1694 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 3);
1697 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1698 // this will also stuck in the holding cell
1699 nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
1700 check_added_monitors!(nodes[0], 0);
1701 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1702 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1704 // flush the pending htlc
1705 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1706 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1707 check_added_monitors!(nodes[1], 1);
1709 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1710 check_added_monitors!(nodes[0], 1);
1711 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1713 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1714 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1715 // No commitment_signed so get_event_msg's assert(len == 1) passes
1716 check_added_monitors!(nodes[0], 1);
1718 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1719 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1720 check_added_monitors!(nodes[1], 1);
1722 expect_pending_htlcs_forwardable!(nodes[1]);
1724 let ref payment_event_11 = expect_forward!(nodes[1]);
1725 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1726 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1728 expect_pending_htlcs_forwardable!(nodes[2]);
1729 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1731 // flush the htlcs in the holding cell
1732 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1733 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1734 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1735 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1736 expect_pending_htlcs_forwardable!(nodes[1]);
1738 let ref payment_event_3 = expect_forward!(nodes[1]);
1739 assert_eq!(payment_event_3.msgs.len(), 2);
1740 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1741 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1743 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1744 expect_pending_htlcs_forwardable!(nodes[2]);
1746 let events = nodes[2].node.get_and_clear_pending_events();
1747 assert_eq!(events.len(), 2);
1749 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1750 assert_eq!(our_payment_hash_21, *payment_hash);
1751 assert_eq!(*payment_secret, None);
1752 assert_eq!(recv_value_21, amt);
1754 _ => panic!("Unexpected event"),
1757 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1758 assert_eq!(our_payment_hash_22, *payment_hash);
1759 assert_eq!(None, *payment_secret);
1760 assert_eq!(recv_value_22, amt);
1762 _ => panic!("Unexpected event"),
1765 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1766 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1767 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1769 let expected_value_to_self = stat01.value_to_self_msat - (recv_value_1 + total_fee_msat) - (recv_value_21 + total_fee_msat) - (recv_value_22 + total_fee_msat);
1770 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1771 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1772 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1774 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1775 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1779 fn channel_reserve_test() {
1780 do_channel_reserve_test(false);
1781 do_channel_reserve_test(true);
1785 fn channel_reserve_in_flight_removes() {
1786 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1787 // can send to its counterparty, but due to update ordering, the other side may not yet have
1788 // considered those HTLCs fully removed.
1789 // This tests that we don't count HTLCs which will not be included in the next remote
1790 // commitment transaction towards the reserve value (as it implies no commitment transaction
1791 // will be generated which violates the remote reserve value).
1792 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1794 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1795 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1796 // you only consider the value of the first HTLC, it may not),
1797 // * start routing a third HTLC from A to B,
1798 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1799 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1800 // * deliver the first fulfill from B
1801 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1803 // * deliver A's response CS and RAA.
1804 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1805 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1806 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1807 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1808 let chanmon_cfgs = create_chanmon_cfgs(2);
1809 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1810 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1811 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1812 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1813 let logger = Arc::new(test_utils::TestLogger::new());
1815 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1816 // Route the first two HTLCs.
1817 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1818 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1820 // Start routing the third HTLC (this is just used to get everyone in the right state).
1821 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1823 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1824 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1825 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
1826 check_added_monitors!(nodes[0], 1);
1827 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1828 assert_eq!(events.len(), 1);
1829 SendEvent::from_event(events.remove(0))
1832 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1833 // initial fulfill/CS.
1834 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1835 check_added_monitors!(nodes[1], 1);
1836 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1838 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1839 // remove the second HTLC when we send the HTLC back from B to A.
1840 assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
1841 check_added_monitors!(nodes[1], 1);
1842 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1844 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1845 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1846 check_added_monitors!(nodes[0], 1);
1847 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1848 expect_payment_sent!(nodes[0], payment_preimage_1);
1850 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1851 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1852 check_added_monitors!(nodes[1], 1);
1853 // B is already AwaitingRAA, so cant generate a CS here
1854 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1856 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1857 check_added_monitors!(nodes[1], 1);
1858 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1860 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1861 check_added_monitors!(nodes[0], 1);
1862 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1864 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1865 check_added_monitors!(nodes[1], 1);
1866 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1868 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1869 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1870 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1871 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1872 // on-chain as necessary).
1873 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1874 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1875 check_added_monitors!(nodes[0], 1);
1876 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1877 expect_payment_sent!(nodes[0], payment_preimage_2);
1879 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1880 check_added_monitors!(nodes[1], 1);
1881 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1883 expect_pending_htlcs_forwardable!(nodes[1]);
1884 expect_payment_received!(nodes[1], payment_hash_3, 100000);
1886 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1887 // resolve the second HTLC from A's point of view.
1888 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1889 check_added_monitors!(nodes[0], 1);
1890 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1892 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1893 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1894 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1896 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1897 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV, logger.clone()).unwrap();
1898 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
1899 check_added_monitors!(nodes[1], 1);
1900 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1901 assert_eq!(events.len(), 1);
1902 SendEvent::from_event(events.remove(0))
1905 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1906 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1907 check_added_monitors!(nodes[0], 1);
1908 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1910 // Now just resolve all the outstanding messages/HTLCs for completeness...
1912 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1913 check_added_monitors!(nodes[1], 1);
1914 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1916 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1917 check_added_monitors!(nodes[1], 1);
1919 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1920 check_added_monitors!(nodes[0], 1);
1921 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1923 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1924 check_added_monitors!(nodes[1], 1);
1925 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1927 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1928 check_added_monitors!(nodes[0], 1);
1930 expect_pending_htlcs_forwardable!(nodes[0]);
1931 expect_payment_received!(nodes[0], payment_hash_4, 10000);
1933 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1934 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1938 fn channel_monitor_network_test() {
1939 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1940 // tests that ChannelMonitor is able to recover from various states.
1941 let chanmon_cfgs = create_chanmon_cfgs(5);
1942 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1943 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1944 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1946 // Create some initial channels
1947 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1948 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1949 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1950 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1952 // Rebalance the network a bit by relaying one payment through all the channels...
1953 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1954 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1955 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1956 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1958 // Simple case with no pending HTLCs:
1959 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1960 check_added_monitors!(nodes[1], 1);
1962 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1963 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1964 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1965 check_added_monitors!(nodes[0], 1);
1966 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1968 get_announce_close_broadcast_events(&nodes, 0, 1);
1969 assert_eq!(nodes[0].node.list_channels().len(), 0);
1970 assert_eq!(nodes[1].node.list_channels().len(), 1);
1972 // One pending HTLC is discarded by the force-close:
1973 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1975 // Simple case of one pending HTLC to HTLC-Timeout
1976 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1977 check_added_monitors!(nodes[1], 1);
1979 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1980 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1981 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1982 check_added_monitors!(nodes[2], 1);
1983 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1985 get_announce_close_broadcast_events(&nodes, 1, 2);
1986 assert_eq!(nodes[1].node.list_channels().len(), 0);
1987 assert_eq!(nodes[2].node.list_channels().len(), 1);
1989 macro_rules! claim_funds {
1990 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1992 assert!($node.node.claim_funds($preimage, &None, $amount));
1993 check_added_monitors!($node, 1);
1995 let events = $node.node.get_and_clear_pending_msg_events();
1996 assert_eq!(events.len(), 1);
1998 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1999 assert!(update_add_htlcs.is_empty());
2000 assert!(update_fail_htlcs.is_empty());
2001 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2003 _ => panic!("Unexpected event"),
2009 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2010 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2011 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2012 check_added_monitors!(nodes[2], 1);
2013 let node2_commitment_txid;
2015 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2016 node2_commitment_txid = node_txn[0].txid();
2018 // Claim the payment on nodes[3], giving it knowledge of the preimage
2019 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2021 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2022 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2023 check_added_monitors!(nodes[3], 1);
2025 check_preimage_claim(&nodes[3], &node_txn);
2027 get_announce_close_broadcast_events(&nodes, 2, 3);
2028 assert_eq!(nodes[2].node.list_channels().len(), 0);
2029 assert_eq!(nodes[3].node.list_channels().len(), 1);
2031 { // Cheat and reset nodes[4]'s height to 1
2032 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2033 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2036 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2037 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2038 // One pending HTLC to time out:
2039 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2040 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2044 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2045 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2046 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2047 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2048 nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2050 check_added_monitors!(nodes[3], 1);
2052 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2054 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2055 node_txn.retain(|tx| {
2056 if tx.input[0].previous_output.txid == node2_commitment_txid {
2062 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2064 // Claim the payment on nodes[4], giving it knowledge of the preimage
2065 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2067 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2069 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2070 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2071 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2072 nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2075 check_added_monitors!(nodes[4], 1);
2076 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2078 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2079 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2081 check_preimage_claim(&nodes[4], &node_txn);
2083 get_announce_close_broadcast_events(&nodes, 3, 4);
2084 assert_eq!(nodes[3].node.list_channels().len(), 0);
2085 assert_eq!(nodes[4].node.list_channels().len(), 0);
2089 fn test_justice_tx() {
2090 // Test justice txn built on revoked HTLC-Success tx, against both sides
2091 let mut alice_config = UserConfig::default();
2092 alice_config.channel_options.announced_channel = true;
2093 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2094 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2095 let mut bob_config = UserConfig::default();
2096 bob_config.channel_options.announced_channel = true;
2097 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2098 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2099 let user_cfgs = [Some(alice_config), Some(bob_config)];
2100 let chanmon_cfgs = create_chanmon_cfgs(2);
2101 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2102 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2103 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2104 // Create some new channels:
2105 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2107 // A pending HTLC which will be revoked:
2108 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2109 // Get the will-be-revoked local txn from nodes[0]
2110 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2111 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2112 assert_eq!(revoked_local_txn[0].input.len(), 1);
2113 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2114 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2115 assert_eq!(revoked_local_txn[1].input.len(), 1);
2116 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2117 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2118 // Revoke the old state
2119 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2122 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2123 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2125 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2126 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2127 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2129 check_spends!(node_txn[0], revoked_local_txn[0]);
2130 node_txn.swap_remove(0);
2131 node_txn.truncate(1);
2133 check_added_monitors!(nodes[1], 1);
2134 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2136 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2137 // Verify broadcast of revoked HTLC-timeout
2138 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2139 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2140 check_added_monitors!(nodes[0], 1);
2141 // Broadcast revoked HTLC-timeout on node 1
2142 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2143 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2145 get_announce_close_broadcast_events(&nodes, 0, 1);
2147 assert_eq!(nodes[0].node.list_channels().len(), 0);
2148 assert_eq!(nodes[1].node.list_channels().len(), 0);
2150 // We test justice_tx build by A on B's revoked HTLC-Success tx
2151 // Create some new channels:
2152 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2154 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2158 // A pending HTLC which will be revoked:
2159 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2160 // Get the will-be-revoked local txn from B
2161 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2162 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2163 assert_eq!(revoked_local_txn[0].input.len(), 1);
2164 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2165 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2166 // Revoke the old state
2167 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2169 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2170 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2172 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2173 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2174 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2176 check_spends!(node_txn[0], revoked_local_txn[0]);
2177 node_txn.swap_remove(0);
2179 check_added_monitors!(nodes[0], 1);
2180 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2182 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2183 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2184 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2185 check_added_monitors!(nodes[1], 1);
2186 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2187 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2189 get_announce_close_broadcast_events(&nodes, 0, 1);
2190 assert_eq!(nodes[0].node.list_channels().len(), 0);
2191 assert_eq!(nodes[1].node.list_channels().len(), 0);
2195 fn revoked_output_claim() {
2196 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2197 // transaction is broadcast by its counterparty
2198 let chanmon_cfgs = create_chanmon_cfgs(2);
2199 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2200 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2201 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2202 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2203 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2204 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2205 assert_eq!(revoked_local_txn.len(), 1);
2206 // Only output is the full channel value back to nodes[0]:
2207 assert_eq!(revoked_local_txn[0].output.len(), 1);
2208 // Send a payment through, updating everyone's latest commitment txn
2209 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2211 // Inform nodes[1] that nodes[0] broadcast a stale tx
2212 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2213 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2214 check_added_monitors!(nodes[1], 1);
2215 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2216 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2218 check_spends!(node_txn[0], revoked_local_txn[0]);
2219 check_spends!(node_txn[1], chan_1.3);
2221 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2222 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2223 get_announce_close_broadcast_events(&nodes, 0, 1);
2224 check_added_monitors!(nodes[0], 1)
2228 fn claim_htlc_outputs_shared_tx() {
2229 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2230 let chanmon_cfgs = create_chanmon_cfgs(2);
2231 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2232 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2233 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2235 // Create some new channel:
2236 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2238 // Rebalance the network to generate htlc in the two directions
2239 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2240 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx
2241 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2242 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2244 // Get the will-be-revoked local txn from node[0]
2245 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2246 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2247 assert_eq!(revoked_local_txn[0].input.len(), 1);
2248 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2249 assert_eq!(revoked_local_txn[1].input.len(), 1);
2250 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2251 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2252 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2254 //Revoke the old state
2255 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2258 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2259 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2260 check_added_monitors!(nodes[0], 1);
2261 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2262 check_added_monitors!(nodes[1], 1);
2263 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2264 expect_payment_failed!(nodes[1], payment_hash_2, true);
2266 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2267 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2269 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2270 check_spends!(node_txn[0], revoked_local_txn[0]);
2272 let mut witness_lens = BTreeSet::new();
2273 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2274 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2275 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2276 assert_eq!(witness_lens.len(), 3);
2277 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2278 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2279 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2281 // Next nodes[1] broadcasts its current local tx state:
2282 assert_eq!(node_txn[1].input.len(), 1);
2283 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2285 assert_eq!(node_txn[2].input.len(), 1);
2286 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2287 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2288 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2289 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2290 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2292 get_announce_close_broadcast_events(&nodes, 0, 1);
2293 assert_eq!(nodes[0].node.list_channels().len(), 0);
2294 assert_eq!(nodes[1].node.list_channels().len(), 0);
2298 fn claim_htlc_outputs_single_tx() {
2299 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2300 let chanmon_cfgs = create_chanmon_cfgs(2);
2301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2303 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2305 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2307 // Rebalance the network to generate htlc in the two directions
2308 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2309 // node[0] is gonna to revoke an old state thus node[1] should be able to claim both offered/received HTLC outputs on top of commitment tx, but this
2310 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2311 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2312 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2314 // Get the will-be-revoked local txn from node[0]
2315 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2317 //Revoke the old state
2318 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2321 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2322 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2323 check_added_monitors!(nodes[0], 1);
2324 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2325 check_added_monitors!(nodes[1], 1);
2326 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2328 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2329 expect_payment_failed!(nodes[1], payment_hash_2, true);
2331 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2332 assert_eq!(node_txn.len(), 9);
2333 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2334 // ChannelManager: local commmitment + local HTLC-timeout (2)
2335 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2336 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2338 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2339 assert_eq!(node_txn[2].input.len(), 1);
2340 check_spends!(node_txn[2], chan_1.3);
2341 assert_eq!(node_txn[3].input.len(), 1);
2342 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2343 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2344 check_spends!(node_txn[3], node_txn[2]);
2346 // Justice transactions are indices 1-2-4
2347 assert_eq!(node_txn[0].input.len(), 1);
2348 assert_eq!(node_txn[1].input.len(), 1);
2349 assert_eq!(node_txn[4].input.len(), 1);
2351 check_spends!(node_txn[0], revoked_local_txn[0]);
2352 check_spends!(node_txn[1], revoked_local_txn[0]);
2353 check_spends!(node_txn[4], revoked_local_txn[0]);
2355 let mut witness_lens = BTreeSet::new();
2356 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2357 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2358 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2359 assert_eq!(witness_lens.len(), 3);
2360 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2361 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2362 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2364 get_announce_close_broadcast_events(&nodes, 0, 1);
2365 assert_eq!(nodes[0].node.list_channels().len(), 0);
2366 assert_eq!(nodes[1].node.list_channels().len(), 0);
2370 fn test_htlc_on_chain_success() {
2371 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2372 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2373 // broadcasting the right event to other nodes in payment path.
2374 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2375 // A --------------------> B ----------------------> C (preimage)
2376 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2377 // commitment transaction was broadcast.
2378 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2380 // B should be able to claim via preimage if A then broadcasts its local tx.
2381 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2382 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2383 // PaymentSent event).
2385 let chanmon_cfgs = create_chanmon_cfgs(3);
2386 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2387 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2388 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2390 // Create some initial channels
2391 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2392 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2394 // Rebalance the network a bit by relaying one payment through all the channels...
2395 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2396 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2398 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2399 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2400 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2402 // Broadcast legit commitment tx from C on B's chain
2403 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2404 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2405 assert_eq!(commitment_tx.len(), 1);
2406 check_spends!(commitment_tx[0], chan_2.3);
2407 nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2408 nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2409 check_added_monitors!(nodes[2], 2);
2410 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2411 assert!(updates.update_add_htlcs.is_empty());
2412 assert!(updates.update_fail_htlcs.is_empty());
2413 assert!(updates.update_fail_malformed_htlcs.is_empty());
2414 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2416 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2417 check_closed_broadcast!(nodes[2], false);
2418 check_added_monitors!(nodes[2], 1);
2419 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2420 assert_eq!(node_txn.len(), 5);
2421 assert_eq!(node_txn[0], node_txn[3]);
2422 assert_eq!(node_txn[1], node_txn[4]);
2423 assert_eq!(node_txn[2], commitment_tx[0]);
2424 check_spends!(node_txn[0], commitment_tx[0]);
2425 check_spends!(node_txn[1], commitment_tx[0]);
2426 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2427 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2428 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2429 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2430 assert_eq!(node_txn[0].lock_time, 0);
2431 assert_eq!(node_txn[1].lock_time, 0);
2433 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2434 nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2436 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2437 assert_eq!(added_monitors.len(), 1);
2438 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2439 added_monitors.clear();
2441 let events = nodes[1].node.get_and_clear_pending_msg_events();
2443 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2444 assert_eq!(added_monitors.len(), 2);
2445 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2446 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2447 added_monitors.clear();
2449 assert_eq!(events.len(), 2);
2451 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2452 _ => panic!("Unexpected event"),
2455 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2456 assert!(update_add_htlcs.is_empty());
2457 assert!(update_fail_htlcs.is_empty());
2458 assert_eq!(update_fulfill_htlcs.len(), 1);
2459 assert!(update_fail_malformed_htlcs.is_empty());
2460 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2462 _ => panic!("Unexpected event"),
2464 macro_rules! check_tx_local_broadcast {
2465 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2466 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2467 assert_eq!(node_txn.len(), 5);
2468 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2469 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2470 check_spends!(node_txn[0], $commitment_tx);
2471 check_spends!(node_txn[1], $commitment_tx);
2472 assert_ne!(node_txn[0].lock_time, 0);
2473 assert_ne!(node_txn[1].lock_time, 0);
2475 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2476 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2477 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2478 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2480 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2481 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2482 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2483 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2485 check_spends!(node_txn[2], $chan_tx);
2486 check_spends!(node_txn[3], node_txn[2]);
2487 check_spends!(node_txn[4], node_txn[2]);
2488 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2489 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2490 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2491 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2492 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2493 assert_ne!(node_txn[3].lock_time, 0);
2494 assert_ne!(node_txn[4].lock_time, 0);
2498 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2499 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2500 // timeout-claim of the output that nodes[2] just claimed via success.
2501 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2503 // Broadcast legit commitment tx from A on B's chain
2504 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2505 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2506 check_spends!(commitment_tx[0], chan_1.3);
2507 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2508 check_closed_broadcast!(nodes[1], false);
2509 check_added_monitors!(nodes[1], 1);
2510 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2511 assert_eq!(node_txn.len(), 4);
2512 check_spends!(node_txn[0], commitment_tx[0]);
2513 assert_eq!(node_txn[0].input.len(), 2);
2514 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2515 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2516 assert_eq!(node_txn[0].lock_time, 0);
2517 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2518 check_spends!(node_txn[1], chan_1.3);
2519 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2520 check_spends!(node_txn[2], node_txn[1]);
2521 check_spends!(node_txn[3], node_txn[1]);
2522 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2523 // we already checked the same situation with A.
2525 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2526 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2527 check_closed_broadcast!(nodes[0], false);
2528 check_added_monitors!(nodes[0], 1);
2529 let events = nodes[0].node.get_and_clear_pending_events();
2530 assert_eq!(events.len(), 2);
2531 let mut first_claimed = false;
2532 for event in events {
2534 Event::PaymentSent { payment_preimage } => {
2535 if payment_preimage == our_payment_preimage {
2536 assert!(!first_claimed);
2537 first_claimed = true;
2539 assert_eq!(payment_preimage, our_payment_preimage_2);
2542 _ => panic!("Unexpected event"),
2545 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2549 fn test_htlc_on_chain_timeout() {
2550 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2551 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2552 // broadcasting the right event to other nodes in payment path.
2553 // A ------------------> B ----------------------> C (timeout)
2554 // B's commitment tx C's commitment tx
2556 // B's HTLC timeout tx B's timeout tx
2558 let chanmon_cfgs = create_chanmon_cfgs(3);
2559 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2560 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2561 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2563 // Create some intial channels
2564 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2565 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2567 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2568 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2569 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2571 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2572 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2574 // Broadcast legit commitment tx from C on B's chain
2575 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2576 check_spends!(commitment_tx[0], chan_2.3);
2577 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2578 check_added_monitors!(nodes[2], 0);
2579 expect_pending_htlcs_forwardable!(nodes[2]);
2580 check_added_monitors!(nodes[2], 1);
2582 let events = nodes[2].node.get_and_clear_pending_msg_events();
2583 assert_eq!(events.len(), 1);
2585 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2586 assert!(update_add_htlcs.is_empty());
2587 assert!(!update_fail_htlcs.is_empty());
2588 assert!(update_fulfill_htlcs.is_empty());
2589 assert!(update_fail_malformed_htlcs.is_empty());
2590 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2592 _ => panic!("Unexpected event"),
2594 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2595 check_closed_broadcast!(nodes[2], false);
2596 check_added_monitors!(nodes[2], 1);
2597 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2598 assert_eq!(node_txn.len(), 1);
2599 check_spends!(node_txn[0], chan_2.3);
2600 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2602 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2603 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2604 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2607 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2608 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2609 assert_eq!(node_txn[1], node_txn[3]);
2610 assert_eq!(node_txn[2], node_txn[4]);
2612 check_spends!(node_txn[0], commitment_tx[0]);
2613 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2615 check_spends!(node_txn[1], chan_2.3);
2616 check_spends!(node_txn[2], node_txn[1]);
2617 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2618 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2620 timeout_tx = node_txn[0].clone();
2624 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2625 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2626 check_added_monitors!(nodes[1], 1);
2627 check_closed_broadcast!(nodes[1], false);
2629 expect_pending_htlcs_forwardable!(nodes[1]);
2630 check_added_monitors!(nodes[1], 1);
2631 let events = nodes[1].node.get_and_clear_pending_msg_events();
2632 assert_eq!(events.len(), 1);
2634 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2635 assert!(update_add_htlcs.is_empty());
2636 assert!(!update_fail_htlcs.is_empty());
2637 assert!(update_fulfill_htlcs.is_empty());
2638 assert!(update_fail_malformed_htlcs.is_empty());
2639 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2641 _ => panic!("Unexpected event"),
2643 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // Well... here we detect our own htlc_timeout_tx so no tx to be generated
2644 assert_eq!(node_txn.len(), 0);
2646 // Broadcast legit commitment tx from B on A's chain
2647 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2648 check_spends!(commitment_tx[0], chan_1.3);
2650 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2651 check_closed_broadcast!(nodes[0], false);
2652 check_added_monitors!(nodes[0], 1);
2653 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2654 assert_eq!(node_txn.len(), 3);
2655 check_spends!(node_txn[0], commitment_tx[0]);
2656 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2657 check_spends!(node_txn[1], chan_1.3);
2658 check_spends!(node_txn[2], node_txn[1]);
2659 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2660 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2664 fn test_simple_commitment_revoked_fail_backward() {
2665 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2666 // and fail backward accordingly.
2668 let chanmon_cfgs = create_chanmon_cfgs(3);
2669 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2670 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2671 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2673 // Create some initial channels
2674 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2675 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2677 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2678 // Get the will-be-revoked local txn from nodes[2]
2679 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2680 // Revoke the old state
2681 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2683 let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2685 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2686 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2687 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2688 check_added_monitors!(nodes[1], 1);
2689 check_closed_broadcast!(nodes[1], false);
2691 expect_pending_htlcs_forwardable!(nodes[1]);
2692 check_added_monitors!(nodes[1], 1);
2693 let events = nodes[1].node.get_and_clear_pending_msg_events();
2694 assert_eq!(events.len(), 1);
2696 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
2697 assert!(update_add_htlcs.is_empty());
2698 assert_eq!(update_fail_htlcs.len(), 1);
2699 assert!(update_fulfill_htlcs.is_empty());
2700 assert!(update_fail_malformed_htlcs.is_empty());
2701 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2703 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2704 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2706 let events = nodes[0].node.get_and_clear_pending_msg_events();
2707 assert_eq!(events.len(), 1);
2709 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2710 _ => panic!("Unexpected event"),
2712 expect_payment_failed!(nodes[0], payment_hash, false);
2714 _ => panic!("Unexpected event"),
2718 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2719 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2720 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2721 // commitment transaction anymore.
2722 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2723 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2724 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2725 // technically disallowed and we should probably handle it reasonably.
2726 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2727 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2729 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2730 // commitment_signed (implying it will be in the latest remote commitment transaction).
2731 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2732 // and once they revoke the previous commitment transaction (allowing us to send a new
2733 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2734 let chanmon_cfgs = create_chanmon_cfgs(3);
2735 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2736 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2737 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2739 // Create some initial channels
2740 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2741 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2743 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2744 // Get the will-be-revoked local txn from nodes[2]
2745 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2746 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2747 // Revoke the old state
2748 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2750 let value = if use_dust {
2751 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2752 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2753 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2756 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2757 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2758 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2760 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
2761 expect_pending_htlcs_forwardable!(nodes[2]);
2762 check_added_monitors!(nodes[2], 1);
2763 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2764 assert!(updates.update_add_htlcs.is_empty());
2765 assert!(updates.update_fulfill_htlcs.is_empty());
2766 assert!(updates.update_fail_malformed_htlcs.is_empty());
2767 assert_eq!(updates.update_fail_htlcs.len(), 1);
2768 assert!(updates.update_fee.is_none());
2769 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2770 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2771 // Drop the last RAA from 3 -> 2
2773 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
2774 expect_pending_htlcs_forwardable!(nodes[2]);
2775 check_added_monitors!(nodes[2], 1);
2776 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2777 assert!(updates.update_add_htlcs.is_empty());
2778 assert!(updates.update_fulfill_htlcs.is_empty());
2779 assert!(updates.update_fail_malformed_htlcs.is_empty());
2780 assert_eq!(updates.update_fail_htlcs.len(), 1);
2781 assert!(updates.update_fee.is_none());
2782 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2783 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2784 check_added_monitors!(nodes[1], 1);
2785 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2786 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2787 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2788 check_added_monitors!(nodes[2], 1);
2790 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
2791 expect_pending_htlcs_forwardable!(nodes[2]);
2792 check_added_monitors!(nodes[2], 1);
2793 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2794 assert!(updates.update_add_htlcs.is_empty());
2795 assert!(updates.update_fulfill_htlcs.is_empty());
2796 assert!(updates.update_fail_malformed_htlcs.is_empty());
2797 assert_eq!(updates.update_fail_htlcs.len(), 1);
2798 assert!(updates.update_fee.is_none());
2799 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2800 // At this point first_payment_hash has dropped out of the latest two commitment
2801 // transactions that nodes[1] is tracking...
2802 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2803 check_added_monitors!(nodes[1], 1);
2804 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2805 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2806 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2807 check_added_monitors!(nodes[2], 1);
2809 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2810 // on nodes[2]'s RAA.
2811 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2812 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2813 let logger = Arc::new(test_utils::TestLogger::new());
2814 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
2815 nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
2816 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2817 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2818 check_added_monitors!(nodes[1], 0);
2821 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2822 // One monitor for the new revocation preimage, no second on as we won't generate a new
2823 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2824 check_added_monitors!(nodes[1], 1);
2825 let events = nodes[1].node.get_and_clear_pending_events();
2826 assert_eq!(events.len(), 1);
2828 Event::PendingHTLCsForwardable { .. } => { },
2829 _ => panic!("Unexpected event"),
2831 // Deliberately don't process the pending fail-back so they all fail back at once after
2832 // block connection just like the !deliver_bs_raa case
2835 let mut failed_htlcs = HashSet::new();
2836 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2838 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2839 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2840 check_added_monitors!(nodes[1], 1);
2841 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2843 let events = nodes[1].node.get_and_clear_pending_events();
2844 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2846 Event::PaymentFailed { ref payment_hash, .. } => {
2847 assert_eq!(*payment_hash, fourth_payment_hash);
2849 _ => panic!("Unexpected event"),
2851 if !deliver_bs_raa {
2853 Event::PendingHTLCsForwardable { .. } => { },
2854 _ => panic!("Unexpected event"),
2857 nodes[1].node.process_pending_htlc_forwards();
2858 check_added_monitors!(nodes[1], 1);
2860 let events = nodes[1].node.get_and_clear_pending_msg_events();
2861 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2862 match events[if deliver_bs_raa { 1 } else { 0 }] {
2863 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2864 _ => panic!("Unexpected event"),
2868 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, .. } } => {
2869 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2870 assert_eq!(update_add_htlcs.len(), 1);
2871 assert!(update_fulfill_htlcs.is_empty());
2872 assert!(update_fail_htlcs.is_empty());
2873 assert!(update_fail_malformed_htlcs.is_empty());
2875 _ => panic!("Unexpected event"),
2878 match events[if deliver_bs_raa { 2 } else { 1 }] {
2879 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, ref update_fulfill_htlcs, ref update_fail_malformed_htlcs, ref commitment_signed, .. } } => {
2880 assert!(update_add_htlcs.is_empty());
2881 assert_eq!(update_fail_htlcs.len(), 3);
2882 assert!(update_fulfill_htlcs.is_empty());
2883 assert!(update_fail_malformed_htlcs.is_empty());
2884 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2886 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2887 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2888 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2890 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2892 let events = nodes[0].node.get_and_clear_pending_msg_events();
2893 // If we delivered B's RAA we got an unknown preimage error, not something
2894 // that we should update our routing table for.
2895 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2896 for event in events {
2898 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2899 _ => panic!("Unexpected event"),
2902 let events = nodes[0].node.get_and_clear_pending_events();
2903 assert_eq!(events.len(), 3);
2905 Event::PaymentFailed { ref payment_hash, .. } => {
2906 assert!(failed_htlcs.insert(payment_hash.0));
2908 _ => panic!("Unexpected event"),
2911 Event::PaymentFailed { ref payment_hash, .. } => {
2912 assert!(failed_htlcs.insert(payment_hash.0));
2914 _ => panic!("Unexpected event"),
2917 Event::PaymentFailed { ref payment_hash, .. } => {
2918 assert!(failed_htlcs.insert(payment_hash.0));
2920 _ => panic!("Unexpected event"),
2923 _ => panic!("Unexpected event"),
2926 assert!(failed_htlcs.contains(&first_payment_hash.0));
2927 assert!(failed_htlcs.contains(&second_payment_hash.0));
2928 assert!(failed_htlcs.contains(&third_payment_hash.0));
2932 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2933 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2934 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2935 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2936 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2940 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2941 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2942 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2943 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2944 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2948 fn fail_backward_pending_htlc_upon_channel_failure() {
2949 let chanmon_cfgs = create_chanmon_cfgs(2);
2950 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2951 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2952 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2953 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
2954 let logger = Arc::new(test_utils::TestLogger::new());
2956 // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
2958 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
2959 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2960 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, logger.clone()).unwrap();
2961 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
2962 check_added_monitors!(nodes[0], 1);
2964 let payment_event = {
2965 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2966 assert_eq!(events.len(), 1);
2967 SendEvent::from_event(events.remove(0))
2969 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
2970 assert_eq!(payment_event.msgs.len(), 1);
2973 // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
2974 let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2976 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2977 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, logger.clone()).unwrap();
2978 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
2979 check_added_monitors!(nodes[0], 0);
2981 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2984 // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
2986 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
2988 let secp_ctx = Secp256k1::new();
2989 let session_priv = {
2990 let mut session_key = [0; 32];
2991 let mut rng = thread_rng();
2992 rng.fill_bytes(&mut session_key);
2993 SecretKey::from_slice(&session_key).expect("RNG is bad!")
2996 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
2997 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2998 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, logger.clone()).unwrap();
2999 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
3000 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3001 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3003 // Send a 0-msat update_add_htlc to fail the channel.
3004 let update_add_htlc = msgs::UpdateAddHTLC {
3010 onion_routing_packet,
3012 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3015 // Check that Alice fails backward the pending HTLC from the second payment.
3016 expect_payment_failed!(nodes[0], failed_payment_hash, true);
3017 check_closed_broadcast!(nodes[0], true);
3018 check_added_monitors!(nodes[0], 1);
3022 fn test_htlc_ignore_latest_remote_commitment() {
3023 // Test that HTLC transactions spending the latest remote commitment transaction are simply
3024 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3025 let chanmon_cfgs = create_chanmon_cfgs(2);
3026 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3027 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3028 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3029 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3031 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3032 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3033 check_closed_broadcast!(nodes[0], false);
3034 check_added_monitors!(nodes[0], 1);
3036 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3037 assert_eq!(node_txn.len(), 2);
3039 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3040 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3041 check_closed_broadcast!(nodes[1], false);
3042 check_added_monitors!(nodes[1], 1);
3044 // Duplicate the block_connected call since this may happen due to other listeners
3045 // registering new transactions
3046 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3050 fn test_force_close_fail_back() {
3051 // Check which HTLCs are failed-backwards on channel force-closure
3052 let chanmon_cfgs = create_chanmon_cfgs(3);
3053 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3054 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3055 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3056 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3057 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3058 let logger = Arc::new(test_utils::TestLogger::new());
3060 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3062 let mut payment_event = {
3063 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3064 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42, logger.clone()).unwrap();
3065 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3066 check_added_monitors!(nodes[0], 1);
3068 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3069 assert_eq!(events.len(), 1);
3070 SendEvent::from_event(events.remove(0))
3073 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3074 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3076 expect_pending_htlcs_forwardable!(nodes[1]);
3078 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3079 assert_eq!(events_2.len(), 1);
3080 payment_event = SendEvent::from_event(events_2.remove(0));
3081 assert_eq!(payment_event.msgs.len(), 1);
3083 check_added_monitors!(nodes[1], 1);
3084 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3085 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3086 check_added_monitors!(nodes[2], 1);
3087 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3089 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3090 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3091 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3093 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3094 check_closed_broadcast!(nodes[2], false);
3095 check_added_monitors!(nodes[2], 1);
3097 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3098 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3099 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3100 // back to nodes[1] upon timeout otherwise.
3101 assert_eq!(node_txn.len(), 1);
3105 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3106 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3108 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3109 check_closed_broadcast!(nodes[1], false);
3110 check_added_monitors!(nodes[1], 1);
3112 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3114 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3115 monitors.get_mut(&OutPoint::new(Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
3116 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3118 nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3119 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3120 assert_eq!(node_txn.len(), 1);
3121 assert_eq!(node_txn[0].input.len(), 1);
3122 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3123 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3124 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3126 check_spends!(node_txn[0], tx);
3130 fn test_unconf_chan() {
3131 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3132 let chanmon_cfgs = create_chanmon_cfgs(2);
3133 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3134 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3135 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3136 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3138 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3139 assert_eq!(channel_state.by_id.len(), 1);
3140 assert_eq!(channel_state.short_to_id.len(), 1);
3141 mem::drop(channel_state);
3143 let mut headers = Vec::new();
3144 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3145 headers.push(header.clone());
3147 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3148 headers.push(header.clone());
3150 let mut height = 99;
3151 while !headers.is_empty() {
3152 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3155 check_closed_broadcast!(nodes[0], false);
3156 check_added_monitors!(nodes[0], 1);
3157 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3158 assert_eq!(channel_state.by_id.len(), 0);
3159 assert_eq!(channel_state.short_to_id.len(), 0);
3163 fn test_simple_peer_disconnect() {
3164 // Test that we can reconnect when there are no lost messages
3165 let chanmon_cfgs = create_chanmon_cfgs(3);
3166 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3167 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3168 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3169 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3170 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3172 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3173 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3174 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3176 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3177 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3178 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3179 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3181 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3182 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3183 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3185 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3186 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3187 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3188 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3190 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3191 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3193 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3194 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3196 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3198 let events = nodes[0].node.get_and_clear_pending_events();
3199 assert_eq!(events.len(), 2);
3201 Event::PaymentSent { payment_preimage } => {
3202 assert_eq!(payment_preimage, payment_preimage_3);
3204 _ => panic!("Unexpected event"),
3207 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3208 assert_eq!(payment_hash, payment_hash_5);
3209 assert!(rejected_by_dest);
3211 _ => panic!("Unexpected event"),
3215 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3216 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3219 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3220 // Test that we can reconnect when in-flight HTLC updates get dropped
3221 let chanmon_cfgs = create_chanmon_cfgs(2);
3222 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3223 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3224 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3225 if messages_delivered == 0 {
3226 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3227 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3229 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3232 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3234 let logger = Arc::new(test_utils::TestLogger::new());
3235 let payment_event = {
3236 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3237 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3238 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3239 check_added_monitors!(nodes[0], 1);
3241 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3242 assert_eq!(events.len(), 1);
3243 SendEvent::from_event(events.remove(0))
3245 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3247 if messages_delivered < 2 {
3248 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3250 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3251 if messages_delivered >= 3 {
3252 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3253 check_added_monitors!(nodes[1], 1);
3254 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3256 if messages_delivered >= 4 {
3257 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3258 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3259 check_added_monitors!(nodes[0], 1);
3261 if messages_delivered >= 5 {
3262 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3263 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3264 // No commitment_signed so get_event_msg's assert(len == 1) passes
3265 check_added_monitors!(nodes[0], 1);
3267 if messages_delivered >= 6 {
3268 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3269 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3270 check_added_monitors!(nodes[1], 1);
3277 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3278 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3279 if messages_delivered < 3 {
3280 // Even if the funding_locked messages get exchanged, as long as nothing further was
3281 // received on either side, both sides will need to resend them.
3282 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3283 } else if messages_delivered == 3 {
3284 // nodes[0] still wants its RAA + commitment_signed
3285 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3286 } else if messages_delivered == 4 {
3287 // nodes[0] still wants its commitment_signed
3288 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3289 } else if messages_delivered == 5 {
3290 // nodes[1] still wants its final RAA
3291 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3292 } else if messages_delivered == 6 {
3293 // Everything was delivered...
3294 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3297 let events_1 = nodes[1].node.get_and_clear_pending_events();
3298 assert_eq!(events_1.len(), 1);
3300 Event::PendingHTLCsForwardable { .. } => { },
3301 _ => panic!("Unexpected event"),
3304 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3305 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3306 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3308 nodes[1].node.process_pending_htlc_forwards();
3310 let events_2 = nodes[1].node.get_and_clear_pending_events();
3311 assert_eq!(events_2.len(), 1);
3313 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3314 assert_eq!(payment_hash_1, *payment_hash);
3315 assert_eq!(*payment_secret, None);
3316 assert_eq!(amt, 1000000);
3318 _ => panic!("Unexpected event"),
3321 nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3322 check_added_monitors!(nodes[1], 1);
3324 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3325 assert_eq!(events_3.len(), 1);
3326 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3327 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3328 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3329 assert!(updates.update_add_htlcs.is_empty());
3330 assert!(updates.update_fail_htlcs.is_empty());
3331 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3332 assert!(updates.update_fail_malformed_htlcs.is_empty());
3333 assert!(updates.update_fee.is_none());
3334 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3336 _ => panic!("Unexpected event"),
3339 if messages_delivered >= 1 {
3340 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3342 let events_4 = nodes[0].node.get_and_clear_pending_events();
3343 assert_eq!(events_4.len(), 1);
3345 Event::PaymentSent { ref payment_preimage } => {
3346 assert_eq!(payment_preimage_1, *payment_preimage);
3348 _ => panic!("Unexpected event"),
3351 if messages_delivered >= 2 {
3352 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3353 check_added_monitors!(nodes[0], 1);
3354 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3356 if messages_delivered >= 3 {
3357 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3358 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3359 check_added_monitors!(nodes[1], 1);
3361 if messages_delivered >= 4 {
3362 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3363 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3364 // No commitment_signed so get_event_msg's assert(len == 1) passes
3365 check_added_monitors!(nodes[1], 1);
3367 if messages_delivered >= 5 {
3368 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3369 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3370 check_added_monitors!(nodes[0], 1);
3377 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3378 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3379 if messages_delivered < 2 {
3380 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3381 //TODO: Deduplicate PaymentSent events, then enable this if:
3382 //if messages_delivered < 1 {
3383 let events_4 = nodes[0].node.get_and_clear_pending_events();
3384 assert_eq!(events_4.len(), 1);
3386 Event::PaymentSent { ref payment_preimage } => {
3387 assert_eq!(payment_preimage_1, *payment_preimage);
3389 _ => panic!("Unexpected event"),
3392 } else if messages_delivered == 2 {
3393 // nodes[0] still wants its RAA + commitment_signed
3394 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3395 } else if messages_delivered == 3 {
3396 // nodes[0] still wants its commitment_signed
3397 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3398 } else if messages_delivered == 4 {
3399 // nodes[1] still wants its final RAA
3400 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3401 } else if messages_delivered == 5 {
3402 // Everything was delivered...
3403 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3406 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3407 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3408 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3410 // Channel should still work fine...
3411 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3412 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3413 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3414 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3418 fn test_drop_messages_peer_disconnect_a() {
3419 do_test_drop_messages_peer_disconnect(0);
3420 do_test_drop_messages_peer_disconnect(1);
3421 do_test_drop_messages_peer_disconnect(2);
3422 do_test_drop_messages_peer_disconnect(3);
3426 fn test_drop_messages_peer_disconnect_b() {
3427 do_test_drop_messages_peer_disconnect(4);
3428 do_test_drop_messages_peer_disconnect(5);
3429 do_test_drop_messages_peer_disconnect(6);
3433 fn test_funding_peer_disconnect() {
3434 // Test that we can lock in our funding tx while disconnected
3435 let chanmon_cfgs = create_chanmon_cfgs(2);
3436 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3437 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3438 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3439 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3441 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3442 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3444 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3445 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3446 assert_eq!(events_1.len(), 1);
3448 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3449 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3451 _ => panic!("Unexpected event"),
3454 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3456 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3457 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3459 confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3460 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3461 assert_eq!(events_2.len(), 2);
3462 let funding_locked = match events_2[0] {
3463 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3464 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3467 _ => panic!("Unexpected event"),
3469 let bs_announcement_sigs = match events_2[1] {
3470 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3471 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3474 _ => panic!("Unexpected event"),
3477 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3479 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3480 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3481 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3482 assert_eq!(events_3.len(), 2);
3483 let as_announcement_sigs = match events_3[0] {
3484 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3485 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3488 _ => panic!("Unexpected event"),
3490 let (as_announcement, as_update) = match events_3[1] {
3491 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3492 (msg.clone(), update_msg.clone())
3494 _ => panic!("Unexpected event"),
3497 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3498 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3499 assert_eq!(events_4.len(), 1);
3500 let (_, bs_update) = match events_4[0] {
3501 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3502 (msg.clone(), update_msg.clone())
3504 _ => panic!("Unexpected event"),
3507 nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3508 nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3509 nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3511 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3512 let logger = Arc::new(test_utils::TestLogger::new());
3513 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3514 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3515 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3519 fn test_drop_messages_peer_disconnect_dual_htlc() {
3520 // Test that we can handle reconnecting when both sides of a channel have pending
3521 // commitment_updates when we disconnect.
3522 let chanmon_cfgs = create_chanmon_cfgs(2);
3523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3525 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3526 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3527 let logger = Arc::new(test_utils::TestLogger::new());
3529 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3531 // Now try to send a second payment which will fail to send
3532 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3533 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3534 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3535 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3536 check_added_monitors!(nodes[0], 1);
3538 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3539 assert_eq!(events_1.len(), 1);
3541 MessageSendEvent::UpdateHTLCs { .. } => {},
3542 _ => panic!("Unexpected event"),
3545 assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3546 check_added_monitors!(nodes[1], 1);
3548 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3549 assert_eq!(events_2.len(), 1);
3551 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
3552 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3553 assert!(update_add_htlcs.is_empty());
3554 assert_eq!(update_fulfill_htlcs.len(), 1);
3555 assert!(update_fail_htlcs.is_empty());
3556 assert!(update_fail_malformed_htlcs.is_empty());
3557 assert!(update_fee.is_none());
3559 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3560 let events_3 = nodes[0].node.get_and_clear_pending_events();
3561 assert_eq!(events_3.len(), 1);
3563 Event::PaymentSent { ref payment_preimage } => {
3564 assert_eq!(*payment_preimage, payment_preimage_1);
3566 _ => panic!("Unexpected event"),
3569 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3570 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3571 // No commitment_signed so get_event_msg's assert(len == 1) passes
3572 check_added_monitors!(nodes[0], 1);
3574 _ => panic!("Unexpected event"),
3577 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3578 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3580 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3581 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3582 assert_eq!(reestablish_1.len(), 1);
3583 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3584 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3585 assert_eq!(reestablish_2.len(), 1);
3587 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3588 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3589 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3590 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3592 assert!(as_resp.0.is_none());
3593 assert!(bs_resp.0.is_none());
3595 assert!(bs_resp.1.is_none());
3596 assert!(bs_resp.2.is_none());
3598 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3600 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3601 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3602 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3603 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3604 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3605 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3606 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3607 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3608 // No commitment_signed so get_event_msg's assert(len == 1) passes
3609 check_added_monitors!(nodes[1], 1);
3611 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3612 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3613 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3614 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3615 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3616 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3617 assert!(bs_second_commitment_signed.update_fee.is_none());
3618 check_added_monitors!(nodes[1], 1);
3620 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3621 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3622 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3623 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3624 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3625 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3626 assert!(as_commitment_signed.update_fee.is_none());
3627 check_added_monitors!(nodes[0], 1);
3629 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3630 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3631 // No commitment_signed so get_event_msg's assert(len == 1) passes
3632 check_added_monitors!(nodes[0], 1);
3634 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3635 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3636 // No commitment_signed so get_event_msg's assert(len == 1) passes
3637 check_added_monitors!(nodes[1], 1);
3639 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3640 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3641 check_added_monitors!(nodes[1], 1);
3643 expect_pending_htlcs_forwardable!(nodes[1]);
3645 let events_5 = nodes[1].node.get_and_clear_pending_events();
3646 assert_eq!(events_5.len(), 1);
3648 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3649 assert_eq!(payment_hash_2, *payment_hash);
3650 assert_eq!(*payment_secret, None);
3652 _ => panic!("Unexpected event"),
3655 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3656 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3657 check_added_monitors!(nodes[0], 1);
3659 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3662 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3663 // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3664 // to avoid our counterparty failing the channel.
3665 let chanmon_cfgs = create_chanmon_cfgs(2);
3666 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3667 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3668 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3670 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3671 let logger = Arc::new(test_utils::TestLogger::new());
3673 let our_payment_hash = if send_partial_mpp {
3674 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3675 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3676 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
3677 let payment_secret = PaymentSecret([0xdb; 32]);
3678 // Use the utility function send_payment_along_path to send the payment with MPP data which
3679 // indicates there are more HTLCs coming.
3680 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
3681 check_added_monitors!(nodes[0], 1);
3682 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3683 assert_eq!(events.len(), 1);
3684 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3685 // hop should *not* yet generate any PaymentReceived event(s).
3686 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
3689 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3692 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3693 nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3694 nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3695 for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3696 header.prev_blockhash = header.bitcoin_hash();
3697 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3698 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3701 expect_pending_htlcs_forwardable!(nodes[1]);
3703 check_added_monitors!(nodes[1], 1);
3704 let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3705 assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3706 assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3707 assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3708 assert!(htlc_timeout_updates.update_fee.is_none());
3710 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3711 commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3712 // 100_000 msat as u64, followed by a height of 123 as u32
3713 let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3714 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
3715 expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3719 fn test_htlc_timeout() {
3720 do_test_htlc_timeout(true);
3721 do_test_htlc_timeout(false);
3724 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3725 // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3726 let chanmon_cfgs = create_chanmon_cfgs(3);
3727 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3728 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3729 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3730 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3731 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3732 let logger = Arc::new(test_utils::TestLogger::new());
3734 // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3735 let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3737 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3738 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3739 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
3741 assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3742 check_added_monitors!(nodes[1], 1);
3744 // Now attempt to route a second payment, which should be placed in the holding cell
3745 let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3747 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3748 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3749 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
3750 check_added_monitors!(nodes[0], 1);
3751 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3752 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3753 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3754 expect_pending_htlcs_forwardable!(nodes[1]);
3755 check_added_monitors!(nodes[1], 0);
3757 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3758 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
3759 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
3760 check_added_monitors!(nodes[1], 0);
3763 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3764 nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3765 for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3766 header.prev_blockhash = header.bitcoin_hash();
3767 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3770 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3771 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3773 header.prev_blockhash = header.bitcoin_hash();
3774 nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
3777 expect_pending_htlcs_forwardable!(nodes[1]);
3778 check_added_monitors!(nodes[1], 1);
3779 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
3780 assert_eq!(fail_commit.len(), 1);
3781 match fail_commit[0] {
3782 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
3783 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3784 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
3786 _ => unreachable!(),
3788 expect_payment_failed!(nodes[0], second_payment_hash, false);
3789 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
3791 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
3792 _ => panic!("Unexpected event"),
3795 panic!("Unexpected event");
3798 expect_payment_failed!(nodes[1], second_payment_hash, true);
3803 fn test_holding_cell_htlc_add_timeouts() {
3804 do_test_holding_cell_htlc_add_timeouts(false);
3805 do_test_holding_cell_htlc_add_timeouts(true);
3809 fn test_invalid_channel_announcement() {
3810 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3811 let secp_ctx = Secp256k1::new();
3812 let chanmon_cfgs = create_chanmon_cfgs(2);
3813 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3814 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3815 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3817 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
3819 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3820 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3821 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3822 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3824 nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3826 let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3827 let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3829 let as_network_key = nodes[0].node.get_our_node_id();
3830 let bs_network_key = nodes[1].node.get_our_node_id();
3832 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3834 let mut chan_announcement;
3836 macro_rules! dummy_unsigned_msg {
3838 msgs::UnsignedChannelAnnouncement {
3839 features: ChannelFeatures::known(),
3840 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3841 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3842 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3843 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3844 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3845 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3846 excess_data: Vec::new(),
3851 macro_rules! sign_msg {
3852 ($unsigned_msg: expr) => {
3853 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3854 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3855 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3856 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3857 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3858 chan_announcement = msgs::ChannelAnnouncement {
3859 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3860 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3861 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3862 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3863 contents: $unsigned_msg
3868 let unsigned_msg = dummy_unsigned_msg!();
3869 sign_msg!(unsigned_msg);
3870 assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
3871 let _ = nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3873 // Configured with Network::Testnet
3874 let mut unsigned_msg = dummy_unsigned_msg!();
3875 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3876 sign_msg!(unsigned_msg);
3877 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3879 let mut unsigned_msg = dummy_unsigned_msg!();
3880 unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
3881 sign_msg!(unsigned_msg);
3882 assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3886 fn test_no_txn_manager_serialize_deserialize() {
3887 let chanmon_cfgs = create_chanmon_cfgs(2);
3888 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3889 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3890 let fee_estimator: test_utils::TestFeeEstimator;
3891 let new_chan_monitor: test_utils::TestChannelMonitor;
3892 let keys_manager: test_utils::TestKeysInterface;
3893 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3894 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3896 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3898 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3900 let nodes_0_serialized = nodes[0].node.encode();
3901 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3902 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3904 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3905 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
3906 nodes[0].chan_monitor = &new_chan_monitor;
3907 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3908 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3909 assert!(chan_0_monitor_read.is_empty());
3911 let mut nodes_0_read = &nodes_0_serialized[..];
3912 let config = UserConfig::default();
3913 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3914 let (_, nodes_0_deserialized_tmp) = {
3915 let mut channel_monitors = HashMap::new();
3916 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3917 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3918 default_config: config,
3919 keys_manager: &keys_manager,
3920 fee_estimator: &fee_estimator,
3921 monitor: nodes[0].chan_monitor,
3922 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3923 logger: Arc::new(test_utils::TestLogger::new()),
3924 channel_monitors: &mut channel_monitors,
3927 nodes_0_deserialized = nodes_0_deserialized_tmp;
3928 assert!(nodes_0_read.is_empty());
3930 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3931 nodes[0].node = &nodes_0_deserialized;
3932 nodes[0].block_notifier.register_listener(nodes[0].node);
3933 assert_eq!(nodes[0].node.list_channels().len(), 1);
3934 check_added_monitors!(nodes[0], 1);
3936 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3937 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3938 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3939 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3941 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3942 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3943 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3944 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3946 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3947 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3948 for node in nodes.iter() {
3949 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
3950 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3951 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3954 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3958 fn test_manager_serialize_deserialize_events() {
3959 // This test makes sure the events field in ChannelManager survives de/serialization
3960 let chanmon_cfgs = create_chanmon_cfgs(2);
3961 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3962 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3963 let fee_estimator: test_utils::TestFeeEstimator;
3964 let new_chan_monitor: test_utils::TestChannelMonitor;
3965 let keys_manager: test_utils::TestKeysInterface;
3966 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3967 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3969 // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
3970 let channel_value = 100000;
3971 let push_msat = 10001;
3972 let a_flags = InitFeatures::known();
3973 let b_flags = InitFeatures::known();
3974 let node_a = nodes.pop().unwrap();
3975 let node_b = nodes.pop().unwrap();
3976 node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
3977 node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
3978 node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
3980 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
3982 node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3983 check_added_monitors!(node_a, 0);
3985 node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
3987 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3988 assert_eq!(added_monitors.len(), 1);
3989 assert_eq!(added_monitors[0].0, funding_output);
3990 added_monitors.clear();
3993 node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
3995 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3996 assert_eq!(added_monitors.len(), 1);
3997 assert_eq!(added_monitors[0].0, funding_output);
3998 added_monitors.clear();
4000 // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4005 // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4006 let nodes_0_serialized = nodes[0].node.encode();
4007 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4008 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4010 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4011 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
4012 nodes[0].chan_monitor = &new_chan_monitor;
4013 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4014 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
4015 assert!(chan_0_monitor_read.is_empty());
4017 let mut nodes_0_read = &nodes_0_serialized[..];
4018 let config = UserConfig::default();
4019 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
4020 let (_, nodes_0_deserialized_tmp) = {
4021 let mut channel_monitors = HashMap::new();
4022 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
4023 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4024 default_config: config,
4025 keys_manager: &keys_manager,
4026 fee_estimator: &fee_estimator,
4027 monitor: nodes[0].chan_monitor,
4028 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4029 logger: Arc::new(test_utils::TestLogger::new()),
4030 channel_monitors: &mut channel_monitors,
4033 nodes_0_deserialized = nodes_0_deserialized_tmp;
4034 assert!(nodes_0_read.is_empty());
4036 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4038 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
4039 nodes[0].node = &nodes_0_deserialized;
4041 // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4042 let events_4 = nodes[0].node.get_and_clear_pending_events();
4043 assert_eq!(events_4.len(), 1);
4045 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4046 assert_eq!(user_channel_id, 42);
4047 assert_eq!(*funding_txo, funding_output);
4049 _ => panic!("Unexpected event"),
4052 // Make sure the channel is functioning as though the de/serialization never happened
4053 nodes[0].block_notifier.register_listener(nodes[0].node);
4054 assert_eq!(nodes[0].node.list_channels().len(), 1);
4055 check_added_monitors!(nodes[0], 1);
4057 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4058 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4059 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4060 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4062 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4063 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4064 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4065 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4067 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4068 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4069 for node in nodes.iter() {
4070 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4071 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4072 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4075 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4079 fn test_simple_manager_serialize_deserialize() {
4080 let chanmon_cfgs = create_chanmon_cfgs(2);
4081 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4082 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4083 let fee_estimator: test_utils::TestFeeEstimator;
4084 let new_chan_monitor: test_utils::TestChannelMonitor;
4085 let keys_manager: test_utils::TestKeysInterface;
4086 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
4087 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4088 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4090 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4091 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4093 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4095 let nodes_0_serialized = nodes[0].node.encode();
4096 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4097 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4099 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4100 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
4101 nodes[0].chan_monitor = &new_chan_monitor;
4102 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4103 let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
4104 assert!(chan_0_monitor_read.is_empty());
4106 let mut nodes_0_read = &nodes_0_serialized[..];
4107 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
4108 let (_, nodes_0_deserialized_tmp) = {
4109 let mut channel_monitors = HashMap::new();
4110 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
4111 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4112 default_config: UserConfig::default(),
4113 keys_manager: &keys_manager,
4114 fee_estimator: &fee_estimator,
4115 monitor: nodes[0].chan_monitor,
4116 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4117 logger: Arc::new(test_utils::TestLogger::new()),
4118 channel_monitors: &mut channel_monitors,
4121 nodes_0_deserialized = nodes_0_deserialized_tmp;
4122 assert!(nodes_0_read.is_empty());
4124 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
4125 nodes[0].node = &nodes_0_deserialized;
4126 check_added_monitors!(nodes[0], 1);
4128 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4130 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4131 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4135 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4136 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4137 let chanmon_cfgs = create_chanmon_cfgs(4);
4138 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4139 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4140 let fee_estimator: test_utils::TestFeeEstimator;
4141 let new_chan_monitor: test_utils::TestChannelMonitor;
4142 let keys_manager: test_utils::TestKeysInterface;
4143 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
4144 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4145 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4146 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4147 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4149 let mut node_0_stale_monitors_serialized = Vec::new();
4150 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4151 let mut writer = test_utils::TestVecWriter(Vec::new());
4152 monitor.1.write_for_disk(&mut writer).unwrap();
4153 node_0_stale_monitors_serialized.push(writer.0);
4156 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4158 // Serialize the ChannelManager here, but the monitor we keep up-to-date
4159 let nodes_0_serialized = nodes[0].node.encode();
4161 route_payment(&nodes[0], &[&nodes[3]], 1000000);
4162 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4163 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4164 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4166 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4168 let mut node_0_monitors_serialized = Vec::new();
4169 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4170 let mut writer = test_utils::TestVecWriter(Vec::new());
4171 monitor.1.write_for_disk(&mut writer).unwrap();
4172 node_0_monitors_serialized.push(writer.0);
4175 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4176 new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), &fee_estimator);
4177 nodes[0].chan_monitor = &new_chan_monitor;
4179 let mut node_0_stale_monitors = Vec::new();
4180 for serialized in node_0_stale_monitors_serialized.iter() {
4181 let mut read = &serialized[..];
4182 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
4183 assert!(read.is_empty());
4184 node_0_stale_monitors.push(monitor);
4187 let mut node_0_monitors = Vec::new();
4188 for serialized in node_0_monitors_serialized.iter() {
4189 let mut read = &serialized[..];
4190 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
4191 assert!(read.is_empty());
4192 node_0_monitors.push(monitor);
4195 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
4197 let mut nodes_0_read = &nodes_0_serialized[..];
4198 if let Err(msgs::DecodeError::InvalidValue) =
4199 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4200 default_config: UserConfig::default(),
4201 keys_manager: &keys_manager,
4202 fee_estimator: &fee_estimator,
4203 monitor: nodes[0].chan_monitor,
4204 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4205 logger: Arc::new(test_utils::TestLogger::new()),
4206 channel_monitors: &mut node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4208 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4211 let mut nodes_0_read = &nodes_0_serialized[..];
4212 let (_, nodes_0_deserialized_tmp) =
4213 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4214 default_config: UserConfig::default(),
4215 keys_manager: &keys_manager,
4216 fee_estimator: &fee_estimator,
4217 monitor: nodes[0].chan_monitor,
4218 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4219 logger: Arc::new(test_utils::TestLogger::new()),
4220 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4222 nodes_0_deserialized = nodes_0_deserialized_tmp;
4223 assert!(nodes_0_read.is_empty());
4225 { // Channel close should result in a commitment tx and an HTLC tx
4226 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4227 assert_eq!(txn.len(), 2);
4228 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4229 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4232 for monitor in node_0_monitors.drain(..) {
4233 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo(), monitor).is_ok());
4234 check_added_monitors!(nodes[0], 1);
4236 nodes[0].node = &nodes_0_deserialized;
4238 // nodes[1] and nodes[2] have no lost state with nodes[0]...
4239 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4240 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4241 //... and we can even still claim the payment!
4242 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4244 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4245 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4246 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4247 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4248 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4249 assert_eq!(msg_events.len(), 1);
4250 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4252 &ErrorAction::SendErrorMessage { ref msg } => {
4253 assert_eq!(msg.channel_id, channel_id);
4255 _ => panic!("Unexpected event!"),
4260 macro_rules! check_spendable_outputs {
4261 ($node: expr, $der_idx: expr) => {
4263 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4264 let mut txn = Vec::new();
4265 for event in events {
4267 Event::SpendableOutputs { ref outputs } => {
4268 for outp in outputs {
4270 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
4272 previous_output: outpoint.clone(),
4273 script_sig: Script::new(),
4275 witness: Vec::new(),
4278 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4279 value: output.value,
4281 let mut spend_tx = Transaction {
4287 let secp_ctx = Secp256k1::new();
4288 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
4289 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4290 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4291 let remotesig = secp_ctx.sign(&sighash, key);
4292 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4293 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4294 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4297 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
4299 previous_output: outpoint.clone(),
4300 script_sig: Script::new(),
4301 sequence: *to_self_delay as u32,
4302 witness: Vec::new(),
4305 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4306 value: output.value,
4308 let mut spend_tx = Transaction {
4314 let secp_ctx = Secp256k1::new();
4315 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
4316 let local_delaysig = secp_ctx.sign(&sighash, key);
4317 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
4318 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4319 spend_tx.input[0].witness.push(vec!());
4320 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4323 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4324 let secp_ctx = Secp256k1::new();
4326 previous_output: outpoint.clone(),
4327 script_sig: Script::new(),
4329 witness: Vec::new(),
4332 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4333 value: output.value,
4335 let mut spend_tx = Transaction {
4339 output: vec![outp.clone()],
4342 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4344 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4346 Err(_) => panic!("Your RNG is busted"),
4349 Err(_) => panic!("Your rng is busted"),
4352 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4353 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4354 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4355 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4356 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4357 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4358 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4364 _ => panic!("Unexpected event"),
4373 fn test_claim_sizeable_push_msat() {
4374 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4375 let chanmon_cfgs = create_chanmon_cfgs(2);
4376 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4377 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4378 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4380 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4381 nodes[1].node.force_close_channel(&chan.2);
4382 check_closed_broadcast!(nodes[1], false);
4383 check_added_monitors!(nodes[1], 1);
4384 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4385 assert_eq!(node_txn.len(), 1);
4386 check_spends!(node_txn[0], chan.3);
4387 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4389 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4390 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4391 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4393 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4394 assert_eq!(spend_txn.len(), 1);
4395 check_spends!(spend_txn[0], node_txn[0]);
4399 fn test_claim_on_remote_sizeable_push_msat() {
4400 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4401 // to_remote output is encumbered by a P2WPKH
4402 let chanmon_cfgs = create_chanmon_cfgs(2);
4403 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4404 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4405 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4407 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4408 nodes[0].node.force_close_channel(&chan.2);
4409 check_closed_broadcast!(nodes[0], false);
4410 check_added_monitors!(nodes[0], 1);
4412 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4413 assert_eq!(node_txn.len(), 1);
4414 check_spends!(node_txn[0], chan.3);
4415 assert_eq!(node_txn[0].output.len(), 2); // We can't force trimming of to_remote output as channel_reserve_satoshis block us to do so at channel opening
4417 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4418 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4419 check_closed_broadcast!(nodes[1], false);
4420 check_added_monitors!(nodes[1], 1);
4421 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4423 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4424 assert_eq!(spend_txn.len(), 2);
4425 assert_eq!(spend_txn[0], spend_txn[1]);
4426 check_spends!(spend_txn[0], node_txn[0]);
4430 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4431 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4432 // to_remote output is encumbered by a P2WPKH
4434 let chanmon_cfgs = create_chanmon_cfgs(2);
4435 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4436 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4437 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4439 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4440 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4441 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4442 assert_eq!(revoked_local_txn[0].input.len(), 1);
4443 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4445 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4446 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4447 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4448 check_closed_broadcast!(nodes[1], false);
4449 check_added_monitors!(nodes[1], 1);
4451 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4452 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4453 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4454 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4456 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4457 assert_eq!(spend_txn.len(), 3);
4458 assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4459 check_spends!(spend_txn[0], revoked_local_txn[0]);
4460 check_spends!(spend_txn[2], node_txn[0]);
4464 fn test_static_spendable_outputs_preimage_tx() {
4465 let chanmon_cfgs = create_chanmon_cfgs(2);
4466 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4467 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4468 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4470 // Create some initial channels
4471 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4473 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4475 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4476 assert_eq!(commitment_tx[0].input.len(), 1);
4477 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4479 // Settle A's commitment tx on B's chain
4480 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4481 assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4482 check_added_monitors!(nodes[1], 1);
4483 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4484 check_added_monitors!(nodes[1], 1);
4485 let events = nodes[1].node.get_and_clear_pending_msg_events();
4487 MessageSendEvent::UpdateHTLCs { .. } => {},
4488 _ => panic!("Unexpected event"),
4491 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4492 _ => panic!("Unexepected event"),
4495 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4496 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4497 assert_eq!(node_txn.len(), 3);
4498 check_spends!(node_txn[0], commitment_tx[0]);
4499 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4500 check_spends!(node_txn[1], chan_1.3);
4501 check_spends!(node_txn[2], node_txn[1]);
4503 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4504 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4505 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4507 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4508 assert_eq!(spend_txn.len(), 1);
4509 check_spends!(spend_txn[0], node_txn[0]);
4513 fn test_static_spendable_outputs_timeout_tx() {
4514 let chanmon_cfgs = create_chanmon_cfgs(2);
4515 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4516 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4517 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4519 // Create some initial channels
4520 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4522 // Rebalance the network a bit by relaying one payment through all the channels ...
4523 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4525 let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4527 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4528 assert_eq!(commitment_tx[0].input.len(), 1);
4529 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4531 // Settle A's commitment tx on B' chain
4532 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4533 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4534 check_added_monitors!(nodes[1], 1);
4535 let events = nodes[1].node.get_and_clear_pending_msg_events();
4537 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4538 _ => panic!("Unexpected event"),
4541 // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4542 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4543 assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4544 check_spends!(node_txn[0], commitment_tx[0].clone());
4545 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4546 check_spends!(node_txn[1], chan_1.3.clone());
4547 check_spends!(node_txn[2], node_txn[1]);
4549 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4550 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4551 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4552 expect_payment_failed!(nodes[1], our_payment_hash, true);
4554 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4555 assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4556 check_spends!(spend_txn[2], node_txn[0].clone());
4560 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4561 let chanmon_cfgs = create_chanmon_cfgs(2);
4562 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4563 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4564 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4566 // Create some initial channels
4567 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4569 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4570 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4571 assert_eq!(revoked_local_txn[0].input.len(), 1);
4572 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4574 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4576 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4577 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4578 check_closed_broadcast!(nodes[1], false);
4579 check_added_monitors!(nodes[1], 1);
4581 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4582 assert_eq!(node_txn.len(), 2);
4583 assert_eq!(node_txn[0].input.len(), 2);
4584 check_spends!(node_txn[0], revoked_local_txn[0]);
4586 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4587 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4588 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4590 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4591 assert_eq!(spend_txn.len(), 1);
4592 check_spends!(spend_txn[0], node_txn[0]);
4596 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4597 let chanmon_cfgs = create_chanmon_cfgs(2);
4598 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4599 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4600 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4602 // Create some initial channels
4603 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4605 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4606 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4607 assert_eq!(revoked_local_txn[0].input.len(), 1);
4608 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4610 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4612 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4613 // A will generate HTLC-Timeout from revoked commitment tx
4614 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4615 check_closed_broadcast!(nodes[0], false);
4616 check_added_monitors!(nodes[0], 1);
4618 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4619 assert_eq!(revoked_htlc_txn.len(), 2);
4620 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4621 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4622 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4623 check_spends!(revoked_htlc_txn[1], chan_1.3);
4625 // B will generate justice tx from A's revoked commitment/HTLC tx
4626 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4627 check_closed_broadcast!(nodes[1], false);
4628 check_added_monitors!(nodes[1], 1);
4630 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4631 assert_eq!(node_txn.len(), 4); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-timeout, adjusted justice tx, ChannelManager: local commitment tx
4632 assert_eq!(node_txn[0].input.len(), 2);
4633 check_spends!(node_txn[0], revoked_local_txn[0]);
4634 check_spends!(node_txn[1], chan_1.3);
4635 assert_eq!(node_txn[2].input.len(), 1);
4636 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4637 assert_eq!(node_txn[3].input.len(), 1);
4638 check_spends!(node_txn[3], revoked_local_txn[0]);
4640 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4641 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4642 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4644 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4645 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4646 assert_eq!(spend_txn.len(), 2);
4647 check_spends!(spend_txn[0], node_txn[0]);
4648 check_spends!(spend_txn[1], node_txn[2]);
4652 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4653 let chanmon_cfgs = create_chanmon_cfgs(2);
4654 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4655 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4656 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4658 // Create some initial channels
4659 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4661 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4662 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4663 assert_eq!(revoked_local_txn[0].input.len(), 1);
4664 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4666 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4668 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4669 // B will generate HTLC-Success from revoked commitment tx
4670 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4671 check_closed_broadcast!(nodes[1], false);
4672 check_added_monitors!(nodes[1], 1);
4673 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4675 assert_eq!(revoked_htlc_txn.len(), 2);
4676 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4677 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4678 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4680 // A will generate justice tx from B's revoked commitment/HTLC tx
4681 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4682 check_closed_broadcast!(nodes[0], false);
4683 check_added_monitors!(nodes[0], 1);
4685 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4686 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4687 assert_eq!(node_txn[2].input.len(), 1);
4688 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4690 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4691 nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4692 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4694 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4695 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4696 assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4697 assert_eq!(spend_txn[0], spend_txn[1]);
4698 assert_eq!(spend_txn[0], spend_txn[2]);
4699 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4700 check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4701 check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
4705 fn test_onchain_to_onchain_claim() {
4706 // Test that in case of channel closure, we detect the state of output thanks to
4707 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4708 // First, have C claim an HTLC against its own latest commitment transaction.
4709 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4711 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4714 let chanmon_cfgs = create_chanmon_cfgs(3);
4715 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4716 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4717 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4719 // Create some initial channels
4720 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4721 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4723 // Rebalance the network a bit by relaying one payment through all the channels ...
4724 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4725 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4727 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4728 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4729 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4730 check_spends!(commitment_tx[0], chan_2.3);
4731 nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
4732 check_added_monitors!(nodes[2], 1);
4733 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4734 assert!(updates.update_add_htlcs.is_empty());
4735 assert!(updates.update_fail_htlcs.is_empty());
4736 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4737 assert!(updates.update_fail_malformed_htlcs.is_empty());
4739 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4740 check_closed_broadcast!(nodes[2], false);
4741 check_added_monitors!(nodes[2], 1);
4743 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4744 assert_eq!(c_txn.len(), 3);
4745 assert_eq!(c_txn[0], c_txn[2]);
4746 assert_eq!(commitment_tx[0], c_txn[1]);
4747 check_spends!(c_txn[1], chan_2.3);
4748 check_spends!(c_txn[2], c_txn[1]);
4749 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4750 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4751 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4752 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4754 // So we broadcast C's commitment tx and HTLC-Success on B's chain, we should successfully be able to extract preimage and update downstream monitor
4755 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4757 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4758 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4759 assert_eq!(b_txn.len(), 3);
4760 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4761 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4762 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4763 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4764 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4765 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4766 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4767 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4768 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4771 check_added_monitors!(nodes[1], 1);
4772 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4773 check_added_monitors!(nodes[1], 1);
4774 match msg_events[0] {
4775 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4776 _ => panic!("Unexpected event"),
4778 match msg_events[1] {
4779 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
4780 assert!(update_add_htlcs.is_empty());
4781 assert!(update_fail_htlcs.is_empty());
4782 assert_eq!(update_fulfill_htlcs.len(), 1);
4783 assert!(update_fail_malformed_htlcs.is_empty());
4784 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4786 _ => panic!("Unexpected event"),
4788 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4789 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4790 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4791 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4792 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4793 assert_eq!(b_txn.len(), 3);
4794 check_spends!(b_txn[1], chan_1.3);
4795 check_spends!(b_txn[2], b_txn[1]);
4796 check_spends!(b_txn[0], commitment_tx[0]);
4797 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4798 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4799 assert_eq!(b_txn[0].lock_time, 0); // Success tx
4801 check_closed_broadcast!(nodes[1], false);
4802 check_added_monitors!(nodes[1], 1);
4806 fn test_duplicate_payment_hash_one_failure_one_success() {
4807 // Topology : A --> B --> C
4808 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4809 let chanmon_cfgs = create_chanmon_cfgs(3);
4810 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4811 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4812 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4814 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4815 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4817 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4818 *nodes[0].network_payment_count.borrow_mut() -= 1;
4819 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4821 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4822 assert_eq!(commitment_txn[0].input.len(), 1);
4823 check_spends!(commitment_txn[0], chan_2.3);
4825 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4826 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4827 check_closed_broadcast!(nodes[1], false);
4828 check_added_monitors!(nodes[1], 1);
4830 let htlc_timeout_tx;
4831 { // Extract one of the two HTLC-Timeout transaction
4832 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4833 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4834 assert_eq!(node_txn.len(), 5);
4835 check_spends!(node_txn[0], commitment_txn[0]);
4836 assert_eq!(node_txn[0].input.len(), 1);
4837 check_spends!(node_txn[1], commitment_txn[0]);
4838 assert_eq!(node_txn[1].input.len(), 1);
4839 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4840 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4841 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4842 check_spends!(node_txn[2], chan_2.3);
4843 check_spends!(node_txn[3], node_txn[2]);
4844 check_spends!(node_txn[4], node_txn[2]);
4845 htlc_timeout_tx = node_txn[1].clone();
4848 nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
4849 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4850 check_added_monitors!(nodes[2], 3);
4851 let events = nodes[2].node.get_and_clear_pending_msg_events();
4853 MessageSendEvent::UpdateHTLCs { .. } => {},
4854 _ => panic!("Unexpected event"),
4857 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4858 _ => panic!("Unexepected event"),
4860 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4861 assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
4862 check_spends!(htlc_success_txn[2], chan_2.3);
4863 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4864 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4865 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
4866 assert_eq!(htlc_success_txn[0].input.len(), 1);
4867 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4868 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4869 assert_eq!(htlc_success_txn[1].input.len(), 1);
4870 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4871 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4872 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4873 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4875 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4876 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4877 expect_pending_htlcs_forwardable!(nodes[1]);
4878 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4879 assert!(htlc_updates.update_add_htlcs.is_empty());
4880 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4881 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4882 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4883 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4884 check_added_monitors!(nodes[1], 1);
4886 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4887 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4889 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4890 let events = nodes[0].node.get_and_clear_pending_msg_events();
4891 assert_eq!(events.len(), 1);
4893 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
4895 _ => { panic!("Unexpected event"); }
4898 expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
4900 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4901 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4902 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4903 assert!(updates.update_add_htlcs.is_empty());
4904 assert!(updates.update_fail_htlcs.is_empty());
4905 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4906 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4907 assert!(updates.update_fail_malformed_htlcs.is_empty());
4908 check_added_monitors!(nodes[1], 1);
4910 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4911 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4913 let events = nodes[0].node.get_and_clear_pending_events();
4915 Event::PaymentSent { ref payment_preimage } => {
4916 assert_eq!(*payment_preimage, our_payment_preimage);
4918 _ => panic!("Unexpected event"),
4923 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4924 let chanmon_cfgs = create_chanmon_cfgs(2);
4925 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4926 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4927 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4929 // Create some initial channels
4930 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4932 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4933 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4934 assert_eq!(local_txn[0].input.len(), 1);
4935 check_spends!(local_txn[0], chan_1.3);
4937 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4938 nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
4939 check_added_monitors!(nodes[1], 1);
4940 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4941 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4942 check_added_monitors!(nodes[1], 1);
4943 let events = nodes[1].node.get_and_clear_pending_msg_events();
4945 MessageSendEvent::UpdateHTLCs { .. } => {},
4946 _ => panic!("Unexpected event"),
4949 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4950 _ => panic!("Unexepected event"),
4953 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4954 assert_eq!(node_txn[0].input.len(), 1);
4955 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4956 check_spends!(node_txn[0], local_txn[0]);
4957 vec![node_txn[0].clone(), node_txn[2].clone()]
4960 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4961 nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
4962 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
4964 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4965 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4966 assert_eq!(spend_txn.len(), 2);
4967 check_spends!(spend_txn[0], node_txn[0]);
4968 check_spends!(spend_txn[1], node_txn[1]);
4971 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4972 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4973 // unrevoked commitment transaction.
4974 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4975 // a remote RAA before they could be failed backwards (and combinations thereof).
4976 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4977 // use the same payment hashes.
4978 // Thus, we use a six-node network:
4983 // And test where C fails back to A/B when D announces its latest commitment transaction
4984 let chanmon_cfgs = create_chanmon_cfgs(6);
4985 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4986 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
4987 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4988 let logger = Arc::new(test_utils::TestLogger::new());
4990 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
4991 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4992 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
4993 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
4994 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
4996 // Rebalance and check output sanity...
4997 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4998 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4999 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5001 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5003 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5005 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5006 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5007 let our_node_id = &nodes[1].node.get_our_node_id();
5008 let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5010 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_1); // not added < dust limit + HTLC tx fee
5012 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_2); // not added < dust limit + HTLC tx fee
5014 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5016 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5017 let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5019 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5021 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5024 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5026 let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5027 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], ds_dust_limit*1000, payment_hash_5); // not added < dust limit + HTLC tx fee
5030 let (_, payment_hash_6) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], ds_dust_limit*1000); // not added < dust limit + HTLC tx fee
5032 let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5033 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5035 // Double-check that six of the new HTLC were added
5036 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5037 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5038 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5039 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5041 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5042 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5043 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5044 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5045 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5046 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5047 check_added_monitors!(nodes[4], 0);
5048 expect_pending_htlcs_forwardable!(nodes[4]);
5049 check_added_monitors!(nodes[4], 1);
5051 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5052 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5053 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5054 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5055 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5056 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5058 // Fail 3rd below-dust and 7th above-dust HTLCs
5059 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5060 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5061 check_added_monitors!(nodes[5], 0);
5062 expect_pending_htlcs_forwardable!(nodes[5]);
5063 check_added_monitors!(nodes[5], 1);
5065 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5066 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5067 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5068 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5070 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5072 expect_pending_htlcs_forwardable!(nodes[3]);
5073 check_added_monitors!(nodes[3], 1);
5074 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5075 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5076 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5077 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5078 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5079 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5080 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5081 if deliver_last_raa {
5082 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5084 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5087 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5088 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5089 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5090 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5092 // We now broadcast the latest commitment transaction, which *should* result in failures for
5093 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5094 // the non-broadcast above-dust HTLCs.
5096 // Alternatively, we may broadcast the previous commitment transaction, which should only
5097 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5098 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5100 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5101 if announce_latest {
5102 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5104 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5106 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
5107 check_closed_broadcast!(nodes[2], false);
5108 expect_pending_htlcs_forwardable!(nodes[2]);
5109 check_added_monitors!(nodes[2], 3);
5111 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5112 assert_eq!(cs_msgs.len(), 2);
5113 let mut a_done = false;
5114 for msg in cs_msgs {
5116 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5117 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5118 // should be failed-backwards here.
5119 let target = if *node_id == nodes[0].node.get_our_node_id() {
5120 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5121 for htlc in &updates.update_fail_htlcs {
5122 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 6 || if announce_latest { htlc.htlc_id == 3 || htlc.htlc_id == 5 } else { false });
5124 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5129 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5130 for htlc in &updates.update_fail_htlcs {
5131 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5133 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5134 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5137 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5138 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5139 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5140 if announce_latest {
5141 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5142 if *node_id == nodes[0].node.get_our_node_id() {
5143 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5146 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5148 _ => panic!("Unexpected event"),
5152 let as_events = nodes[0].node.get_and_clear_pending_events();
5153 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5154 let mut as_failds = HashSet::new();
5155 for event in as_events.iter() {
5156 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5157 assert!(as_failds.insert(*payment_hash));
5158 if *payment_hash != payment_hash_2 {
5159 assert_eq!(*rejected_by_dest, deliver_last_raa);
5161 assert!(!rejected_by_dest);
5163 } else { panic!("Unexpected event"); }
5165 assert!(as_failds.contains(&payment_hash_1));
5166 assert!(as_failds.contains(&payment_hash_2));
5167 if announce_latest {
5168 assert!(as_failds.contains(&payment_hash_3));
5169 assert!(as_failds.contains(&payment_hash_5));
5171 assert!(as_failds.contains(&payment_hash_6));
5173 let bs_events = nodes[1].node.get_and_clear_pending_events();
5174 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5175 let mut bs_failds = HashSet::new();
5176 for event in bs_events.iter() {
5177 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5178 assert!(bs_failds.insert(*payment_hash));
5179 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5180 assert_eq!(*rejected_by_dest, deliver_last_raa);
5182 assert!(!rejected_by_dest);
5184 } else { panic!("Unexpected event"); }
5186 assert!(bs_failds.contains(&payment_hash_1));
5187 assert!(bs_failds.contains(&payment_hash_2));
5188 if announce_latest {
5189 assert!(bs_failds.contains(&payment_hash_4));
5191 assert!(bs_failds.contains(&payment_hash_5));
5193 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5194 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5195 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5196 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5197 // PaymentFailureNetworkUpdates.
5198 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5199 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5200 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5201 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5202 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5204 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5205 _ => panic!("Unexpected event"),
5211 fn test_fail_backwards_latest_remote_announce_a() {
5212 do_test_fail_backwards_unrevoked_remote_announce(false, true);
5216 fn test_fail_backwards_latest_remote_announce_b() {
5217 do_test_fail_backwards_unrevoked_remote_announce(true, true);
5221 fn test_fail_backwards_previous_remote_announce() {
5222 do_test_fail_backwards_unrevoked_remote_announce(false, false);
5223 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5224 // tested for in test_commitment_revoked_fail_backward_exhaustive()
5228 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5229 let chanmon_cfgs = create_chanmon_cfgs(2);
5230 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5231 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5232 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5234 // Create some initial channels
5235 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5237 let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5238 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5239 assert_eq!(local_txn[0].input.len(), 1);
5240 check_spends!(local_txn[0], chan_1.3);
5242 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5243 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5244 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5245 check_closed_broadcast!(nodes[0], false);
5246 check_added_monitors!(nodes[0], 1);
5248 let htlc_timeout = {
5249 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5250 assert_eq!(node_txn[0].input.len(), 1);
5251 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5252 check_spends!(node_txn[0], local_txn[0]);
5256 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5257 nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5258 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5259 expect_payment_failed!(nodes[0], our_payment_hash, true);
5261 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5262 let spend_txn = check_spendable_outputs!(nodes[0], 1);
5263 assert_eq!(spend_txn.len(), 3);
5264 assert_eq!(spend_txn[0], spend_txn[1]);
5265 check_spends!(spend_txn[0], local_txn[0]);
5266 check_spends!(spend_txn[2], htlc_timeout);
5270 fn test_static_output_closing_tx() {
5271 let chanmon_cfgs = create_chanmon_cfgs(2);
5272 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5273 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5274 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5276 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5278 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5279 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5281 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5282 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5283 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5285 let spend_txn = check_spendable_outputs!(nodes[0], 2);
5286 assert_eq!(spend_txn.len(), 1);
5287 check_spends!(spend_txn[0], closing_tx);
5289 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5290 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5292 let spend_txn = check_spendable_outputs!(nodes[1], 2);
5293 assert_eq!(spend_txn.len(), 1);
5294 check_spends!(spend_txn[0], closing_tx);
5297 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5298 let chanmon_cfgs = create_chanmon_cfgs(2);
5299 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5300 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5301 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5302 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5304 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5306 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5307 // present in B's local commitment transaction, but none of A's commitment transactions.
5308 assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5309 check_added_monitors!(nodes[1], 1);
5311 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5312 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5313 let events = nodes[0].node.get_and_clear_pending_events();
5314 assert_eq!(events.len(), 1);
5316 Event::PaymentSent { payment_preimage } => {
5317 assert_eq!(payment_preimage, our_payment_preimage);
5319 _ => panic!("Unexpected event"),
5322 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5323 check_added_monitors!(nodes[0], 1);
5324 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5325 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5326 check_added_monitors!(nodes[1], 1);
5328 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5329 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5330 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5331 header.prev_blockhash = header.bitcoin_hash();
5333 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5334 check_closed_broadcast!(nodes[1], false);
5335 check_added_monitors!(nodes[1], 1);
5338 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5339 let chanmon_cfgs = create_chanmon_cfgs(2);
5340 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5341 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5342 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5343 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5344 let logger = Arc::new(test_utils::TestLogger::new());
5346 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5347 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5348 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, logger.clone()).unwrap();
5349 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5350 check_added_monitors!(nodes[0], 1);
5352 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5354 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5355 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5356 // to "time out" the HTLC.
5358 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5360 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5361 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5362 header.prev_blockhash = header.bitcoin_hash();
5364 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5365 check_closed_broadcast!(nodes[0], false);
5366 check_added_monitors!(nodes[0], 1);
5369 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5370 let chanmon_cfgs = create_chanmon_cfgs(3);
5371 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5372 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5373 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5374 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5376 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5377 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5378 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5379 // actually revoked.
5380 let htlc_value = if use_dust { 50000 } else { 3000000 };
5381 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5382 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5383 expect_pending_htlcs_forwardable!(nodes[1]);
5384 check_added_monitors!(nodes[1], 1);
5386 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5387 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5388 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5389 check_added_monitors!(nodes[0], 1);
5390 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5391 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5392 check_added_monitors!(nodes[1], 1);
5393 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5394 check_added_monitors!(nodes[1], 1);
5395 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5397 if check_revoke_no_close {
5398 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5399 check_added_monitors!(nodes[0], 1);
5402 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5403 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5404 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5405 header.prev_blockhash = header.bitcoin_hash();
5407 if !check_revoke_no_close {
5408 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5409 check_closed_broadcast!(nodes[0], false);
5410 check_added_monitors!(nodes[0], 1);
5412 expect_payment_failed!(nodes[0], our_payment_hash, true);
5416 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5417 // There are only a few cases to test here:
5418 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5419 // broadcastable commitment transactions result in channel closure,
5420 // * its included in an unrevoked-but-previous remote commitment transaction,
5421 // * its included in the latest remote or local commitment transactions.
5422 // We test each of the three possible commitment transactions individually and use both dust and
5424 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5425 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5426 // tested for at least one of the cases in other tests.
5428 fn htlc_claim_single_commitment_only_a() {
5429 do_htlc_claim_local_commitment_only(true);
5430 do_htlc_claim_local_commitment_only(false);
5432 do_htlc_claim_current_remote_commitment_only(true);
5433 do_htlc_claim_current_remote_commitment_only(false);
5437 fn htlc_claim_single_commitment_only_b() {
5438 do_htlc_claim_previous_remote_commitment_only(true, false);
5439 do_htlc_claim_previous_remote_commitment_only(false, false);
5440 do_htlc_claim_previous_remote_commitment_only(true, true);
5441 do_htlc_claim_previous_remote_commitment_only(false, true);
5444 fn run_onion_failure_test<F1,F2>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, callback_msg: F1, callback_node: F2, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
5445 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5448 run_onion_failure_test_with_fail_intercept(_name, test_case, nodes, route, payment_hash, callback_msg, |_|{}, callback_node, expected_retryable, expected_error_code, expected_channel_update);
5452 // 0: node1 fails backward
5453 // 1: final node fails backward
5454 // 2: payment completed but the user rejects the payment
5455 // 3: final node fails backward (but tamper onion payloads from node0)
5456 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5457 // 200: trigger error in the final node and tamper returning fail_htlc
5458 fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case: u8, nodes: &Vec<Node>, route: &Route, payment_hash: &PaymentHash, mut callback_msg: F1, mut callback_fail: F2, mut callback_node: F3, expected_retryable: bool, expected_error_code: Option<u16>, expected_channel_update: Option<HTLCFailChannelUpdate>)
5459 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5460 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5464 // reset block height
5465 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5466 for ix in 0..nodes.len() {
5467 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5470 macro_rules! expect_event {
5471 ($node: expr, $event_type: path) => {{
5472 let events = $node.node.get_and_clear_pending_events();
5473 assert_eq!(events.len(), 1);
5475 $event_type { .. } => {},
5476 _ => panic!("Unexpected event"),
5481 macro_rules! expect_htlc_forward {
5483 expect_event!($node, Event::PendingHTLCsForwardable);
5484 $node.node.process_pending_htlc_forwards();
5488 // 0 ~~> 2 send payment
5489 nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
5490 check_added_monitors!(nodes[0], 1);
5491 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5492 // temper update_add (0 => 1)
5493 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5494 if test_case == 0 || test_case == 3 || test_case == 100 {
5495 callback_msg(&mut update_add_0);
5498 // 0 => 1 update_add & CS
5499 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5500 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5502 let update_1_0 = match test_case {
5503 0|100 => { // intermediate node failure; fail backward to 0
5504 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5505 assert!(update_1_0.update_fail_htlcs.len()+update_1_0.update_fail_malformed_htlcs.len()==1 && (update_1_0.update_fail_htlcs.len()==1 || update_1_0.update_fail_malformed_htlcs.len()==1));
5508 1|2|3|200 => { // final node failure; forwarding to 2
5509 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5511 if test_case != 200 {
5514 expect_htlc_forward!(&nodes[1]);
5516 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5517 check_added_monitors!(&nodes[1], 1);
5518 assert_eq!(update_1.update_add_htlcs.len(), 1);
5519 // tamper update_add (1 => 2)
5520 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5521 if test_case != 3 && test_case != 200 {
5522 callback_msg(&mut update_add_1);
5526 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5527 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5529 if test_case == 2 || test_case == 200 {
5530 expect_htlc_forward!(&nodes[2]);
5531 expect_event!(&nodes[2], Event::PaymentReceived);
5533 expect_pending_htlcs_forwardable!(nodes[2]);
5536 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5537 if test_case == 2 || test_case == 200 {
5538 check_added_monitors!(&nodes[2], 1);
5540 assert!(update_2_1.update_fail_htlcs.len() == 1);
5542 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5543 if test_case == 200 {
5544 callback_fail(&mut fail_msg);
5548 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5549 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5551 // backward fail on 1
5552 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5553 assert!(update_1_0.update_fail_htlcs.len() == 1);
5556 _ => unreachable!(),
5559 // 1 => 0 commitment_signed_dance
5560 if update_1_0.update_fail_htlcs.len() > 0 {
5561 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5562 if test_case == 100 {
5563 callback_fail(&mut fail_msg);
5565 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5567 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5570 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5572 let events = nodes[0].node.get_and_clear_pending_events();
5573 assert_eq!(events.len(), 1);
5574 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
5575 assert_eq!(*rejected_by_dest, !expected_retryable);
5576 assert_eq!(*error_code, expected_error_code);
5578 panic!("Uexpected event");
5581 let events = nodes[0].node.get_and_clear_pending_msg_events();
5582 if expected_channel_update.is_some() {
5583 assert_eq!(events.len(), 1);
5585 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5587 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5588 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5589 panic!("channel_update not found!");
5592 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5593 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5594 assert!(*short_channel_id == *expected_short_channel_id);
5595 assert!(*is_permanent == *expected_is_permanent);
5597 panic!("Unexpected message event");
5600 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5601 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5602 assert!(*node_id == *expected_node_id);
5603 assert!(*is_permanent == *expected_is_permanent);
5605 panic!("Unexpected message event");
5610 _ => panic!("Unexpected message event"),
5613 assert_eq!(events.len(), 0);
5617 impl msgs::ChannelUpdate {
5618 fn dummy() -> msgs::ChannelUpdate {
5619 use bitcoin::secp256k1::ffi::Signature as FFISignature;
5620 use bitcoin::secp256k1::Signature;
5621 msgs::ChannelUpdate {
5622 signature: Signature::from(FFISignature::new()),
5623 contents: msgs::UnsignedChannelUpdate {
5624 chain_hash: BlockHash::hash(&vec![0u8][..]),
5625 short_channel_id: 0,
5628 cltv_expiry_delta: 0,
5629 htlc_minimum_msat: 0,
5631 fee_proportional_millionths: 0,
5632 excess_data: vec![],
5638 struct BogusOnionHopData {
5641 impl BogusOnionHopData {
5642 fn new(orig: msgs::OnionHopData) -> Self {
5643 Self { data: orig.encode() }
5646 impl Writeable for BogusOnionHopData {
5647 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5648 writer.write_all(&self.data[..])
5653 fn test_onion_failure() {
5654 use ln::msgs::ChannelUpdate;
5655 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5656 use bitcoin::secp256k1;
5658 const BADONION: u16 = 0x8000;
5659 const PERM: u16 = 0x4000;
5660 const NODE: u16 = 0x2000;
5661 const UPDATE: u16 = 0x1000;
5663 let chanmon_cfgs = create_chanmon_cfgs(3);
5664 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5665 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5666 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5667 for node in nodes.iter() {
5668 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5670 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
5671 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5672 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5673 let logger = Arc::new(test_utils::TestLogger::new());
5674 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5676 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5678 // intermediate node failure
5679 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5680 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5681 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5682 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5683 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5684 let mut new_payloads = Vec::new();
5685 for payload in onion_payloads.drain(..) {
5686 new_payloads.push(BogusOnionHopData::new(payload));
5688 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5689 // describing a length-1 TLV payload, which is obviously bogus.
5690 new_payloads[0].data[0] = 1;
5691 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5692 }, ||{}, true, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
5694 // final node failure
5695 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5696 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5697 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5698 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5699 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5700 let mut new_payloads = Vec::new();
5701 for payload in onion_payloads.drain(..) {
5702 new_payloads.push(BogusOnionHopData::new(payload));
5704 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5705 // length-1 TLV payload, which is obviously bogus.
5706 new_payloads[1].data[0] = 1;
5707 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5708 }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5710 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5711 // receiving simulated fail messages
5712 // intermediate node failure
5713 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5715 msg.amount_msat -= 1;
5717 // and tamper returning error message
5718 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5719 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5720 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5721 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
5723 // final node failure
5724 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5725 // and tamper returning error message
5726 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5727 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5728 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5730 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5731 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
5733 // intermediate node failure
5734 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5735 msg.amount_msat -= 1;
5737 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5738 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5739 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5740 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5742 // final node failure
5743 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5744 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5745 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5746 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5748 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5749 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5751 // intermediate node failure
5752 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5753 msg.amount_msat -= 1;
5755 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5756 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5757 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5759 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5760 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5762 // final node failure
5763 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5764 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5765 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5766 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5768 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5769 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5771 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5772 Some(BADONION|PERM|4), None);
5774 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5775 Some(BADONION|PERM|5), None);
5777 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5778 Some(BADONION|PERM|6), None);
5780 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5781 msg.amount_msat -= 1;
5783 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5784 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5785 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5786 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5788 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5789 msg.amount_msat -= 1;
5791 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5792 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5793 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5794 // short_channel_id from the processing node
5795 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5797 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5798 msg.amount_msat -= 1;
5800 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5801 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5802 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5803 // short_channel_id from the processing node
5804 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5806 let mut bogus_route = route.clone();
5807 bogus_route.paths[0][1].short_channel_id -= 1;
5808 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5809 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
5811 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5812 let mut bogus_route = route.clone();
5813 let route_len = bogus_route.paths[0].len();
5814 bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
5815 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5817 //TODO: with new config API, we will be able to generate both valid and
5818 //invalid channel_update cases.
5819 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5820 msg.amount_msat -= 1;
5821 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5823 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5824 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5825 msg.cltv_expiry -= 1;
5826 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5828 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5829 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5830 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5832 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5833 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5835 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5836 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5837 }, false, Some(PERM|15), None);
5839 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5840 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5841 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5843 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5844 }, || {}, true, Some(17), None);
5846 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5847 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5848 for f in pending_forwards.iter_mut() {
5850 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5851 forward_info.outgoing_cltv_value += 1,
5856 }, true, Some(18), None);
5858 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5859 // violate amt_to_forward > msg.amount_msat
5860 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5861 for f in pending_forwards.iter_mut() {
5863 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5864 forward_info.amt_to_forward -= 1,
5869 }, true, Some(19), None);
5871 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5872 // disconnect event to the channel between nodes[1] ~ nodes[2]
5873 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5874 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5875 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5876 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5878 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5879 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5880 let mut route = route.clone();
5882 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
5883 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5884 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
5885 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5886 msg.cltv_expiry = htlc_cltv;
5887 msg.onion_routing_packet = onion_packet;
5888 }, ||{}, true, Some(21), None);
5893 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5894 let chanmon_cfgs = create_chanmon_cfgs(2);
5895 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5896 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5897 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5898 //Force duplicate channel ids
5899 for node in nodes.iter() {
5900 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5903 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5904 let channel_value_satoshis=10000;
5905 let push_msat=10001;
5906 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5907 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5908 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5910 //Create a second channel with a channel_id collision
5911 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5915 fn bolt2_open_channel_sending_node_checks_part2() {
5916 let chanmon_cfgs = create_chanmon_cfgs(2);
5917 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5918 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5919 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5921 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5922 let channel_value_satoshis=2^24;
5923 let push_msat=10001;
5924 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5926 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5927 let channel_value_satoshis=10000;
5928 // Test when push_msat is equal to 1000 * funding_satoshis.
5929 let push_msat=1000*channel_value_satoshis+1;
5930 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5932 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5933 let channel_value_satoshis=10000;
5934 let push_msat=10001;
5935 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5936 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5937 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5939 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5940 // Only the least-significant bit of channel_flags is currently defined resulting in channel_flags only having one of two possible states 0 or 1
5941 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5943 // BOLT #2 spec: Sending node should set to_self_delay sufficient to ensure the sender can irreversibly spend a commitment transaction output, in case of misbehaviour by the receiver.
5944 assert!(BREAKDOWN_TIMEOUT>0);
5945 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5947 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5948 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5949 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5951 // BOLT #2 spec: Sending node must set funding_pubkey, revocation_basepoint, htlc_basepoint, payment_basepoint, and delayed_payment_basepoint to valid DER-encoded, compressed, secp256k1 pubkeys.
5952 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5953 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5954 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5955 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5956 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5959 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5960 // BOLT 2 Requirement: MUST NOT offer amount_msat it cannot pay for in the remote commitment transaction at the current feerate_per_kw (see "Updating Fees") while maintaining its channel reserve.
5961 //TODO: I don't believe this is explicitly enforced when sending an HTLC but as the Fee aspect of the BOLT specs is in flux leaving this as a TODO.
5964 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5965 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5966 let chanmon_cfgs = create_chanmon_cfgs(2);
5967 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5968 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5969 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5970 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5972 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5973 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5974 let logger = Arc::new(test_utils::TestLogger::new());
5975 let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5976 route.paths[0][0].fee_msat = 100;
5978 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5979 assert_eq!(err, "Cannot send less than their minimum HTLC value"));
5980 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5981 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5985 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5986 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5987 let chanmon_cfgs = create_chanmon_cfgs(2);
5988 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5989 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5990 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5991 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5992 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5994 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5995 let logger = Arc::new(test_utils::TestLogger::new());
5996 let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
5997 route.paths[0][0].fee_msat = 0;
5998 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5999 assert_eq!(err, "Cannot send 0-msat HTLC"));
6001 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6002 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6006 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6007 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6008 let chanmon_cfgs = create_chanmon_cfgs(2);
6009 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6010 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6011 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6012 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6014 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6015 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6016 let logger = Arc::new(test_utils::TestLogger::new());
6017 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6018 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6019 check_added_monitors!(nodes[0], 1);
6020 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6021 updates.update_add_htlcs[0].amount_msat = 0;
6023 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6024 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6025 check_closed_broadcast!(nodes[1], true).unwrap();
6026 check_added_monitors!(nodes[1], 1);
6030 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6031 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6032 //It is enforced when constructing a route.
6033 let chanmon_cfgs = create_chanmon_cfgs(2);
6034 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6035 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6036 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6037 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6038 let logger = Arc::new(test_utils::TestLogger::new());
6040 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6042 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6043 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001, logger.clone()).unwrap();
6044 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { err },
6045 assert_eq!(err, "Channel CLTV overflowed?!"));
6049 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6050 //BOLT 2 Requirement: if result would be offering more than the remote's max_accepted_htlcs HTLCs, in the remote commitment transaction: MUST NOT add an HTLC.
6051 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6052 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6053 let chanmon_cfgs = create_chanmon_cfgs(2);
6054 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6055 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6056 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6057 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6058 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
6060 let logger = Arc::new(test_utils::TestLogger::new());
6061 for i in 0..max_accepted_htlcs {
6062 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6063 let payment_event = {
6064 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6065 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6066 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6067 check_added_monitors!(nodes[0], 1);
6069 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6070 assert_eq!(events.len(), 1);
6071 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6072 assert_eq!(htlcs[0].htlc_id, i);
6076 SendEvent::from_event(events.remove(0))
6078 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6079 check_added_monitors!(nodes[1], 0);
6080 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6082 expect_pending_htlcs_forwardable!(nodes[1]);
6083 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6085 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6086 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6087 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6088 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6089 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
6091 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6092 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6096 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6097 //BOLT 2 Requirement: if the sum of total offered HTLCs would exceed the remote's max_htlc_value_in_flight_msat: MUST NOT add an HTLC.
6098 let chanmon_cfgs = create_chanmon_cfgs(2);
6099 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6100 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6101 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6102 let channel_value = 100000;
6103 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6104 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
6106 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6108 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6109 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6110 let logger = Arc::new(test_utils::TestLogger::new());
6111 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV, logger.clone()).unwrap();
6112 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6113 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
6115 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6116 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
6118 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6121 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6123 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6124 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6125 let chanmon_cfgs = create_chanmon_cfgs(2);
6126 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6127 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6128 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6129 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6130 let htlc_minimum_msat: u64;
6132 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6133 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6134 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
6137 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6138 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6139 let logger = Arc::new(test_utils::TestLogger::new());
6140 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, logger.clone()).unwrap();
6141 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6142 check_added_monitors!(nodes[0], 1);
6143 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6144 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6145 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6146 assert!(nodes[1].node.list_channels().is_empty());
6147 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6148 assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
6149 check_added_monitors!(nodes[1], 1);
6153 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6154 //BOLT2 Requirement: receiving an amount_msat that the sending node cannot afford at the current feerate_per_kw (while maintaining its channel reserve): SHOULD fail the channel
6155 let chanmon_cfgs = create_chanmon_cfgs(2);
6156 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6157 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6158 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6159 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6161 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
6163 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6164 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6165 let logger = Arc::new(test_utils::TestLogger::new());
6166 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV, logger.clone()).unwrap();
6167 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6168 check_added_monitors!(nodes[0], 1);
6169 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6171 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
6172 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6174 assert!(nodes[1].node.list_channels().is_empty());
6175 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6176 assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
6177 check_added_monitors!(nodes[1], 1);
6181 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6182 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6183 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6184 let chanmon_cfgs = create_chanmon_cfgs(2);
6185 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6186 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6187 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6188 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6189 let logger = Arc::new(test_utils::TestLogger::new());
6191 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6193 let session_priv = SecretKey::from_slice(&{
6194 let mut session_key = [0; 32];
6195 let mut rng = thread_rng();
6196 rng.fill_bytes(&mut session_key);
6198 }).expect("RNG is bad!");
6200 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6201 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV, logger.clone()).unwrap();
6203 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6204 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6205 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6206 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6208 let mut msg = msgs::UpdateAddHTLC {
6212 payment_hash: our_payment_hash,
6213 cltv_expiry: htlc_cltv,
6214 onion_routing_packet: onion_packet.clone(),
6217 for i in 0..super::channel::OUR_MAX_HTLCS {
6218 msg.htlc_id = i as u64;
6219 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6221 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6222 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6224 assert!(nodes[1].node.list_channels().is_empty());
6225 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6226 assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
6227 check_added_monitors!(nodes[1], 1);
6231 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6232 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6233 let chanmon_cfgs = create_chanmon_cfgs(2);
6234 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6235 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6236 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6237 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6238 let logger = Arc::new(test_utils::TestLogger::new());
6240 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6241 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6242 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6243 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6244 check_added_monitors!(nodes[0], 1);
6245 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6246 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
6247 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6249 assert!(nodes[1].node.list_channels().is_empty());
6250 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6251 assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
6252 check_added_monitors!(nodes[1], 1);
6256 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6257 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6258 let chanmon_cfgs = create_chanmon_cfgs(2);
6259 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6260 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6261 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6262 let logger = Arc::new(test_utils::TestLogger::new());
6264 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6265 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6266 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6267 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6268 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6269 check_added_monitors!(nodes[0], 1);
6270 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6271 updates.update_add_htlcs[0].cltv_expiry = 500000000;
6272 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6274 assert!(nodes[1].node.list_channels().is_empty());
6275 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6276 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6277 check_added_monitors!(nodes[1], 1);
6281 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6282 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6283 // We test this by first testing that that repeated HTLCs pass commitment signature checks
6284 // after disconnect and that non-sequential htlc_ids result in a channel failure.
6285 let chanmon_cfgs = create_chanmon_cfgs(2);
6286 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6287 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6288 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6289 let logger = Arc::new(test_utils::TestLogger::new());
6291 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6292 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6293 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6294 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6295 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6296 check_added_monitors!(nodes[0], 1);
6297 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6298 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6300 //Disconnect and Reconnect
6301 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6302 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6303 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6304 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6305 assert_eq!(reestablish_1.len(), 1);
6306 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6307 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6308 assert_eq!(reestablish_2.len(), 1);
6309 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6310 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6311 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6312 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6315 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6316 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6317 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6318 check_added_monitors!(nodes[1], 1);
6319 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6321 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6323 assert!(nodes[1].node.list_channels().is_empty());
6324 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6325 assert_eq!(err_msg.data, "Remote skipped HTLC ID");
6326 check_added_monitors!(nodes[1], 1);
6330 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6331 //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions: MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6333 let chanmon_cfgs = create_chanmon_cfgs(2);
6334 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6335 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6336 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6337 let logger = Arc::new(test_utils::TestLogger::new());
6338 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6339 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6340 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6341 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6342 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6344 check_added_monitors!(nodes[0], 1);
6345 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6346 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6348 let update_msg = msgs::UpdateFulfillHTLC{
6351 payment_preimage: our_payment_preimage,
6354 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6356 assert!(nodes[0].node.list_channels().is_empty());
6357 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6358 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6359 check_added_monitors!(nodes[0], 1);
6363 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6364 //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions: MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6366 let chanmon_cfgs = create_chanmon_cfgs(2);
6367 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6368 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6369 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6370 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6371 let logger = Arc::new(test_utils::TestLogger::new());
6373 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6374 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6375 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6376 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6377 check_added_monitors!(nodes[0], 1);
6378 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6379 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6381 let update_msg = msgs::UpdateFailHTLC{
6384 reason: msgs::OnionErrorPacket { data: Vec::new()},
6387 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6389 assert!(nodes[0].node.list_channels().is_empty());
6390 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6391 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6392 check_added_monitors!(nodes[0], 1);
6396 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6397 //BOLT 2 Requirement: until the corresponding HTLC is irrevocably committed in both sides' commitment transactions: MUST NOT send an update_fulfill_htlc, update_fail_htlc, or update_fail_malformed_htlc.
6399 let chanmon_cfgs = create_chanmon_cfgs(2);
6400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6402 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6403 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6404 let logger = Arc::new(test_utils::TestLogger::new());
6406 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6407 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6408 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6409 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6410 check_added_monitors!(nodes[0], 1);
6411 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6412 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6414 let update_msg = msgs::UpdateFailMalformedHTLC{
6417 sha256_of_onion: [1; 32],
6418 failure_code: 0x8000,
6421 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6423 assert!(nodes[0].node.list_channels().is_empty());
6424 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6425 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6426 check_added_monitors!(nodes[0], 1);
6430 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6431 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6433 let chanmon_cfgs = create_chanmon_cfgs(2);
6434 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6435 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6436 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6437 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6439 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6441 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6442 check_added_monitors!(nodes[1], 1);
6444 let events = nodes[1].node.get_and_clear_pending_msg_events();
6445 assert_eq!(events.len(), 1);
6446 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6448 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6449 assert!(update_add_htlcs.is_empty());
6450 assert_eq!(update_fulfill_htlcs.len(), 1);
6451 assert!(update_fail_htlcs.is_empty());
6452 assert!(update_fail_malformed_htlcs.is_empty());
6453 assert!(update_fee.is_none());
6454 update_fulfill_htlcs[0].clone()
6456 _ => panic!("Unexpected event"),
6460 update_fulfill_msg.htlc_id = 1;
6462 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6464 assert!(nodes[0].node.list_channels().is_empty());
6465 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6466 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6467 check_added_monitors!(nodes[0], 1);
6471 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6472 //BOLT 2 Requirement: A receiving node: if the payment_preimage value in update_fulfill_htlc doesn't SHA256 hash to the corresponding HTLC payment_hash MUST fail the channel.
6474 let chanmon_cfgs = create_chanmon_cfgs(2);
6475 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6476 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6477 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6478 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6480 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6482 nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6483 check_added_monitors!(nodes[1], 1);
6485 let events = nodes[1].node.get_and_clear_pending_msg_events();
6486 assert_eq!(events.len(), 1);
6487 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6489 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6490 assert!(update_add_htlcs.is_empty());
6491 assert_eq!(update_fulfill_htlcs.len(), 1);
6492 assert!(update_fail_htlcs.is_empty());
6493 assert!(update_fail_malformed_htlcs.is_empty());
6494 assert!(update_fee.is_none());
6495 update_fulfill_htlcs[0].clone()
6497 _ => panic!("Unexpected event"),
6501 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6503 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6505 assert!(nodes[0].node.list_channels().is_empty());
6506 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6507 assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6508 check_added_monitors!(nodes[0], 1);
6512 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6513 //BOLT 2 Requirement: A receiving node: if the BADONION bit in failure_code is not set for update_fail_malformed_htlc MUST fail the channel.
6515 let chanmon_cfgs = create_chanmon_cfgs(2);
6516 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6517 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6518 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6519 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6520 let logger = Arc::new(test_utils::TestLogger::new());
6522 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6523 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6524 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6525 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6526 check_added_monitors!(nodes[0], 1);
6528 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6529 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6531 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6532 check_added_monitors!(nodes[1], 0);
6533 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6535 let events = nodes[1].node.get_and_clear_pending_msg_events();
6537 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6539 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6540 assert!(update_add_htlcs.is_empty());
6541 assert!(update_fulfill_htlcs.is_empty());
6542 assert!(update_fail_htlcs.is_empty());
6543 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6544 assert!(update_fee.is_none());
6545 update_fail_malformed_htlcs[0].clone()
6547 _ => panic!("Unexpected event"),
6550 update_msg.failure_code &= !0x8000;
6551 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6553 assert!(nodes[0].node.list_channels().is_empty());
6554 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6555 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6556 check_added_monitors!(nodes[0], 1);
6560 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6561 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6562 // * MUST return an error in the update_fail_htlc sent to the link which originally sent the HTLC, using the failure_code given and setting the data to sha256_of_onion.
6564 let chanmon_cfgs = create_chanmon_cfgs(3);
6565 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6566 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6567 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6568 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6569 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6570 let logger = Arc::new(test_utils::TestLogger::new());
6572 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6575 let mut payment_event = {
6576 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6577 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
6578 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6579 check_added_monitors!(nodes[0], 1);
6580 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6581 assert_eq!(events.len(), 1);
6582 SendEvent::from_event(events.remove(0))
6584 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6585 check_added_monitors!(nodes[1], 0);
6586 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6587 expect_pending_htlcs_forwardable!(nodes[1]);
6588 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6589 assert_eq!(events_2.len(), 1);
6590 check_added_monitors!(nodes[1], 1);
6591 payment_event = SendEvent::from_event(events_2.remove(0));
6592 assert_eq!(payment_event.msgs.len(), 1);
6595 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6596 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6597 check_added_monitors!(nodes[2], 0);
6598 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6600 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6601 assert_eq!(events_3.len(), 1);
6602 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6604 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
6605 assert!(update_add_htlcs.is_empty());
6606 assert!(update_fulfill_htlcs.is_empty());
6607 assert!(update_fail_htlcs.is_empty());
6608 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6609 assert!(update_fee.is_none());
6610 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6612 _ => panic!("Unexpected event"),
6616 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6618 check_added_monitors!(nodes[1], 0);
6619 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6620 expect_pending_htlcs_forwardable!(nodes[1]);
6621 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6622 assert_eq!(events_4.len(), 1);
6624 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6626 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, .. } } => {
6627 assert!(update_add_htlcs.is_empty());
6628 assert!(update_fulfill_htlcs.is_empty());
6629 assert_eq!(update_fail_htlcs.len(), 1);
6630 assert!(update_fail_malformed_htlcs.is_empty());
6631 assert!(update_fee.is_none());
6633 _ => panic!("Unexpected event"),
6636 check_added_monitors!(nodes[1], 1);
6639 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6640 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6641 // We can have at most two valid local commitment tx, so both cases must be covered, and both txs must be checked to get them all as
6642 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6644 let chanmon_cfgs = create_chanmon_cfgs(2);
6645 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6646 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6647 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6648 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6650 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6652 // We route 2 dust-HTLCs between A and B
6653 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6654 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6655 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6657 // Cache one local commitment tx as previous
6658 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6660 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6661 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6662 check_added_monitors!(nodes[1], 0);
6663 expect_pending_htlcs_forwardable!(nodes[1]);
6664 check_added_monitors!(nodes[1], 1);
6666 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6667 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6668 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6669 check_added_monitors!(nodes[0], 1);
6671 // Cache one local commitment tx as lastest
6672 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6674 let events = nodes[0].node.get_and_clear_pending_msg_events();
6676 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6677 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6679 _ => panic!("Unexpected event"),
6682 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6683 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6685 _ => panic!("Unexpected event"),
6688 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6689 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6690 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6692 if announce_latest {
6693 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6695 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6698 check_closed_broadcast!(nodes[0], false);
6699 check_added_monitors!(nodes[0], 1);
6701 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6702 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
6703 let events = nodes[0].node.get_and_clear_pending_events();
6704 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6705 assert_eq!(events.len(), 2);
6706 let mut first_failed = false;
6707 for event in events {
6709 Event::PaymentFailed { payment_hash, .. } => {
6710 if payment_hash == payment_hash_1 {
6711 assert!(!first_failed);
6712 first_failed = true;
6714 assert_eq!(payment_hash, payment_hash_2);
6717 _ => panic!("Unexpected event"),
6723 fn test_failure_delay_dust_htlc_local_commitment() {
6724 do_test_failure_delay_dust_htlc_local_commitment(true);
6725 do_test_failure_delay_dust_htlc_local_commitment(false);
6729 fn test_no_failure_dust_htlc_local_commitment() {
6730 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6731 // prone to error, we test here that a dummy transaction don't fail them.
6733 let chanmon_cfgs = create_chanmon_cfgs(2);
6734 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6735 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6736 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6737 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6740 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6742 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6743 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6745 // We route 2 dust-HTLCs between A and B
6746 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6747 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6749 // Build a dummy invalid transaction trying to spend a commitment tx
6751 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6752 script_sig: Script::new(),
6754 witness: Vec::new(),
6758 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6762 let dummy_tx = Transaction {
6769 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6770 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6771 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6772 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6773 // We broadcast a few more block to check everything is all right
6774 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.bitcoin_hash());
6775 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6776 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6778 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6779 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6782 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6783 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6784 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6785 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6786 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6787 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6788 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6790 let chanmon_cfgs = create_chanmon_cfgs(3);
6791 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6792 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6793 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6794 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6796 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6798 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6799 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6801 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6802 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6804 // We revoked bs_commitment_tx
6806 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6807 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6810 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6811 let mut timeout_tx = Vec::new();
6813 // We fail dust-HTLC 1 by broadcast of local commitment tx
6814 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6815 check_closed_broadcast!(nodes[0], false);
6816 check_added_monitors!(nodes[0], 1);
6817 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6818 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6819 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6820 expect_payment_failed!(nodes[0], dust_hash, true);
6821 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6822 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6823 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6824 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6825 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6826 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6827 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6828 expect_payment_failed!(nodes[0], non_dust_hash, true);
6830 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6831 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6832 check_closed_broadcast!(nodes[0], false);
6833 check_added_monitors!(nodes[0], 1);
6834 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6835 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6836 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6837 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6839 expect_payment_failed!(nodes[0], dust_hash, true);
6840 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6841 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6842 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6843 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6844 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6845 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6846 expect_payment_failed!(nodes[0], non_dust_hash, true);
6848 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6850 let events = nodes[0].node.get_and_clear_pending_events();
6851 assert_eq!(events.len(), 2);
6854 Event::PaymentFailed { payment_hash, .. } => {
6855 if payment_hash == dust_hash { first = true; }
6856 else { first = false; }
6858 _ => panic!("Unexpected event"),
6861 Event::PaymentFailed { payment_hash, .. } => {
6862 if first { assert_eq!(payment_hash, non_dust_hash); }
6863 else { assert_eq!(payment_hash, dust_hash); }
6865 _ => panic!("Unexpected event"),
6872 fn test_sweep_outbound_htlc_failure_update() {
6873 do_test_sweep_outbound_htlc_failure_update(false, true);
6874 do_test_sweep_outbound_htlc_failure_update(false, false);
6875 do_test_sweep_outbound_htlc_failure_update(true, false);
6879 fn test_upfront_shutdown_script() {
6880 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6881 // enforce it at shutdown message
6883 let mut config = UserConfig::default();
6884 config.channel_options.announced_channel = true;
6885 config.peer_channel_config_limits.force_announced_channel_preference = false;
6886 config.channel_options.commit_upfront_shutdown_pubkey = false;
6887 let user_cfgs = [None, Some(config), None];
6888 let chanmon_cfgs = create_chanmon_cfgs(3);
6889 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6890 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6891 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6893 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6894 let flags = InitFeatures::known();
6895 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6896 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6897 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6898 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6899 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
6900 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6901 assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6902 check_added_monitors!(nodes[2], 1);
6904 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6905 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6906 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6907 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6908 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6909 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6910 let events = nodes[2].node.get_and_clear_pending_msg_events();
6911 assert_eq!(events.len(), 1);
6913 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6914 _ => panic!("Unexpected event"),
6917 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6918 let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
6919 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6920 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6921 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6922 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6923 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6924 let events = nodes[1].node.get_and_clear_pending_msg_events();
6925 assert_eq!(events.len(), 1);
6927 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6928 _ => panic!("Unexpected event"),
6931 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6932 // channel smoothly, opt-out is from channel initiator here
6933 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6934 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6935 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6936 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6937 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6938 let events = nodes[0].node.get_and_clear_pending_msg_events();
6939 assert_eq!(events.len(), 1);
6941 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6942 _ => panic!("Unexpected event"),
6945 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6946 //// channel smoothly
6947 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6948 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6949 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6950 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6951 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6952 let events = nodes[0].node.get_and_clear_pending_msg_events();
6953 assert_eq!(events.len(), 2);
6955 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6956 _ => panic!("Unexpected event"),
6959 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6960 _ => panic!("Unexpected event"),
6965 fn test_user_configurable_csv_delay() {
6966 // We test our channel constructors yield errors when we pass them absurd csv delay
6968 let mut low_our_to_self_config = UserConfig::default();
6969 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6970 let mut high_their_to_self_config = UserConfig::default();
6971 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6972 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6973 let chanmon_cfgs = create_chanmon_cfgs(2);
6974 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6975 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6976 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6978 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6979 let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
6980 if let Err(error) = Channel::new_outbound(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), 1000000, 1000000, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6982 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6983 _ => panic!("Unexpected event"),
6985 } else { assert!(false) }
6987 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6988 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6989 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6990 open_channel.to_self_delay = 200;
6991 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6993 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6994 _ => panic!("Unexpected event"),
6996 } else { assert!(false); }
6998 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6999 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7000 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7001 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7002 accept_channel.to_self_delay = 200;
7003 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7004 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7006 &ErrorAction::SendErrorMessage { ref msg } => {
7007 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
7009 _ => { assert!(false); }
7011 } else { assert!(false); }
7013 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7014 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7015 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7016 open_channel.to_self_delay = 200;
7017 if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
7019 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
7020 _ => panic!("Unexpected event"),
7022 } else { assert!(false); }
7026 fn test_data_loss_protect() {
7027 // We want to be sure that :
7028 // * we don't broadcast our Local Commitment Tx in case of fallen behind
7029 // * we close channel in case of detecting other being fallen behind
7030 // * we are able to claim our own outputs thanks to to_remote being static
7036 let chanmon_cfgs = create_chanmon_cfgs(2);
7037 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7038 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7039 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7041 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7043 // Cache node A state before any channel update
7044 let previous_node_state = nodes[0].node.encode();
7045 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7046 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7048 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7049 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7051 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7052 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7054 // Restore node A from previous state
7055 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
7056 let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
7057 let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
7058 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7059 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7060 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger));
7061 monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), &tx_broadcaster, logger.clone(), &fee_estimator);
7063 let mut channel_monitors = HashMap::new();
7064 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7065 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7066 keys_manager: &keys_manager,
7067 fee_estimator: &fee_estimator,
7069 logger: Arc::clone(&logger),
7070 tx_broadcaster: &tx_broadcaster,
7071 default_config: UserConfig::default(),
7072 channel_monitors: &mut channel_monitors,
7075 nodes[0].node = &node_state_0;
7076 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7077 nodes[0].chan_monitor = &monitor;
7078 nodes[0].chain_monitor = chain_monitor;
7080 nodes[0].block_notifier = BlockNotifier::new(nodes[0].chain_monitor.clone());
7081 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7082 nodes[0].block_notifier.register_listener(nodes[0].node);
7084 check_added_monitors!(nodes[0], 1);
7086 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7087 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7089 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7091 // Check we don't broadcast any transactions following learning of per_commitment_point from B
7092 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7093 check_added_monitors!(nodes[0], 1);
7096 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7097 assert_eq!(node_txn.len(), 0);
7100 let mut reestablish_1 = Vec::with_capacity(1);
7101 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7102 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7103 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7104 reestablish_1.push(msg.clone());
7105 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7106 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7108 &ErrorAction::SendErrorMessage { ref msg } => {
7109 assert_eq!(msg.data, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
7111 _ => panic!("Unexpected event!"),
7114 panic!("Unexpected event")
7118 // Check we close channel detecting A is fallen-behind
7119 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7120 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7121 check_added_monitors!(nodes[1], 1);
7124 // Check A is able to claim to_remote output
7125 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7126 assert_eq!(node_txn.len(), 1);
7127 check_spends!(node_txn[0], chan.3);
7128 assert_eq!(node_txn[0].output.len(), 2);
7129 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7130 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7131 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
7132 let spend_txn = check_spendable_outputs!(nodes[0], 1);
7133 assert_eq!(spend_txn.len(), 1);
7134 check_spends!(spend_txn[0], node_txn[0]);
7138 fn test_check_htlc_underpaying() {
7139 // Send payment through A -> B but A is maliciously
7140 // sending a probe payment (i.e less than expected value0
7141 // to B, B should refuse payment.
7143 let chanmon_cfgs = create_chanmon_cfgs(2);
7144 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7145 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7146 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7148 // Create some initial channels
7149 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7151 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7153 // Node 3 is expecting payment of 100_000 but receive 10_000,
7154 // fail htlc like we didn't know the preimage.
7155 nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7156 nodes[1].node.process_pending_htlc_forwards();
7158 let events = nodes[1].node.get_and_clear_pending_msg_events();
7159 assert_eq!(events.len(), 1);
7160 let (update_fail_htlc, commitment_signed) = match events[0] {
7161 MessageSendEvent::UpdateHTLCs { node_id: _ , updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, ref update_fee, ref commitment_signed } } => {
7162 assert!(update_add_htlcs.is_empty());
7163 assert!(update_fulfill_htlcs.is_empty());
7164 assert_eq!(update_fail_htlcs.len(), 1);
7165 assert!(update_fail_malformed_htlcs.is_empty());
7166 assert!(update_fee.is_none());
7167 (update_fail_htlcs[0].clone(), commitment_signed)
7169 _ => panic!("Unexpected event"),
7171 check_added_monitors!(nodes[1], 1);
7173 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7174 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7176 // 10_000 msat as u64, followed by a height of 99 as u32
7177 let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7178 expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7179 expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7180 nodes[1].node.get_and_clear_pending_events();
7184 fn test_announce_disable_channels() {
7185 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7186 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7188 let chanmon_cfgs = create_chanmon_cfgs(2);
7189 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7190 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7191 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7193 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7194 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7195 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7198 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7199 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7201 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7202 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7203 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7204 assert_eq!(msg_events.len(), 3);
7205 for e in msg_events {
7207 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7208 let short_id = msg.contents.short_channel_id;
7209 // Check generated channel_update match list in PendingChannelUpdate
7210 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7211 panic!("Generated ChannelUpdate for wrong chan!");
7214 _ => panic!("Unexpected event"),
7218 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7219 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7220 assert_eq!(reestablish_1.len(), 3);
7221 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7222 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7223 assert_eq!(reestablish_2.len(), 3);
7225 // Reestablish chan_1
7226 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7227 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7228 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7229 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7230 // Reestablish chan_2
7231 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7232 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7233 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7234 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7235 // Reestablish chan_3
7236 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7237 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7238 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7239 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7241 nodes[0].node.timer_chan_freshness_every_min();
7242 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7246 fn test_bump_penalty_txn_on_revoked_commitment() {
7247 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7248 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7250 let chanmon_cfgs = create_chanmon_cfgs(2);
7251 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7252 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7253 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7255 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7256 let logger = Arc::new(test_utils::TestLogger::new());
7259 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7260 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7261 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30, logger.clone()).unwrap();
7262 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7264 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7265 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7266 assert_eq!(revoked_txn[0].output.len(), 4);
7267 assert_eq!(revoked_txn[0].input.len(), 1);
7268 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7269 let revoked_txid = revoked_txn[0].txid();
7271 let mut penalty_sum = 0;
7272 for outp in revoked_txn[0].output.iter() {
7273 if outp.script_pubkey.is_v0_p2wsh() {
7274 penalty_sum += outp.value;
7278 // Connect blocks to change height_timer range to see if we use right soonest_timelock
7279 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7281 // Actually revoke tx by claiming a HTLC
7282 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7283 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7284 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7285 check_added_monitors!(nodes[1], 1);
7287 // One or more justice tx should have been broadcast, check it
7291 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7292 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7293 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7294 assert_eq!(node_txn[0].output.len(), 1);
7295 check_spends!(node_txn[0], revoked_txn[0]);
7296 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7297 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7298 penalty_1 = node_txn[0].txid();
7302 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7303 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.bitcoin_hash());
7304 let mut penalty_2 = penalty_1;
7305 let mut feerate_2 = 0;
7307 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7308 assert_eq!(node_txn.len(), 1);
7309 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7310 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7311 assert_eq!(node_txn[0].output.len(), 1);
7312 check_spends!(node_txn[0], revoked_txn[0]);
7313 penalty_2 = node_txn[0].txid();
7314 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7315 assert_ne!(penalty_2, penalty_1);
7316 let fee_2 = penalty_sum - node_txn[0].output[0].value;
7317 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7318 // Verify 25% bump heuristic
7319 assert!(feerate_2 * 100 >= feerate_1 * 125);
7323 assert_ne!(feerate_2, 0);
7325 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7326 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7328 let mut feerate_3 = 0;
7330 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7331 assert_eq!(node_txn.len(), 1);
7332 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7333 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7334 assert_eq!(node_txn[0].output.len(), 1);
7335 check_spends!(node_txn[0], revoked_txn[0]);
7336 penalty_3 = node_txn[0].txid();
7337 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7338 assert_ne!(penalty_3, penalty_2);
7339 let fee_3 = penalty_sum - node_txn[0].output[0].value;
7340 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7341 // Verify 25% bump heuristic
7342 assert!(feerate_3 * 100 >= feerate_2 * 125);
7346 assert_ne!(feerate_3, 0);
7348 nodes[1].node.get_and_clear_pending_events();
7349 nodes[1].node.get_and_clear_pending_msg_events();
7353 fn test_bump_penalty_txn_on_revoked_htlcs() {
7354 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7355 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7357 let chanmon_cfgs = create_chanmon_cfgs(2);
7358 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7359 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7360 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7362 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7363 // Lock HTLC in both directions
7364 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7365 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7367 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7368 assert_eq!(revoked_local_txn[0].input.len(), 1);
7369 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7371 // Revoke local commitment tx
7372 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7374 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7375 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7376 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7377 check_closed_broadcast!(nodes[1], false);
7378 check_added_monitors!(nodes[1], 1);
7380 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7381 assert_eq!(revoked_htlc_txn.len(), 4);
7382 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7383 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7384 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7385 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7386 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7387 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7388 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7389 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7390 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7391 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7392 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7393 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7396 // Broadcast set of revoked txn on A
7397 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7398 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7400 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7401 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7406 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7407 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7408 // Verify claim tx are spending revoked HTLC txn
7409 assert_eq!(node_txn[4].input.len(), 2);
7410 assert_eq!(node_txn[4].output.len(), 1);
7411 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7412 first = node_txn[4].txid();
7413 // Store both feerates for later comparison
7414 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7415 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7416 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7420 // Connect three more block to see if bumped penalty are issued for HTLC txn
7421 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7422 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7424 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7425 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7427 check_spends!(node_txn[0], revoked_local_txn[0]);
7428 check_spends!(node_txn[1], revoked_local_txn[0]);
7433 // Few more blocks to confirm penalty txn
7434 let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7435 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7436 let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7438 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7439 assert_eq!(node_txn.len(), 1);
7441 assert_eq!(node_txn[0].input.len(), 2);
7442 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7443 // Verify bumped tx is different and 25% bump heuristic
7444 assert_ne!(first, node_txn[0].txid());
7445 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7446 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7447 assert!(feerate_2 * 100 > feerate_1 * 125);
7448 let txn = vec![node_txn[0].clone()];
7452 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7453 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7454 nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7455 connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7457 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7458 // We verify than no new transaction has been broadcast because previously
7459 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7460 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7461 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7462 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7463 // up bumped justice generation.
7464 assert_eq!(node_txn.len(), 0);
7467 check_closed_broadcast!(nodes[0], false);
7468 check_added_monitors!(nodes[0], 1);
7472 fn test_bump_penalty_txn_on_remote_commitment() {
7473 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7474 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7477 // Provide preimage for one
7478 // Check aggregation
7480 let chanmon_cfgs = create_chanmon_cfgs(2);
7481 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7482 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7483 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7485 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7486 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7487 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7489 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7490 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7491 assert_eq!(remote_txn[0].output.len(), 4);
7492 assert_eq!(remote_txn[0].input.len(), 1);
7493 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7495 // Claim a HTLC without revocation (provide B monitor with preimage)
7496 nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7497 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7498 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7499 check_added_monitors!(nodes[1], 2);
7501 // One or more claim tx should have been broadcast, check it
7504 let feerate_timeout;
7505 let feerate_preimage;
7507 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7508 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7509 assert_eq!(node_txn[0].input.len(), 1);
7510 assert_eq!(node_txn[1].input.len(), 1);
7511 check_spends!(node_txn[0], remote_txn[0]);
7512 check_spends!(node_txn[1], remote_txn[0]);
7513 check_spends!(node_txn[2], chan.3);
7514 check_spends!(node_txn[3], node_txn[2]);
7515 check_spends!(node_txn[4], node_txn[2]);
7516 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7517 timeout = node_txn[0].txid();
7518 let index = node_txn[0].input[0].previous_output.vout;
7519 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7520 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7522 preimage = node_txn[1].txid();
7523 let index = node_txn[1].input[0].previous_output.vout;
7524 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7525 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7527 timeout = node_txn[1].txid();
7528 let index = node_txn[1].input[0].previous_output.vout;
7529 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7530 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7532 preimage = node_txn[0].txid();
7533 let index = node_txn[0].input[0].previous_output.vout;
7534 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7535 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7539 assert_ne!(feerate_timeout, 0);
7540 assert_ne!(feerate_preimage, 0);
7542 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7543 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.bitcoin_hash());
7545 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7546 assert_eq!(node_txn.len(), 2);
7547 assert_eq!(node_txn[0].input.len(), 1);
7548 assert_eq!(node_txn[1].input.len(), 1);
7549 check_spends!(node_txn[0], remote_txn[0]);
7550 check_spends!(node_txn[1], remote_txn[0]);
7551 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7552 let index = node_txn[0].input[0].previous_output.vout;
7553 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7554 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7555 assert!(new_feerate * 100 > feerate_timeout * 125);
7556 assert_ne!(timeout, node_txn[0].txid());
7558 let index = node_txn[1].input[0].previous_output.vout;
7559 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7560 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7561 assert!(new_feerate * 100 > feerate_preimage * 125);
7562 assert_ne!(preimage, node_txn[1].txid());
7564 let index = node_txn[1].input[0].previous_output.vout;
7565 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7566 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7567 assert!(new_feerate * 100 > feerate_timeout * 125);
7568 assert_ne!(timeout, node_txn[1].txid());
7570 let index = node_txn[0].input[0].previous_output.vout;
7571 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7572 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7573 assert!(new_feerate * 100 > feerate_preimage * 125);
7574 assert_ne!(preimage, node_txn[0].txid());
7579 nodes[1].node.get_and_clear_pending_events();
7580 nodes[1].node.get_and_clear_pending_msg_events();
7584 fn test_set_outpoints_partial_claiming() {
7585 // - remote party claim tx, new bump tx
7586 // - disconnect remote claiming tx, new bump
7587 // - disconnect tx, see no tx anymore
7588 let chanmon_cfgs = create_chanmon_cfgs(2);
7589 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7590 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7591 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7593 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7594 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7595 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7597 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7598 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7599 assert_eq!(remote_txn.len(), 3);
7600 assert_eq!(remote_txn[0].output.len(), 4);
7601 assert_eq!(remote_txn[0].input.len(), 1);
7602 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7603 check_spends!(remote_txn[1], remote_txn[0]);
7604 check_spends!(remote_txn[2], remote_txn[0]);
7606 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7607 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7608 // Provide node A with both preimage
7609 nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7610 nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7611 check_added_monitors!(nodes[0], 2);
7612 nodes[0].node.get_and_clear_pending_events();
7613 nodes[0].node.get_and_clear_pending_msg_events();
7615 // Connect blocks on node A commitment transaction
7616 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7617 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7618 check_closed_broadcast!(nodes[0], false);
7619 check_added_monitors!(nodes[0], 1);
7620 // Verify node A broadcast tx claiming both HTLCs
7622 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7623 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7624 assert_eq!(node_txn.len(), 4);
7625 check_spends!(node_txn[0], remote_txn[0]);
7626 check_spends!(node_txn[1], chan.3);
7627 check_spends!(node_txn[2], node_txn[1]);
7628 check_spends!(node_txn[3], node_txn[1]);
7629 assert_eq!(node_txn[0].input.len(), 2);
7633 // Connect blocks on node B
7634 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7635 check_closed_broadcast!(nodes[1], false);
7636 check_added_monitors!(nodes[1], 1);
7637 // Verify node B broadcast 2 HTLC-timeout txn
7638 let partial_claim_tx = {
7639 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7640 assert_eq!(node_txn.len(), 3);
7641 check_spends!(node_txn[1], node_txn[0]);
7642 check_spends!(node_txn[2], node_txn[0]);
7643 assert_eq!(node_txn[1].input.len(), 1);
7644 assert_eq!(node_txn[2].input.len(), 1);
7648 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7649 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7650 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7652 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7653 assert_eq!(node_txn.len(), 1);
7654 check_spends!(node_txn[0], remote_txn[0]);
7655 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7658 nodes[0].node.get_and_clear_pending_msg_events();
7660 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7661 nodes[0].block_notifier.block_disconnected(&header, 102);
7663 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7664 assert_eq!(node_txn.len(), 1);
7665 check_spends!(node_txn[0], remote_txn[0]);
7666 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7670 //// Disconnect one more block and then reconnect multiple no transaction should be generated
7671 nodes[0].block_notifier.block_disconnected(&header, 101);
7672 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7674 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7675 assert_eq!(node_txn.len(), 0);
7681 fn test_counterparty_raa_skip_no_crash() {
7682 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7683 // commitment transaction, we would have happily carried on and provided them the next
7684 // commitment transaction based on one RAA forward. This would probably eventually have led to
7685 // channel closure, but it would not have resulted in funds loss. Still, our
7686 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7687 // check simply that the channel is closed in response to such an RAA, but don't check whether
7688 // we decide to punish our counterparty for revoking their funds (as we don't currently
7690 let chanmon_cfgs = create_chanmon_cfgs(2);
7691 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7692 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7693 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7694 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7696 let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7697 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7698 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7699 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7700 let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7702 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7703 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7704 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7705 check_added_monitors!(nodes[1], 1);
7709 fn test_bump_txn_sanitize_tracking_maps() {
7710 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7711 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7713 let chanmon_cfgs = create_chanmon_cfgs(2);
7714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7716 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7718 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7719 // Lock HTLC in both directions
7720 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7721 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7723 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7724 assert_eq!(revoked_local_txn[0].input.len(), 1);
7725 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7727 // Revoke local commitment tx
7728 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7730 // Broadcast set of revoked txn on A
7731 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7732 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7734 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7735 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7736 check_closed_broadcast!(nodes[0], false);
7737 check_added_monitors!(nodes[0], 1);
7739 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7740 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7741 check_spends!(node_txn[0], revoked_local_txn[0]);
7742 check_spends!(node_txn[1], revoked_local_txn[0]);
7743 check_spends!(node_txn[2], revoked_local_txn[0]);
7744 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7748 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7749 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7750 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.bitcoin_hash());
7752 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7753 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7754 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7755 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7761 fn test_override_channel_config() {
7762 let chanmon_cfgs = create_chanmon_cfgs(2);
7763 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7764 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7765 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7767 // Node0 initiates a channel to node1 using the override config.
7768 let mut override_config = UserConfig::default();
7769 override_config.own_channel_config.our_to_self_delay = 200;
7771 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7773 // Assert the channel created by node0 is using the override config.
7774 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7775 assert_eq!(res.channel_flags, 0);
7776 assert_eq!(res.to_self_delay, 200);
7780 fn test_override_0msat_htlc_minimum() {
7781 let mut zero_config = UserConfig::default();
7782 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7783 let chanmon_cfgs = create_chanmon_cfgs(2);
7784 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7785 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7786 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7788 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7789 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7790 assert_eq!(res.htlc_minimum_msat, 1);
7792 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
7793 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7794 assert_eq!(res.htlc_minimum_msat, 1);
7798 fn test_simple_payment_secret() {
7799 // Simple test of sending a payment with a payment_secret present. This does not use any AMP
7800 // features, however.
7801 let chanmon_cfgs = create_chanmon_cfgs(3);
7802 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7803 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7804 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7806 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7807 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
7808 let logger = Arc::new(test_utils::TestLogger::new());
7810 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7811 let payment_secret = PaymentSecret([0xdb; 32]);
7812 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7813 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
7814 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
7815 // Claiming with all the correct values but the wrong secret should result in nothing...
7816 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
7817 assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
7818 // ...but with the right secret we should be able to claim all the way back
7819 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
7823 fn test_simple_mpp() {
7824 // Simple test of sending a multi-path payment.
7825 let chanmon_cfgs = create_chanmon_cfgs(4);
7826 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7827 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7828 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7830 let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7831 let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7832 let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7833 let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7834 let logger = Arc::new(test_utils::TestLogger::new());
7836 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7837 let payment_secret = PaymentSecret([0xdb; 32]);
7838 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7839 let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, logger.clone()).unwrap();
7840 let path = route.paths[0].clone();
7841 route.paths.push(path);
7842 route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7843 route.paths[0][0].short_channel_id = chan_1_id;
7844 route.paths[0][1].short_channel_id = chan_3_id;
7845 route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7846 route.paths[1][0].short_channel_id = chan_2_id;
7847 route.paths[1][1].short_channel_id = chan_4_id;
7848 send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
7849 // Claiming with all the correct values but the wrong secret should result in nothing...
7850 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
7851 assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
7852 // ...but with the right secret we should be able to claim all the way back
7853 claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
7857 fn test_update_err_monitor_lockdown() {
7858 // Our monitor will lock update of local commitment transaction if a broadcastion condition
7859 // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
7860 // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
7862 // This scenario may happen in a watchtower setup, where watchtower process a block height
7863 // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
7864 // commitment at same time.
7866 let chanmon_cfgs = create_chanmon_cfgs(2);
7867 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7868 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7869 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7871 // Create some initial channel
7872 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7873 let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
7875 // Rebalance the network to generate htlc in the two directions
7876 send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
7878 // Route a HTLC from node 0 to node 1 (but don't settle)
7879 let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7881 // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
7882 let logger = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
7884 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7885 let monitor = monitors.get(&outpoint).unwrap();
7886 let mut w = test_utils::TestVecWriter(Vec::new());
7887 monitor.write_for_disk(&mut w).unwrap();
7888 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
7889 &mut ::std::io::Cursor::new(&w.0), Arc::new(test_utils::TestLogger::new())).unwrap().1;
7890 assert!(new_monitor == *monitor);
7891 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet, logger.clone() as Arc<Logger>));
7892 let watchtower = test_utils::TestChannelMonitor::new(chain_monitor, &chanmon_cfgs[0].tx_broadcaster, logger.clone(), &chanmon_cfgs[0].fee_estimator);
7893 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
7896 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7897 watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
7899 // Try to update ChannelMonitor
7900 assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
7901 check_added_monitors!(nodes[1], 1);
7902 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7903 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7904 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
7905 if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
7906 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator) {
7907 if let Err(_) = watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
7908 if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
7909 } else { assert!(false); }
7910 } else { assert!(false); };
7911 // Our local monitor is in-sync and hasn't processed yet timeout
7912 check_added_monitors!(nodes[0], 1);
7913 let events = nodes[0].node.get_and_clear_pending_events();
7914 assert_eq!(events.len(), 1);