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::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
8 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
9 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT};
10 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
11 use ln::channel::{Channel, ChannelError};
12 use ln::{chan_utils, onion_utils};
13 use ln::router::{Route, RouteHop};
14 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
16 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
17 use util::enforcing_trait_impls::EnforcingChannelKeys;
19 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
20 use util::errors::APIError;
21 use util::ser::{Writeable, Writer, ReadableArgs};
22 use util::config::UserConfig;
23 use util::logger::Logger;
25 use bitcoin::util::hash::BitcoinHash;
26 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
27 use bitcoin::util::bip143;
28 use bitcoin::util::address::Address;
29 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
30 use bitcoin::blockdata::block::{Block, BlockHeader};
31 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
32 use bitcoin::blockdata::script::{Builder, Script};
33 use bitcoin::blockdata::opcodes;
34 use bitcoin::blockdata::constants::genesis_block;
35 use bitcoin::network::constants::Network;
37 use bitcoin_hashes::sha256::Hash as Sha256;
38 use bitcoin_hashes::Hash;
40 use secp256k1::{Secp256k1, Message};
41 use secp256k1::key::{PublicKey,SecretKey};
43 use std::collections::{BTreeSet, HashMap, HashSet};
44 use std::default::Default;
45 use std::sync::{Arc, Mutex};
46 use std::sync::atomic::Ordering;
49 use rand::{thread_rng, Rng};
51 use ln::functional_test_utils::*;
54 fn test_insane_channel_opens() {
55 // Stand up a network of 2 nodes
56 let chanmon_cfgs = create_chanmon_cfgs(2);
57 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
58 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
59 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
61 // Instantiate channel parameters where we push the maximum msats given our
63 let channel_value_sat = 31337; // same as funding satoshis
64 let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_our_channel_reserve_satoshis(channel_value_sat);
65 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
67 // Have node0 initiate a channel to node1 with aforementioned parameters
68 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
70 // Extract the channel open message from node0 to node1
71 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
73 // Test helper that asserts we get the correct error string given a mutator
74 // that supposedly makes the channel open message insane
75 let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
76 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &message_mutator(open_channel_message.clone()));
77 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
78 assert_eq!(msg_events.len(), 1);
79 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
81 &ErrorAction::SendErrorMessage { .. } => {
82 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
84 _ => panic!("unexpected event!"),
86 } else { assert!(false); }
89 use ln::channel::MAX_FUNDING_SATOSHIS;
90 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
92 // Test all mutations that would make the channel open message insane
93 insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
95 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
97 insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
99 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
101 insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
103 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 });
105 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 });
107 insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
109 insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
113 fn test_async_inbound_update_fee() {
114 let chanmon_cfgs = create_chanmon_cfgs(2);
115 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
116 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
117 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
118 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
119 let channel_id = chan.2;
122 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
126 // send (1) commitment_signed -.
127 // <- update_add_htlc/commitment_signed
128 // send (2) RAA (awaiting remote revoke) -.
129 // (1) commitment_signed is delivered ->
130 // .- send (3) RAA (awaiting remote revoke)
131 // (2) RAA is delivered ->
132 // .- send (4) commitment_signed
133 // <- (3) RAA is delivered
134 // send (5) commitment_signed -.
135 // <- (4) commitment_signed is delivered
137 // (5) commitment_signed is delivered ->
139 // (6) RAA is delivered ->
141 // First nodes[0] generates an update_fee
142 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
143 check_added_monitors!(nodes[0], 1);
145 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
146 assert_eq!(events_0.len(), 1);
147 let (update_msg, commitment_signed) = match events_0[0] { // (1)
148 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
149 (update_fee.as_ref(), commitment_signed)
151 _ => panic!("Unexpected event"),
154 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
156 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
157 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
158 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
159 check_added_monitors!(nodes[1], 1);
161 let payment_event = {
162 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
163 assert_eq!(events_1.len(), 1);
164 SendEvent::from_event(events_1.remove(0))
166 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
167 assert_eq!(payment_event.msgs.len(), 1);
169 // ...now when the messages get delivered everyone should be happy
170 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
171 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
172 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
173 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
174 check_added_monitors!(nodes[0], 1);
176 // deliver(1), generate (3):
177 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
178 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
179 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
180 check_added_monitors!(nodes[1], 1);
182 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
183 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
184 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
185 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
186 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
187 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
188 assert!(bs_update.update_fee.is_none()); // (4)
189 check_added_monitors!(nodes[1], 1);
191 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
192 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
193 assert!(as_update.update_add_htlcs.is_empty()); // (5)
194 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
195 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
196 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
197 assert!(as_update.update_fee.is_none()); // (5)
198 check_added_monitors!(nodes[0], 1);
200 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
201 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
202 // only (6) so get_event_msg's assert(len == 1) passes
203 check_added_monitors!(nodes[0], 1);
205 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
206 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
207 check_added_monitors!(nodes[1], 1);
209 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
210 check_added_monitors!(nodes[0], 1);
212 let events_2 = nodes[0].node.get_and_clear_pending_events();
213 assert_eq!(events_2.len(), 1);
215 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
216 _ => panic!("Unexpected event"),
219 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
220 check_added_monitors!(nodes[1], 1);
224 fn test_update_fee_unordered_raa() {
225 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
226 // crash in an earlier version of the update_fee patch)
227 let chanmon_cfgs = create_chanmon_cfgs(2);
228 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
229 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
230 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
231 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
232 let channel_id = chan.2;
235 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
237 // First nodes[0] generates an update_fee
238 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
239 check_added_monitors!(nodes[0], 1);
241 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
242 assert_eq!(events_0.len(), 1);
243 let update_msg = match events_0[0] { // (1)
244 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
247 _ => panic!("Unexpected event"),
250 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
252 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
253 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
254 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
255 check_added_monitors!(nodes[1], 1);
257 let payment_event = {
258 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
259 assert_eq!(events_1.len(), 1);
260 SendEvent::from_event(events_1.remove(0))
262 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
263 assert_eq!(payment_event.msgs.len(), 1);
265 // ...now when the messages get delivered everyone should be happy
266 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
267 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
268 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
269 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
270 check_added_monitors!(nodes[0], 1);
272 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
273 check_added_monitors!(nodes[1], 1);
275 // We can't continue, sadly, because our (1) now has a bogus signature
279 fn test_multi_flight_update_fee() {
280 let chanmon_cfgs = create_chanmon_cfgs(2);
281 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
282 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
283 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
284 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
285 let channel_id = chan.2;
288 // update_fee/commitment_signed ->
289 // .- send (1) RAA and (2) commitment_signed
290 // update_fee (never committed) ->
292 // We have to manually generate the above update_fee, it is allowed by the protocol but we
293 // don't track which updates correspond to which revoke_and_ack responses so we're in
294 // AwaitingRAA mode and will not generate the update_fee yet.
295 // <- (1) RAA delivered
296 // (3) is generated and send (4) CS -.
297 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
298 // know the per_commitment_point to use for it.
299 // <- (2) commitment_signed delivered
301 // B should send no response here
302 // (4) commitment_signed delivered ->
303 // <- RAA/commitment_signed delivered
306 // First nodes[0] generates an update_fee
307 let initial_feerate = get_feerate!(nodes[0], channel_id);
308 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
309 check_added_monitors!(nodes[0], 1);
311 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
312 assert_eq!(events_0.len(), 1);
313 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
314 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
315 (update_fee.as_ref().unwrap(), commitment_signed)
317 _ => panic!("Unexpected event"),
320 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
321 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
322 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
323 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
324 check_added_monitors!(nodes[1], 1);
326 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
328 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
329 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
330 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
332 // Create the (3) update_fee message that nodes[0] will generate before it does...
333 let mut update_msg_2 = msgs::UpdateFee {
334 channel_id: update_msg_1.channel_id.clone(),
335 feerate_per_kw: (initial_feerate + 30) as u32,
338 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
340 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
342 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
344 // Deliver (1), generating (3) and (4)
345 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
346 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
347 check_added_monitors!(nodes[0], 1);
348 assert!(as_second_update.update_add_htlcs.is_empty());
349 assert!(as_second_update.update_fulfill_htlcs.is_empty());
350 assert!(as_second_update.update_fail_htlcs.is_empty());
351 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
352 // Check that the update_fee newly generated matches what we delivered:
353 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
354 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
356 // Deliver (2) commitment_signed
357 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
358 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
359 check_added_monitors!(nodes[0], 1);
360 // No commitment_signed so get_event_msg's assert(len == 1) passes
362 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
363 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
364 check_added_monitors!(nodes[1], 1);
367 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
368 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
369 check_added_monitors!(nodes[1], 1);
371 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
372 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
373 check_added_monitors!(nodes[0], 1);
375 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
376 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
377 // No commitment_signed so get_event_msg's assert(len == 1) passes
378 check_added_monitors!(nodes[0], 1);
380 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
381 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
382 check_added_monitors!(nodes[1], 1);
386 fn test_1_conf_open() {
387 // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
388 // tests that we properly send one in that case.
389 let mut alice_config = UserConfig::default();
390 alice_config.own_channel_config.minimum_depth = 1;
391 alice_config.channel_options.announced_channel = true;
392 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
393 let mut bob_config = UserConfig::default();
394 bob_config.own_channel_config.minimum_depth = 1;
395 bob_config.channel_options.announced_channel = true;
396 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
397 let chanmon_cfgs = create_chanmon_cfgs(2);
398 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
399 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
400 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
402 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
403 assert!(nodes[0].chain_monitor.does_match_tx(&tx));
404 assert!(nodes[1].chain_monitor.does_match_tx(&tx));
406 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
407 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
408 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()));
410 nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
411 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
412 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
415 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
416 node.router.handle_channel_update(&as_update).unwrap();
417 node.router.handle_channel_update(&bs_update).unwrap();
421 fn do_test_sanity_on_in_flight_opens(steps: u8) {
422 // Previously, we had issues deserializing channels when we hadn't connected the first block
423 // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
424 // serialization round-trips and simply do steps towards opening a channel and then drop the
427 let chanmon_cfgs = create_chanmon_cfgs(2);
428 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
429 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
430 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
432 if steps & 0b1000_0000 != 0{
433 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
434 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
435 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
438 if steps & 0x0f == 0 { return; }
439 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
440 let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
442 if steps & 0x0f == 1 { return; }
443 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &open_channel);
444 let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
446 if steps & 0x0f == 2 { return; }
447 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::supported(), &accept_channel);
449 let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
451 if steps & 0x0f == 3 { return; }
453 nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
454 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
455 assert_eq!(added_monitors.len(), 1);
456 assert_eq!(added_monitors[0].0, funding_output);
457 added_monitors.clear();
459 let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
461 if steps & 0x0f == 4 { return; }
462 nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
464 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
465 assert_eq!(added_monitors.len(), 1);
466 assert_eq!(added_monitors[0].0, funding_output);
467 added_monitors.clear();
469 let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
471 if steps & 0x0f == 5 { return; }
472 nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
474 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
475 assert_eq!(added_monitors.len(), 1);
476 assert_eq!(added_monitors[0].0, funding_output);
477 added_monitors.clear();
480 let events_4 = nodes[0].node.get_and_clear_pending_events();
481 assert_eq!(events_4.len(), 1);
483 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
484 assert_eq!(user_channel_id, 42);
485 assert_eq!(*funding_txo, funding_output);
487 _ => panic!("Unexpected event"),
490 if steps & 0x0f == 6 { return; }
491 create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
493 if steps & 0x0f == 7 { return; }
494 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
495 create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
499 fn test_sanity_on_in_flight_opens() {
500 do_test_sanity_on_in_flight_opens(0);
501 do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
502 do_test_sanity_on_in_flight_opens(1);
503 do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
504 do_test_sanity_on_in_flight_opens(2);
505 do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
506 do_test_sanity_on_in_flight_opens(3);
507 do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
508 do_test_sanity_on_in_flight_opens(4);
509 do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
510 do_test_sanity_on_in_flight_opens(5);
511 do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
512 do_test_sanity_on_in_flight_opens(6);
513 do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
514 do_test_sanity_on_in_flight_opens(7);
515 do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
516 do_test_sanity_on_in_flight_opens(8);
517 do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
521 fn test_update_fee_vanilla() {
522 let chanmon_cfgs = create_chanmon_cfgs(2);
523 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
524 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
525 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
526 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
527 let channel_id = chan.2;
529 let feerate = get_feerate!(nodes[0], channel_id);
530 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
531 check_added_monitors!(nodes[0], 1);
533 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
534 assert_eq!(events_0.len(), 1);
535 let (update_msg, commitment_signed) = match events_0[0] {
536 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 } } => {
537 (update_fee.as_ref(), commitment_signed)
539 _ => panic!("Unexpected event"),
541 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
543 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
544 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
545 check_added_monitors!(nodes[1], 1);
547 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
548 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
549 check_added_monitors!(nodes[0], 1);
551 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
552 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
553 // No commitment_signed so get_event_msg's assert(len == 1) passes
554 check_added_monitors!(nodes[0], 1);
556 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
557 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
558 check_added_monitors!(nodes[1], 1);
562 fn test_update_fee_that_funder_cannot_afford() {
563 let chanmon_cfgs = create_chanmon_cfgs(2);
564 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
565 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
566 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
567 let channel_value = 1888;
568 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::supported(), InitFeatures::supported());
569 let channel_id = chan.2;
572 nodes[0].node.update_fee(channel_id, feerate).unwrap();
573 check_added_monitors!(nodes[0], 1);
574 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
576 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
578 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
580 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
581 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
583 let mut chan_lock = nodes[1].node.channel_state.lock().unwrap();
584 let chan = chan_lock.by_id.get_mut(&channel_id).unwrap();
586 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
587 let num_htlcs = chan.channel_monitor().get_latest_local_commitment_txn()[0].output.len() - 2;
588 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
589 let mut actual_fee = chan.channel_monitor().get_latest_local_commitment_txn()[0].output.iter().fold(0, |acc, output| acc + output.value);
590 actual_fee = channel_value - actual_fee;
591 assert_eq!(total_fee, actual_fee);
594 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
595 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
596 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
597 check_added_monitors!(nodes[0], 1);
599 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
601 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
603 //While producing the commitment_signed response after handling a received update_fee request the
604 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
605 //Should produce and error.
606 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
607 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
608 check_added_monitors!(nodes[1], 1);
609 check_closed_broadcast!(nodes[1], true);
613 fn test_update_fee_with_fundee_update_add_htlc() {
614 let chanmon_cfgs = create_chanmon_cfgs(2);
615 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
616 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
617 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
618 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
619 let channel_id = chan.2;
622 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
624 let feerate = get_feerate!(nodes[0], channel_id);
625 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
626 check_added_monitors!(nodes[0], 1);
628 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
629 assert_eq!(events_0.len(), 1);
630 let (update_msg, commitment_signed) = match events_0[0] {
631 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 } } => {
632 (update_fee.as_ref(), commitment_signed)
634 _ => panic!("Unexpected event"),
636 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
637 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
638 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
639 check_added_monitors!(nodes[1], 1);
641 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
643 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
645 // nothing happens since node[1] is in AwaitingRemoteRevoke
646 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
648 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
649 assert_eq!(added_monitors.len(), 0);
650 added_monitors.clear();
652 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
653 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
654 // node[1] has nothing to do
656 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
657 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
658 check_added_monitors!(nodes[0], 1);
660 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
661 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
662 // No commitment_signed so get_event_msg's assert(len == 1) passes
663 check_added_monitors!(nodes[0], 1);
664 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
665 check_added_monitors!(nodes[1], 1);
666 // AwaitingRemoteRevoke ends here
668 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
669 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
670 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
671 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
672 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
673 assert_eq!(commitment_update.update_fee.is_none(), true);
675 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
676 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
677 check_added_monitors!(nodes[0], 1);
678 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
680 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
681 check_added_monitors!(nodes[1], 1);
682 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
684 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
685 check_added_monitors!(nodes[1], 1);
686 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
687 // No commitment_signed so get_event_msg's assert(len == 1) passes
689 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
690 check_added_monitors!(nodes[0], 1);
691 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
693 expect_pending_htlcs_forwardable!(nodes[0]);
695 let events = nodes[0].node.get_and_clear_pending_events();
696 assert_eq!(events.len(), 1);
698 Event::PaymentReceived { .. } => { },
699 _ => panic!("Unexpected event"),
702 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
704 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
705 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
706 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
710 fn test_update_fee() {
711 let chanmon_cfgs = create_chanmon_cfgs(2);
712 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
713 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
714 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
715 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
716 let channel_id = chan.2;
719 // (1) update_fee/commitment_signed ->
720 // <- (2) revoke_and_ack
721 // .- send (3) commitment_signed
722 // (4) update_fee/commitment_signed ->
723 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
724 // <- (3) commitment_signed delivered
725 // send (6) revoke_and_ack -.
726 // <- (5) deliver revoke_and_ack
727 // (6) deliver revoke_and_ack ->
728 // .- send (7) commitment_signed in response to (4)
729 // <- (7) deliver commitment_signed
732 // Create and deliver (1)...
733 let feerate = get_feerate!(nodes[0], channel_id);
734 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
735 check_added_monitors!(nodes[0], 1);
737 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
738 assert_eq!(events_0.len(), 1);
739 let (update_msg, commitment_signed) = match events_0[0] {
740 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 } } => {
741 (update_fee.as_ref(), commitment_signed)
743 _ => panic!("Unexpected event"),
745 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
747 // Generate (2) and (3):
748 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
749 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
750 check_added_monitors!(nodes[1], 1);
753 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
754 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
755 check_added_monitors!(nodes[0], 1);
757 // Create and deliver (4)...
758 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
759 check_added_monitors!(nodes[0], 1);
760 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
761 assert_eq!(events_0.len(), 1);
762 let (update_msg, commitment_signed) = match events_0[0] {
763 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 } } => {
764 (update_fee.as_ref(), commitment_signed)
766 _ => panic!("Unexpected event"),
769 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
770 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
771 check_added_monitors!(nodes[1], 1);
773 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
774 // No commitment_signed so get_event_msg's assert(len == 1) passes
776 // Handle (3), creating (6):
777 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
778 check_added_monitors!(nodes[0], 1);
779 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
780 // No commitment_signed so get_event_msg's assert(len == 1) passes
783 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
784 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
785 check_added_monitors!(nodes[0], 1);
787 // Deliver (6), creating (7):
788 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
789 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
790 assert!(commitment_update.update_add_htlcs.is_empty());
791 assert!(commitment_update.update_fulfill_htlcs.is_empty());
792 assert!(commitment_update.update_fail_htlcs.is_empty());
793 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
794 assert!(commitment_update.update_fee.is_none());
795 check_added_monitors!(nodes[1], 1);
798 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
799 check_added_monitors!(nodes[0], 1);
800 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
801 // No commitment_signed so get_event_msg's assert(len == 1) passes
803 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
804 check_added_monitors!(nodes[1], 1);
805 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
807 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
808 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
809 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
813 fn pre_funding_lock_shutdown_test() {
814 // Test sending a shutdown prior to funding_locked after funding generation
815 let chanmon_cfgs = create_chanmon_cfgs(2);
816 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
817 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
818 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
819 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::supported(), InitFeatures::supported());
820 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
821 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
822 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
824 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
825 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
826 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
827 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
828 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
830 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
831 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
832 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
833 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
834 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
835 assert!(node_0_none.is_none());
837 assert!(nodes[0].node.list_channels().is_empty());
838 assert!(nodes[1].node.list_channels().is_empty());
842 fn updates_shutdown_wait() {
843 // Test sending a shutdown with outstanding updates pending
844 let chanmon_cfgs = create_chanmon_cfgs(3);
845 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
846 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
847 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
848 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
849 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
850 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
851 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
853 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
855 nodes[0].node.close_channel(&chan_1.2).unwrap();
856 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
857 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
858 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
859 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
861 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
862 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
864 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
865 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
866 else { panic!("New sends should fail!") };
867 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
868 else { panic!("New sends should fail!") };
870 assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
871 check_added_monitors!(nodes[2], 1);
872 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
873 assert!(updates.update_add_htlcs.is_empty());
874 assert!(updates.update_fail_htlcs.is_empty());
875 assert!(updates.update_fail_malformed_htlcs.is_empty());
876 assert!(updates.update_fee.is_none());
877 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
878 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
879 check_added_monitors!(nodes[1], 1);
880 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
881 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
883 assert!(updates_2.update_add_htlcs.is_empty());
884 assert!(updates_2.update_fail_htlcs.is_empty());
885 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
886 assert!(updates_2.update_fee.is_none());
887 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
888 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
889 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
891 let events = nodes[0].node.get_and_clear_pending_events();
892 assert_eq!(events.len(), 1);
894 Event::PaymentSent { ref payment_preimage } => {
895 assert_eq!(our_payment_preimage, *payment_preimage);
897 _ => panic!("Unexpected event"),
900 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
901 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
902 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
903 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
904 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
905 assert!(node_0_none.is_none());
907 assert!(nodes[0].node.list_channels().is_empty());
909 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
910 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
911 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
912 assert!(nodes[1].node.list_channels().is_empty());
913 assert!(nodes[2].node.list_channels().is_empty());
917 fn htlc_fail_async_shutdown() {
918 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
919 let chanmon_cfgs = create_chanmon_cfgs(3);
920 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
921 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
922 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
923 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
924 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
926 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
927 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
928 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
929 check_added_monitors!(nodes[0], 1);
930 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
931 assert_eq!(updates.update_add_htlcs.len(), 1);
932 assert!(updates.update_fulfill_htlcs.is_empty());
933 assert!(updates.update_fail_htlcs.is_empty());
934 assert!(updates.update_fail_malformed_htlcs.is_empty());
935 assert!(updates.update_fee.is_none());
937 nodes[1].node.close_channel(&chan_1.2).unwrap();
938 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
939 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
940 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
942 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
943 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
944 check_added_monitors!(nodes[1], 1);
945 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
946 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
948 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
949 assert!(updates_2.update_add_htlcs.is_empty());
950 assert!(updates_2.update_fulfill_htlcs.is_empty());
951 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
952 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
953 assert!(updates_2.update_fee.is_none());
955 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
956 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
958 let events = nodes[0].node.get_and_clear_pending_events();
959 assert_eq!(events.len(), 1);
961 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
962 assert_eq!(our_payment_hash, *payment_hash);
963 assert!(!rejected_by_dest);
965 _ => panic!("Unexpected event"),
968 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
969 assert_eq!(msg_events.len(), 2);
970 let node_0_closing_signed = match msg_events[0] {
971 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
972 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
975 _ => panic!("Unexpected event"),
977 match msg_events[1] {
978 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
979 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
981 _ => panic!("Unexpected event"),
984 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
985 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
986 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
987 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
988 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
989 assert!(node_0_none.is_none());
991 assert!(nodes[0].node.list_channels().is_empty());
993 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
994 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
995 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
996 assert!(nodes[1].node.list_channels().is_empty());
997 assert!(nodes[2].node.list_channels().is_empty());
1000 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1001 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1002 // messages delivered prior to disconnect
1003 let chanmon_cfgs = create_chanmon_cfgs(3);
1004 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1005 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1006 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1007 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1008 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1010 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1012 nodes[1].node.close_channel(&chan_1.2).unwrap();
1013 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1015 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1016 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1018 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1022 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1023 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1025 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1026 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1027 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1028 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1030 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1031 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1032 assert!(node_1_shutdown == node_1_2nd_shutdown);
1034 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1035 let node_0_2nd_shutdown = if recv_count > 0 {
1036 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1037 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1040 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1041 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1042 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1044 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1046 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1047 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1049 assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
1050 check_added_monitors!(nodes[2], 1);
1051 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1052 assert!(updates.update_add_htlcs.is_empty());
1053 assert!(updates.update_fail_htlcs.is_empty());
1054 assert!(updates.update_fail_malformed_htlcs.is_empty());
1055 assert!(updates.update_fee.is_none());
1056 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1057 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1058 check_added_monitors!(nodes[1], 1);
1059 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1060 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1062 assert!(updates_2.update_add_htlcs.is_empty());
1063 assert!(updates_2.update_fail_htlcs.is_empty());
1064 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1065 assert!(updates_2.update_fee.is_none());
1066 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1067 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1068 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1070 let events = nodes[0].node.get_and_clear_pending_events();
1071 assert_eq!(events.len(), 1);
1073 Event::PaymentSent { ref payment_preimage } => {
1074 assert_eq!(our_payment_preimage, *payment_preimage);
1076 _ => panic!("Unexpected event"),
1079 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1081 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1082 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1083 assert!(node_1_closing_signed.is_some());
1086 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1087 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1089 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1090 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1091 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1092 if recv_count == 0 {
1093 // If all closing_signeds weren't delivered we can just resume where we left off...
1094 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1096 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1097 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1098 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1100 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1101 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1102 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1104 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1105 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1107 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1108 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1109 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1111 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1112 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1113 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1114 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1115 assert!(node_0_none.is_none());
1117 // If one node, however, received + responded with an identical closing_signed we end
1118 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1119 // There isn't really anything better we can do simply, but in the future we might
1120 // explore storing a set of recently-closed channels that got disconnected during
1121 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1122 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1124 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1126 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1127 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1128 assert_eq!(msg_events.len(), 1);
1129 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1131 &ErrorAction::SendErrorMessage { ref msg } => {
1132 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1133 assert_eq!(msg.channel_id, chan_1.2);
1135 _ => panic!("Unexpected event!"),
1137 } else { panic!("Needed SendErrorMessage close"); }
1139 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1140 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1141 // closing_signed so we do it ourselves
1142 check_closed_broadcast!(nodes[0], false);
1143 check_added_monitors!(nodes[0], 1);
1146 assert!(nodes[0].node.list_channels().is_empty());
1148 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1149 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1150 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1151 assert!(nodes[1].node.list_channels().is_empty());
1152 assert!(nodes[2].node.list_channels().is_empty());
1156 fn test_shutdown_rebroadcast() {
1157 do_test_shutdown_rebroadcast(0);
1158 do_test_shutdown_rebroadcast(1);
1159 do_test_shutdown_rebroadcast(2);
1163 fn fake_network_test() {
1164 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1165 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1166 let chanmon_cfgs = create_chanmon_cfgs(4);
1167 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1168 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1169 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1171 // Create some initial channels
1172 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1173 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1174 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1176 // Rebalance the network a bit by relaying one payment through all the channels...
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);
1179 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1180 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1182 // Send some more payments
1183 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1184 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1185 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1187 // Test failure packets
1188 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1189 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1191 // Add a new channel that skips 3
1192 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1194 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1195 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_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);
1199 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1200 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1202 // Do some rebalance loop payments, simultaneously
1203 let mut hops = Vec::with_capacity(3);
1204 hops.push(RouteHop {
1205 pubkey: nodes[2].node.get_our_node_id(),
1206 node_features: NodeFeatures::empty(),
1207 short_channel_id: chan_2.0.contents.short_channel_id,
1208 channel_features: ChannelFeatures::empty(),
1210 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1212 hops.push(RouteHop {
1213 pubkey: nodes[3].node.get_our_node_id(),
1214 node_features: NodeFeatures::empty(),
1215 short_channel_id: chan_3.0.contents.short_channel_id,
1216 channel_features: ChannelFeatures::empty(),
1218 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1220 hops.push(RouteHop {
1221 pubkey: nodes[1].node.get_our_node_id(),
1222 node_features: NodeFeatures::empty(),
1223 short_channel_id: chan_4.0.contents.short_channel_id,
1224 channel_features: ChannelFeatures::empty(),
1226 cltv_expiry_delta: TEST_FINAL_CLTV,
1228 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;
1229 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;
1230 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1232 let mut hops = Vec::with_capacity(3);
1233 hops.push(RouteHop {
1234 pubkey: nodes[3].node.get_our_node_id(),
1235 node_features: NodeFeatures::empty(),
1236 short_channel_id: chan_4.0.contents.short_channel_id,
1237 channel_features: ChannelFeatures::empty(),
1239 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1241 hops.push(RouteHop {
1242 pubkey: nodes[2].node.get_our_node_id(),
1243 node_features: NodeFeatures::empty(),
1244 short_channel_id: chan_3.0.contents.short_channel_id,
1245 channel_features: ChannelFeatures::empty(),
1247 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1249 hops.push(RouteHop {
1250 pubkey: nodes[1].node.get_our_node_id(),
1251 node_features: NodeFeatures::empty(),
1252 short_channel_id: chan_2.0.contents.short_channel_id,
1253 channel_features: ChannelFeatures::empty(),
1255 cltv_expiry_delta: TEST_FINAL_CLTV,
1257 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;
1258 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;
1259 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1261 // Claim the rebalances...
1262 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1263 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1265 // Add a duplicate new channel from 2 to 4
1266 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1268 // Send some payments across both channels
1269 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1270 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1271 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1274 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1275 let events = nodes[0].node.get_and_clear_pending_msg_events();
1276 assert_eq!(events.len(), 0);
1277 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);
1279 //TODO: Test that routes work again here as we've been notified that the channel is full
1281 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1282 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1283 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1285 // Close down the channels...
1286 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1287 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1288 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1289 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1290 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1294 fn holding_cell_htlc_counting() {
1295 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1296 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1297 // commitment dance rounds.
1298 let chanmon_cfgs = create_chanmon_cfgs(3);
1299 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1300 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1301 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1302 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1303 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1305 let mut payments = Vec::new();
1306 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1307 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1308 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1309 nodes[1].node.send_payment(route, payment_hash).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 route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1323 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1324 if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() {
1325 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
1326 } else { panic!("Unexpected event"); }
1327 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1328 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1330 // This should also be true if we try to forward a payment.
1331 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1332 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1333 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
1334 check_added_monitors!(nodes[0], 1);
1336 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1337 assert_eq!(events.len(), 1);
1338 let payment_event = SendEvent::from_event(events.pop().unwrap());
1339 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1341 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1342 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1343 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1344 // fails), the second will process the resulting failure and fail the HTLC backward.
1345 expect_pending_htlcs_forwardable!(nodes[1]);
1346 expect_pending_htlcs_forwardable!(nodes[1]);
1347 check_added_monitors!(nodes[1], 1);
1349 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1350 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1351 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1353 let events = nodes[0].node.get_and_clear_pending_msg_events();
1354 assert_eq!(events.len(), 1);
1356 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1357 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1359 _ => panic!("Unexpected event"),
1362 let events = nodes[0].node.get_and_clear_pending_events();
1363 assert_eq!(events.len(), 1);
1365 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1366 assert_eq!(payment_hash, payment_hash_2);
1367 assert!(!rejected_by_dest);
1369 _ => panic!("Unexpected event"),
1372 // Now forward all the pending HTLCs and claim them back
1373 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1374 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1375 check_added_monitors!(nodes[2], 1);
1377 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1378 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1379 check_added_monitors!(nodes[1], 1);
1380 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1382 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1383 check_added_monitors!(nodes[1], 1);
1384 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1386 for ref update in as_updates.update_add_htlcs.iter() {
1387 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1389 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1390 check_added_monitors!(nodes[2], 1);
1391 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1392 check_added_monitors!(nodes[2], 1);
1393 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1395 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1396 check_added_monitors!(nodes[1], 1);
1397 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1398 check_added_monitors!(nodes[1], 1);
1399 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1401 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1402 check_added_monitors!(nodes[2], 1);
1404 expect_pending_htlcs_forwardable!(nodes[2]);
1406 let events = nodes[2].node.get_and_clear_pending_events();
1407 assert_eq!(events.len(), payments.len());
1408 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1410 &Event::PaymentReceived { ref payment_hash, .. } => {
1411 assert_eq!(*payment_hash, *hash);
1413 _ => panic!("Unexpected event"),
1417 for (preimage, _) in payments.drain(..) {
1418 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1421 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1425 fn duplicate_htlc_test() {
1426 // Test that we accept duplicate payment_hash HTLCs across the network and that
1427 // claiming/failing them are all separate and don't affect each other
1428 let chanmon_cfgs = create_chanmon_cfgs(6);
1429 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1430 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1431 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1433 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1434 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::supported(), InitFeatures::supported());
1435 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1436 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1437 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
1438 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
1440 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1442 *nodes[0].network_payment_count.borrow_mut() -= 1;
1443 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1445 *nodes[0].network_payment_count.borrow_mut() -= 1;
1446 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1448 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1449 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1450 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1454 fn test_duplicate_htlc_different_direction_onchain() {
1455 // Test that ChannelMonitor doesn't generate 2 preimage txn
1456 // when we have 2 HTLCs with same preimage that go across a node
1457 // in opposite directions.
1458 let chanmon_cfgs = create_chanmon_cfgs(2);
1459 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1460 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1461 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1463 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1466 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1468 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1470 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV).unwrap();
1471 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1473 // Provide preimage to node 0 by claiming payment
1474 nodes[0].node.claim_funds(payment_preimage, 800_000);
1475 check_added_monitors!(nodes[0], 1);
1477 // Broadcast node 1 commitment txn
1478 let remote_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
1480 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1481 let mut has_both_htlcs = 0; // check htlcs match ones committed
1482 for outp in remote_txn[0].output.iter() {
1483 if outp.value == 800_000 / 1000 {
1484 has_both_htlcs += 1;
1485 } else if outp.value == 900_000 / 1000 {
1486 has_both_htlcs += 1;
1489 assert_eq!(has_both_htlcs, 2);
1491 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1492 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1493 check_added_monitors!(nodes[0], 1);
1495 // Check we only broadcast 1 timeout tx
1496 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1497 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()) };
1498 assert_eq!(claim_txn.len(), 5);
1499 check_spends!(claim_txn[2], chan_1.3);
1500 check_spends!(claim_txn[3], claim_txn[2]);
1501 assert_eq!(htlc_pair.0.input.len(), 1);
1502 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1503 check_spends!(htlc_pair.0, remote_txn[0]);
1504 assert_eq!(htlc_pair.1.input.len(), 1);
1505 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1506 check_spends!(htlc_pair.1, remote_txn[0]);
1508 let events = nodes[0].node.get_and_clear_pending_msg_events();
1509 assert_eq!(events.len(), 2);
1512 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1513 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, .. } } => {
1514 assert!(update_add_htlcs.is_empty());
1515 assert!(update_fail_htlcs.is_empty());
1516 assert_eq!(update_fulfill_htlcs.len(), 1);
1517 assert!(update_fail_malformed_htlcs.is_empty());
1518 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1520 _ => panic!("Unexpected event"),
1525 fn do_channel_reserve_test(test_recv: bool) {
1527 let chanmon_cfgs = create_chanmon_cfgs(3);
1528 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1529 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1530 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1531 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::supported(), InitFeatures::supported());
1532 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::supported(), InitFeatures::supported());
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 route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1543 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1544 (route, payment_hash, payment_preimage)
1548 macro_rules! expect_forward {
1550 let mut events = $node.node.get_and_clear_pending_msg_events();
1551 assert_eq!(events.len(), 1);
1552 check_added_monitors!($node, 1);
1553 let payment_event = SendEvent::from_event(events.remove(0));
1558 let feemsat = 239; // somehow we know?
1559 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1561 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1563 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1565 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1566 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1567 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
1569 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
1570 _ => panic!("Unknown error variants"),
1572 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1573 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);
1576 let mut htlc_id = 0;
1577 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1578 // nodes[0]'s wealth
1580 let amt_msat = recv_value_0 + total_fee_msat;
1581 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1584 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1587 let (stat01_, stat11_, stat12_, stat22_) = (
1588 get_channel_value_stat!(nodes[0], chan_1.2),
1589 get_channel_value_stat!(nodes[1], chan_1.2),
1590 get_channel_value_stat!(nodes[1], chan_2.2),
1591 get_channel_value_stat!(nodes[2], chan_2.2),
1594 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1595 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1596 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1597 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1598 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1602 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1603 // attempt to get channel_reserve violation
1604 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1605 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
1607 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1608 _ => panic!("Unknown error variants"),
1610 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1611 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 1);
1614 // adding pending output
1615 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1616 let amt_msat_1 = recv_value_1 + total_fee_msat;
1618 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1619 let payment_event_1 = {
1620 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
1621 check_added_monitors!(nodes[0], 1);
1623 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1624 assert_eq!(events.len(), 1);
1625 SendEvent::from_event(events.remove(0))
1627 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1629 // channel reserve test with htlc pending output > 0
1630 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1632 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1633 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1634 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1635 _ => panic!("Unknown error variants"),
1637 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1638 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 2);
1642 // test channel_reserve test on nodes[1] side
1643 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1645 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1646 let secp_ctx = Secp256k1::new();
1647 let session_priv = SecretKey::from_slice(&{
1648 let mut session_key = [0; 32];
1649 let mut rng = thread_rng();
1650 rng.fill_bytes(&mut session_key);
1652 }).expect("RNG is bad!");
1654 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1655 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1656 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
1657 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1658 let msg = msgs::UpdateAddHTLC {
1659 channel_id: chan_1.2,
1661 amount_msat: htlc_msat,
1662 payment_hash: our_payment_hash,
1663 cltv_expiry: htlc_cltv,
1664 onion_routing_packet: onion_packet,
1668 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1669 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1670 assert_eq!(nodes[1].node.list_channels().len(), 1);
1671 assert_eq!(nodes[1].node.list_channels().len(), 1);
1672 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1673 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
1674 check_added_monitors!(nodes[1], 1);
1679 // split the rest to test holding cell
1680 let recv_value_21 = recv_value_2/2;
1681 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1683 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1684 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);
1687 // now see if they go through on both sides
1688 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1689 // but this will stuck in the holding cell
1690 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
1691 check_added_monitors!(nodes[0], 0);
1692 let events = nodes[0].node.get_and_clear_pending_events();
1693 assert_eq!(events.len(), 0);
1695 // test with outbound holding cell amount > 0
1697 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1698 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1699 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1700 _ => panic!("Unknown error variants"),
1702 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1703 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 3);
1706 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1707 // this will also stuck in the holding cell
1708 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
1709 check_added_monitors!(nodes[0], 0);
1710 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1711 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1713 // flush the pending htlc
1714 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1715 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1716 check_added_monitors!(nodes[1], 1);
1718 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1719 check_added_monitors!(nodes[0], 1);
1720 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1722 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1723 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1724 // No commitment_signed so get_event_msg's assert(len == 1) passes
1725 check_added_monitors!(nodes[0], 1);
1727 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1728 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1729 check_added_monitors!(nodes[1], 1);
1731 expect_pending_htlcs_forwardable!(nodes[1]);
1733 let ref payment_event_11 = expect_forward!(nodes[1]);
1734 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1735 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1737 expect_pending_htlcs_forwardable!(nodes[2]);
1738 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1740 // flush the htlcs in the holding cell
1741 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1742 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1743 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1744 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1745 expect_pending_htlcs_forwardable!(nodes[1]);
1747 let ref payment_event_3 = expect_forward!(nodes[1]);
1748 assert_eq!(payment_event_3.msgs.len(), 2);
1749 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1750 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1752 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1753 expect_pending_htlcs_forwardable!(nodes[2]);
1755 let events = nodes[2].node.get_and_clear_pending_events();
1756 assert_eq!(events.len(), 2);
1758 Event::PaymentReceived { ref payment_hash, amt } => {
1759 assert_eq!(our_payment_hash_21, *payment_hash);
1760 assert_eq!(recv_value_21, amt);
1762 _ => panic!("Unexpected event"),
1765 Event::PaymentReceived { ref payment_hash, amt } => {
1766 assert_eq!(our_payment_hash_22, *payment_hash);
1767 assert_eq!(recv_value_22, amt);
1769 _ => panic!("Unexpected event"),
1772 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1773 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1774 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1776 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);
1777 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1778 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1779 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1781 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1782 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1786 fn channel_reserve_test() {
1787 do_channel_reserve_test(false);
1788 do_channel_reserve_test(true);
1792 fn channel_reserve_in_flight_removes() {
1793 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1794 // can send to its counterparty, but due to update ordering, the other side may not yet have
1795 // considered those HTLCs fully removed.
1796 // This tests that we don't count HTLCs which will not be included in the next remote
1797 // commitment transaction towards the reserve value (as it implies no commitment transaction
1798 // will be generated which violates the remote reserve value).
1799 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1801 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1802 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1803 // you only consider the value of the first HTLC, it may not),
1804 // * start routing a third HTLC from A to B,
1805 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1806 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1807 // * deliver the first fulfill from B
1808 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1810 // * deliver A's response CS and RAA.
1811 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1812 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1813 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1814 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1815 let chanmon_cfgs = create_chanmon_cfgs(2);
1816 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1817 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1818 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1819 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1821 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1822 // Route the first two HTLCs.
1823 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1824 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1826 // Start routing the third HTLC (this is just used to get everyone in the right state).
1827 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1829 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1830 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
1831 check_added_monitors!(nodes[0], 1);
1832 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1833 assert_eq!(events.len(), 1);
1834 SendEvent::from_event(events.remove(0))
1837 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1838 // initial fulfill/CS.
1839 assert!(nodes[1].node.claim_funds(payment_preimage_1, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1840 check_added_monitors!(nodes[1], 1);
1841 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1843 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1844 // remove the second HTLC when we send the HTLC back from B to A.
1845 assert!(nodes[1].node.claim_funds(payment_preimage_2, 20000));
1846 check_added_monitors!(nodes[1], 1);
1847 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1849 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1850 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1851 check_added_monitors!(nodes[0], 1);
1852 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1853 expect_payment_sent!(nodes[0], payment_preimage_1);
1855 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1856 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1857 check_added_monitors!(nodes[1], 1);
1858 // B is already AwaitingRAA, so cant generate a CS here
1859 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1861 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1862 check_added_monitors!(nodes[1], 1);
1863 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1865 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1866 check_added_monitors!(nodes[0], 1);
1867 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1869 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1870 check_added_monitors!(nodes[1], 1);
1871 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1873 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1874 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1875 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1876 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1877 // on-chain as necessary).
1878 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1879 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1880 check_added_monitors!(nodes[0], 1);
1881 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1882 expect_payment_sent!(nodes[0], payment_preimage_2);
1884 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1885 check_added_monitors!(nodes[1], 1);
1886 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1888 expect_pending_htlcs_forwardable!(nodes[1]);
1889 expect_payment_received!(nodes[1], payment_hash_3, 100000);
1891 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1892 // resolve the second HTLC from A's point of view.
1893 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1894 check_added_monitors!(nodes[0], 1);
1895 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1897 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1898 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1899 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1901 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1902 nodes[1].node.send_payment(route, payment_hash_4).unwrap();
1903 check_added_monitors!(nodes[1], 1);
1904 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1905 assert_eq!(events.len(), 1);
1906 SendEvent::from_event(events.remove(0))
1909 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1910 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1911 check_added_monitors!(nodes[0], 1);
1912 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1914 // Now just resolve all the outstanding messages/HTLCs for completeness...
1916 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1917 check_added_monitors!(nodes[1], 1);
1918 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1920 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1921 check_added_monitors!(nodes[1], 1);
1923 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1924 check_added_monitors!(nodes[0], 1);
1925 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1927 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1928 check_added_monitors!(nodes[1], 1);
1929 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1931 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1932 check_added_monitors!(nodes[0], 1);
1934 expect_pending_htlcs_forwardable!(nodes[0]);
1935 expect_payment_received!(nodes[0], payment_hash_4, 10000);
1937 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1938 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1942 fn channel_monitor_network_test() {
1943 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1944 // tests that ChannelMonitor is able to recover from various states.
1945 let chanmon_cfgs = create_chanmon_cfgs(5);
1946 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1947 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1948 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1950 // Create some initial channels
1951 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1952 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1953 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1954 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
1956 // Rebalance the network a bit by relaying one payment through all the channels...
1957 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1958 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1959 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1960 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1962 // Simple case with no pending HTLCs:
1963 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1964 check_added_monitors!(nodes[1], 1);
1966 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1967 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1968 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1969 check_added_monitors!(nodes[0], 1);
1970 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1972 get_announce_close_broadcast_events(&nodes, 0, 1);
1973 assert_eq!(nodes[0].node.list_channels().len(), 0);
1974 assert_eq!(nodes[1].node.list_channels().len(), 1);
1976 // One pending HTLC is discarded by the force-close:
1977 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1979 // Simple case of one pending HTLC to HTLC-Timeout
1980 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1981 check_added_monitors!(nodes[1], 1);
1983 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1984 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1985 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1986 check_added_monitors!(nodes[2], 1);
1987 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1989 get_announce_close_broadcast_events(&nodes, 1, 2);
1990 assert_eq!(nodes[1].node.list_channels().len(), 0);
1991 assert_eq!(nodes[2].node.list_channels().len(), 1);
1993 macro_rules! claim_funds {
1994 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1996 assert!($node.node.claim_funds($preimage, $amount));
1997 check_added_monitors!($node, 1);
1999 let events = $node.node.get_and_clear_pending_msg_events();
2000 assert_eq!(events.len(), 1);
2002 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2003 assert!(update_add_htlcs.is_empty());
2004 assert!(update_fail_htlcs.is_empty());
2005 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2007 _ => panic!("Unexpected event"),
2013 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2014 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2015 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2016 check_added_monitors!(nodes[2], 1);
2017 let node2_commitment_txid;
2019 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2020 node2_commitment_txid = node_txn[0].txid();
2022 // Claim the payment on nodes[3], giving it knowledge of the preimage
2023 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2025 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2026 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2027 check_added_monitors!(nodes[3], 1);
2029 check_preimage_claim(&nodes[3], &node_txn);
2031 get_announce_close_broadcast_events(&nodes, 2, 3);
2032 assert_eq!(nodes[2].node.list_channels().len(), 0);
2033 assert_eq!(nodes[3].node.list_channels().len(), 1);
2035 { // Cheat and reset nodes[4]'s height to 1
2036 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2037 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2040 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2041 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2042 // One pending HTLC to time out:
2043 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2044 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2048 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2049 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2050 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2051 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2052 nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2054 check_added_monitors!(nodes[3], 1);
2056 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2058 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2059 node_txn.retain(|tx| {
2060 if tx.input[0].previous_output.txid == node2_commitment_txid {
2066 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2068 // Claim the payment on nodes[4], giving it knowledge of the preimage
2069 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2071 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2073 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2074 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2075 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2076 nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2079 check_added_monitors!(nodes[4], 1);
2080 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2082 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2083 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2085 check_preimage_claim(&nodes[4], &node_txn);
2087 get_announce_close_broadcast_events(&nodes, 3, 4);
2088 assert_eq!(nodes[3].node.list_channels().len(), 0);
2089 assert_eq!(nodes[4].node.list_channels().len(), 0);
2093 fn test_justice_tx() {
2094 // Test justice txn built on revoked HTLC-Success tx, against both sides
2095 let mut alice_config = UserConfig::default();
2096 alice_config.channel_options.announced_channel = true;
2097 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2098 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2099 let mut bob_config = UserConfig::default();
2100 bob_config.channel_options.announced_channel = true;
2101 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2102 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2103 let user_cfgs = [Some(alice_config), Some(bob_config)];
2104 let chanmon_cfgs = create_chanmon_cfgs(2);
2105 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2106 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2107 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2108 // Create some new channels:
2109 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2111 // A pending HTLC which will be revoked:
2112 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2113 // Get the will-be-revoked local txn from nodes[0]
2114 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter_mut().next().unwrap().1.channel_monitor().get_latest_local_commitment_txn();
2115 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2116 assert_eq!(revoked_local_txn[0].input.len(), 1);
2117 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2118 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2119 assert_eq!(revoked_local_txn[1].input.len(), 1);
2120 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2121 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2122 // Revoke the old state
2123 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2126 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2127 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2129 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2130 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2131 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2133 check_spends!(node_txn[0], revoked_local_txn[0]);
2134 node_txn.swap_remove(0);
2135 node_txn.truncate(1);
2137 check_added_monitors!(nodes[1], 1);
2138 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2140 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2141 // Verify broadcast of revoked HTLC-timeout
2142 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2143 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2144 check_added_monitors!(nodes[0], 1);
2145 // Broadcast revoked HTLC-timeout on node 1
2146 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2147 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2149 get_announce_close_broadcast_events(&nodes, 0, 1);
2151 assert_eq!(nodes[0].node.list_channels().len(), 0);
2152 assert_eq!(nodes[1].node.list_channels().len(), 0);
2154 // We test justice_tx build by A on B's revoked HTLC-Success tx
2155 // Create some new channels:
2156 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2158 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2162 // A pending HTLC which will be revoked:
2163 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2164 // Get the will-be-revoked local txn from B
2165 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter_mut().next().unwrap().1.channel_monitor().get_latest_local_commitment_txn();
2166 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2167 assert_eq!(revoked_local_txn[0].input.len(), 1);
2168 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2169 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2170 // Revoke the old state
2171 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2173 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2174 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2176 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2177 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2178 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2180 check_spends!(node_txn[0], revoked_local_txn[0]);
2181 node_txn.swap_remove(0);
2183 check_added_monitors!(nodes[0], 1);
2184 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2186 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2187 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2188 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2189 check_added_monitors!(nodes[1], 1);
2190 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2191 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2193 get_announce_close_broadcast_events(&nodes, 0, 1);
2194 assert_eq!(nodes[0].node.list_channels().len(), 0);
2195 assert_eq!(nodes[1].node.list_channels().len(), 0);
2199 fn revoked_output_claim() {
2200 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2201 // transaction is broadcast by its counterparty
2202 let chanmon_cfgs = create_chanmon_cfgs(2);
2203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2205 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2206 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2207 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2208 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2209 assert_eq!(revoked_local_txn.len(), 1);
2210 // Only output is the full channel value back to nodes[0]:
2211 assert_eq!(revoked_local_txn[0].output.len(), 1);
2212 // Send a payment through, updating everyone's latest commitment txn
2213 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2215 // Inform nodes[1] that nodes[0] broadcast a stale tx
2216 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2217 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2218 check_added_monitors!(nodes[1], 1);
2219 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2220 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2222 check_spends!(node_txn[0], revoked_local_txn[0]);
2223 check_spends!(node_txn[1], chan_1.3);
2225 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2226 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2227 get_announce_close_broadcast_events(&nodes, 0, 1);
2228 check_added_monitors!(nodes[0], 1)
2232 fn claim_htlc_outputs_shared_tx() {
2233 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2234 let chanmon_cfgs = create_chanmon_cfgs(2);
2235 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2236 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2237 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2239 // Create some new channel:
2240 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2242 // Rebalance the network to generate htlc in the two directions
2243 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2244 // 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
2245 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2246 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2248 // Get the will-be-revoked local txn from node[0]
2249 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2250 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2251 assert_eq!(revoked_local_txn[0].input.len(), 1);
2252 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2253 assert_eq!(revoked_local_txn[1].input.len(), 1);
2254 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2255 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2256 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2258 //Revoke the old state
2259 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2262 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2263 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2264 check_added_monitors!(nodes[0], 1);
2265 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2266 check_added_monitors!(nodes[1], 1);
2267 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2269 let events = nodes[1].node.get_and_clear_pending_events();
2270 assert_eq!(events.len(), 1);
2272 Event::PaymentFailed { payment_hash, .. } => {
2273 assert_eq!(payment_hash, payment_hash_2);
2275 _ => panic!("Unexpected event"),
2278 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2279 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2281 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2282 check_spends!(node_txn[0], revoked_local_txn[0]);
2284 let mut witness_lens = BTreeSet::new();
2285 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2286 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2287 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2288 assert_eq!(witness_lens.len(), 3);
2289 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2290 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2291 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2293 // Next nodes[1] broadcasts its current local tx state:
2294 assert_eq!(node_txn[1].input.len(), 1);
2295 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2297 assert_eq!(node_txn[2].input.len(), 1);
2298 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2299 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2300 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2301 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2302 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2304 get_announce_close_broadcast_events(&nodes, 0, 1);
2305 assert_eq!(nodes[0].node.list_channels().len(), 0);
2306 assert_eq!(nodes[1].node.list_channels().len(), 0);
2310 fn claim_htlc_outputs_single_tx() {
2311 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2312 let chanmon_cfgs = create_chanmon_cfgs(2);
2313 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2314 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2315 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2317 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2319 // Rebalance the network to generate htlc in the two directions
2320 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2321 // 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
2322 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2323 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2324 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2326 // Get the will-be-revoked local txn from node[0]
2327 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2329 //Revoke the old state
2330 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2333 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2334 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2335 check_added_monitors!(nodes[0], 1);
2336 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2337 check_added_monitors!(nodes[1], 1);
2338 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2340 let events = nodes[1].node.get_and_clear_pending_events();
2341 assert_eq!(events.len(), 1);
2343 Event::PaymentFailed { payment_hash, .. } => {
2344 assert_eq!(payment_hash, payment_hash_2);
2346 _ => panic!("Unexpected event"),
2349 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2350 assert_eq!(node_txn.len(), 21);
2351 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2352 // ChannelManager: local commmitment + local HTLC-timeout (2)
2353 // ChannelMonitor: bumped justice tx (4), after one increase, bumps on HTLC aren't generated not being substantial anymore
2354 // ChannelMonito r: local commitment + local HTLC-timeout (14)
2356 assert_eq!(node_txn[0], node_txn[5]);
2357 assert_eq!(node_txn[0], node_txn[7]);
2358 assert_eq!(node_txn[0], node_txn[9]);
2359 assert_eq!(node_txn[0], node_txn[13]);
2360 assert_eq!(node_txn[0], node_txn[15]);
2361 assert_eq!(node_txn[0], node_txn[17]);
2362 assert_eq!(node_txn[0], node_txn[19]);
2364 assert_eq!(node_txn[1], node_txn[6]);
2365 assert_eq!(node_txn[1], node_txn[8]);
2366 assert_eq!(node_txn[1], node_txn[10]);
2367 assert_eq!(node_txn[1], node_txn[14]);
2368 assert_eq!(node_txn[1], node_txn[16]);
2369 assert_eq!(node_txn[1], node_txn[18]);
2370 assert_eq!(node_txn[1], node_txn[20]);
2373 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration and present 8 times (rebroadcast at every block from 200 to 206)
2374 assert_eq!(node_txn[0].input.len(), 1);
2375 check_spends!(node_txn[0], chan_1.3);
2376 assert_eq!(node_txn[1].input.len(), 1);
2377 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2378 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2379 check_spends!(node_txn[1], node_txn[0]);
2381 // Justice transactions are indices 2-3-4
2382 assert_eq!(node_txn[2].input.len(), 1);
2383 assert_eq!(node_txn[3].input.len(), 1);
2384 assert_eq!(node_txn[4].input.len(), 1);
2385 check_spends!(node_txn[2], revoked_local_txn[0]);
2386 check_spends!(node_txn[3], revoked_local_txn[0]);
2387 check_spends!(node_txn[4], revoked_local_txn[0]);
2389 let mut witness_lens = BTreeSet::new();
2390 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2391 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2392 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2393 assert_eq!(witness_lens.len(), 3);
2394 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2395 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2396 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2398 get_announce_close_broadcast_events(&nodes, 0, 1);
2399 assert_eq!(nodes[0].node.list_channels().len(), 0);
2400 assert_eq!(nodes[1].node.list_channels().len(), 0);
2404 fn test_htlc_on_chain_success() {
2405 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2406 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2407 // broadcasting the right event to other nodes in payment path.
2408 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2409 // A --------------------> B ----------------------> C (preimage)
2410 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2411 // commitment transaction was broadcast.
2412 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2414 // B should be able to claim via preimage if A then broadcasts its local tx.
2415 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2416 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2417 // PaymentSent event).
2419 let chanmon_cfgs = create_chanmon_cfgs(3);
2420 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2421 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2422 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2424 // Create some initial channels
2425 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2426 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2428 // Rebalance the network a bit by relaying one payment through all the channels...
2429 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2430 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2432 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2433 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2434 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2436 // Broadcast legit commitment tx from C on B's chain
2437 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2438 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2439 assert_eq!(commitment_tx.len(), 1);
2440 check_spends!(commitment_tx[0], chan_2.3);
2441 nodes[2].node.claim_funds(our_payment_preimage, 3_000_000);
2442 nodes[2].node.claim_funds(our_payment_preimage_2, 3_000_000);
2443 check_added_monitors!(nodes[2], 2);
2444 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2445 assert!(updates.update_add_htlcs.is_empty());
2446 assert!(updates.update_fail_htlcs.is_empty());
2447 assert!(updates.update_fail_malformed_htlcs.is_empty());
2448 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2450 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2451 check_closed_broadcast!(nodes[2], false);
2452 check_added_monitors!(nodes[2], 1);
2453 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
2454 assert_eq!(node_txn.len(), 7);
2455 assert_eq!(node_txn[0], node_txn[3]);
2456 assert_eq!(node_txn[1], node_txn[4]);
2457 assert_eq!(node_txn[0], node_txn[5]);
2458 assert_eq!(node_txn[1], node_txn[6]);
2459 assert_eq!(node_txn[2], commitment_tx[0]);
2460 check_spends!(node_txn[0], commitment_tx[0]);
2461 check_spends!(node_txn[1], commitment_tx[0]);
2462 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2463 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2464 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2465 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2466 assert_eq!(node_txn[0].lock_time, 0);
2467 assert_eq!(node_txn[1].lock_time, 0);
2469 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2470 nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2472 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2473 assert_eq!(added_monitors.len(), 1);
2474 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2475 added_monitors.clear();
2477 let events = nodes[1].node.get_and_clear_pending_msg_events();
2479 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2480 assert_eq!(added_monitors.len(), 2);
2481 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2482 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2483 added_monitors.clear();
2485 assert_eq!(events.len(), 2);
2487 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2488 _ => panic!("Unexpected event"),
2491 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, .. } } => {
2492 assert!(update_add_htlcs.is_empty());
2493 assert!(update_fail_htlcs.is_empty());
2494 assert_eq!(update_fulfill_htlcs.len(), 1);
2495 assert!(update_fail_malformed_htlcs.is_empty());
2496 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2498 _ => panic!("Unexpected event"),
2500 macro_rules! check_tx_local_broadcast {
2501 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2502 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2503 assert_eq!(node_txn.len(), if $htlc_offered { 7 } else { 5 });
2504 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2505 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout * 2 (block-rescan)
2506 check_spends!(node_txn[0], $commitment_tx);
2507 check_spends!(node_txn[1], $commitment_tx);
2509 assert_eq!(node_txn[0], node_txn[5]);
2510 assert_eq!(node_txn[1], node_txn[6]);
2512 assert_ne!(node_txn[0].lock_time, 0);
2513 assert_ne!(node_txn[1].lock_time, 0);
2515 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2516 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2517 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2518 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2520 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2521 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2522 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2523 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2525 check_spends!(node_txn[2], $chan_tx);
2526 check_spends!(node_txn[3], node_txn[2]);
2527 check_spends!(node_txn[4], node_txn[2]);
2528 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2529 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2530 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2531 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2532 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2533 assert_ne!(node_txn[3].lock_time, 0);
2534 assert_ne!(node_txn[4].lock_time, 0);
2538 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2539 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2540 // timeout-claim of the output that nodes[2] just claimed via success.
2541 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2543 // Broadcast legit commitment tx from A on B's chain
2544 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2545 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2546 check_spends!(commitment_tx[0], chan_1.3);
2547 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2548 check_closed_broadcast!(nodes[1], false);
2549 check_added_monitors!(nodes[1], 1);
2550 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2551 assert_eq!(node_txn.len(), 4);
2552 check_spends!(node_txn[0], commitment_tx[0]);
2553 assert_eq!(node_txn[0].input.len(), 2);
2554 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2555 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2556 assert_eq!(node_txn[0].lock_time, 0);
2557 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2558 check_spends!(node_txn[1], chan_1.3);
2559 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2560 check_spends!(node_txn[2], node_txn[1]);
2561 check_spends!(node_txn[3], node_txn[1]);
2562 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2563 // we already checked the same situation with A.
2565 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2566 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2567 check_closed_broadcast!(nodes[0], false);
2568 check_added_monitors!(nodes[0], 1);
2569 let events = nodes[0].node.get_and_clear_pending_events();
2570 assert_eq!(events.len(), 2);
2571 let mut first_claimed = false;
2572 for event in events {
2574 Event::PaymentSent { payment_preimage } => {
2575 if payment_preimage == our_payment_preimage {
2576 assert!(!first_claimed);
2577 first_claimed = true;
2579 assert_eq!(payment_preimage, our_payment_preimage_2);
2582 _ => panic!("Unexpected event"),
2585 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2589 fn test_htlc_on_chain_timeout() {
2590 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2591 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2592 // broadcasting the right event to other nodes in payment path.
2593 // A ------------------> B ----------------------> C (timeout)
2594 // B's commitment tx C's commitment tx
2596 // B's HTLC timeout tx B's timeout tx
2598 let chanmon_cfgs = create_chanmon_cfgs(3);
2599 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2600 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2601 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2603 // Create some intial channels
2604 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2605 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2607 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2608 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2609 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2611 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2612 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2614 // Broadcast legit commitment tx from C on B's chain
2615 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2616 check_spends!(commitment_tx[0], chan_2.3);
2617 nodes[2].node.fail_htlc_backwards(&payment_hash);
2618 check_added_monitors!(nodes[2], 0);
2619 expect_pending_htlcs_forwardable!(nodes[2]);
2620 check_added_monitors!(nodes[2], 1);
2622 let events = nodes[2].node.get_and_clear_pending_msg_events();
2623 assert_eq!(events.len(), 1);
2625 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, .. } } => {
2626 assert!(update_add_htlcs.is_empty());
2627 assert!(!update_fail_htlcs.is_empty());
2628 assert!(update_fulfill_htlcs.is_empty());
2629 assert!(update_fail_malformed_htlcs.is_empty());
2630 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2632 _ => panic!("Unexpected event"),
2634 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2635 check_closed_broadcast!(nodes[2], false);
2636 check_added_monitors!(nodes[2], 1);
2637 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2638 assert_eq!(node_txn.len(), 1);
2639 check_spends!(node_txn[0], chan_2.3);
2640 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2642 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2643 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2644 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2647 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2648 assert_eq!(node_txn.len(), 7); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : (local commitment tx + HTLC-timeout) * 2 (block-rescan), timeout tx
2649 assert_eq!(node_txn[0], node_txn[3]);
2650 assert_eq!(node_txn[0], node_txn[5]);
2651 assert_eq!(node_txn[1], node_txn[4]);
2652 assert_eq!(node_txn[1], node_txn[6]);
2654 check_spends!(node_txn[2], commitment_tx[0]);
2655 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2657 check_spends!(node_txn[0], chan_2.3);
2658 check_spends!(node_txn[1], node_txn[0]);
2659 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2660 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2662 timeout_tx = node_txn[2].clone();
2666 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2667 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2668 check_added_monitors!(nodes[1], 1);
2669 check_closed_broadcast!(nodes[1], false);
2671 expect_pending_htlcs_forwardable!(nodes[1]);
2672 check_added_monitors!(nodes[1], 1);
2673 let events = nodes[1].node.get_and_clear_pending_msg_events();
2674 assert_eq!(events.len(), 1);
2676 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, .. } } => {
2677 assert!(update_add_htlcs.is_empty());
2678 assert!(!update_fail_htlcs.is_empty());
2679 assert!(update_fulfill_htlcs.is_empty());
2680 assert!(update_fail_malformed_htlcs.is_empty());
2681 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2683 _ => panic!("Unexpected event"),
2685 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
2686 assert_eq!(node_txn.len(), 0);
2688 // Broadcast legit commitment tx from B on A's chain
2689 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2690 check_spends!(commitment_tx[0], chan_1.3);
2692 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2693 check_closed_broadcast!(nodes[0], false);
2694 check_added_monitors!(nodes[0], 1);
2695 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2696 assert_eq!(node_txn.len(), 3);
2697 check_spends!(node_txn[0], commitment_tx[0]);
2698 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2699 check_spends!(node_txn[1], chan_1.3);
2700 check_spends!(node_txn[2], node_txn[1]);
2701 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2702 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2706 fn test_simple_commitment_revoked_fail_backward() {
2707 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2708 // and fail backward accordingly.
2710 let chanmon_cfgs = create_chanmon_cfgs(3);
2711 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2712 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2713 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2715 // Create some initial channels
2716 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2717 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2719 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2720 // Get the will-be-revoked local txn from nodes[2]
2721 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2722 // Revoke the old state
2723 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2725 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2727 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2728 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2729 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2730 check_added_monitors!(nodes[1], 1);
2731 check_closed_broadcast!(nodes[1], false);
2733 expect_pending_htlcs_forwardable!(nodes[1]);
2734 check_added_monitors!(nodes[1], 1);
2735 let events = nodes[1].node.get_and_clear_pending_msg_events();
2736 assert_eq!(events.len(), 1);
2738 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, .. } } => {
2739 assert!(update_add_htlcs.is_empty());
2740 assert_eq!(update_fail_htlcs.len(), 1);
2741 assert!(update_fulfill_htlcs.is_empty());
2742 assert!(update_fail_malformed_htlcs.is_empty());
2743 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2745 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2746 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2748 let events = nodes[0].node.get_and_clear_pending_msg_events();
2749 assert_eq!(events.len(), 1);
2751 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2752 _ => panic!("Unexpected event"),
2754 let events = nodes[0].node.get_and_clear_pending_events();
2755 assert_eq!(events.len(), 1);
2757 Event::PaymentFailed { .. } => {},
2758 _ => panic!("Unexpected event"),
2761 _ => panic!("Unexpected event"),
2765 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2766 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2767 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2768 // commitment transaction anymore.
2769 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2770 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2771 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2772 // technically disallowed and we should probably handle it reasonably.
2773 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2774 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2776 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2777 // commitment_signed (implying it will be in the latest remote commitment transaction).
2778 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2779 // and once they revoke the previous commitment transaction (allowing us to send a new
2780 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2781 let chanmon_cfgs = create_chanmon_cfgs(3);
2782 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2783 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2784 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2786 // Create some initial channels
2787 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2788 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2790 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2791 // Get the will-be-revoked local txn from nodes[2]
2792 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
2793 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2794 // Revoke the old state
2795 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2797 let value = if use_dust {
2798 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2799 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2800 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2803 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2804 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2805 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2807 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2808 expect_pending_htlcs_forwardable!(nodes[2]);
2809 check_added_monitors!(nodes[2], 1);
2810 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2811 assert!(updates.update_add_htlcs.is_empty());
2812 assert!(updates.update_fulfill_htlcs.is_empty());
2813 assert!(updates.update_fail_malformed_htlcs.is_empty());
2814 assert_eq!(updates.update_fail_htlcs.len(), 1);
2815 assert!(updates.update_fee.is_none());
2816 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2817 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2818 // Drop the last RAA from 3 -> 2
2820 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2821 expect_pending_htlcs_forwardable!(nodes[2]);
2822 check_added_monitors!(nodes[2], 1);
2823 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2824 assert!(updates.update_add_htlcs.is_empty());
2825 assert!(updates.update_fulfill_htlcs.is_empty());
2826 assert!(updates.update_fail_malformed_htlcs.is_empty());
2827 assert_eq!(updates.update_fail_htlcs.len(), 1);
2828 assert!(updates.update_fee.is_none());
2829 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2830 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2831 check_added_monitors!(nodes[1], 1);
2832 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2833 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2834 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2835 check_added_monitors!(nodes[2], 1);
2837 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2838 expect_pending_htlcs_forwardable!(nodes[2]);
2839 check_added_monitors!(nodes[2], 1);
2840 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2841 assert!(updates.update_add_htlcs.is_empty());
2842 assert!(updates.update_fulfill_htlcs.is_empty());
2843 assert!(updates.update_fail_malformed_htlcs.is_empty());
2844 assert_eq!(updates.update_fail_htlcs.len(), 1);
2845 assert!(updates.update_fee.is_none());
2846 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2847 // At this point first_payment_hash has dropped out of the latest two commitment
2848 // transactions that nodes[1] is tracking...
2849 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2850 check_added_monitors!(nodes[1], 1);
2851 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2852 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2853 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2854 check_added_monitors!(nodes[2], 1);
2856 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2857 // on nodes[2]'s RAA.
2858 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2859 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2860 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
2861 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2862 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2863 check_added_monitors!(nodes[1], 0);
2866 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2867 // One monitor for the new revocation preimage, no second on as we won't generate a new
2868 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2869 check_added_monitors!(nodes[1], 1);
2870 let events = nodes[1].node.get_and_clear_pending_events();
2871 assert_eq!(events.len(), 1);
2873 Event::PendingHTLCsForwardable { .. } => { },
2874 _ => panic!("Unexpected event"),
2876 // Deliberately don't process the pending fail-back so they all fail back at once after
2877 // block connection just like the !deliver_bs_raa case
2880 let mut failed_htlcs = HashSet::new();
2881 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2883 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2884 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2885 check_added_monitors!(nodes[1], 1);
2886 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2888 let events = nodes[1].node.get_and_clear_pending_events();
2889 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2891 Event::PaymentFailed { ref payment_hash, .. } => {
2892 assert_eq!(*payment_hash, fourth_payment_hash);
2894 _ => panic!("Unexpected event"),
2896 if !deliver_bs_raa {
2898 Event::PendingHTLCsForwardable { .. } => { },
2899 _ => panic!("Unexpected event"),
2902 nodes[1].node.process_pending_htlc_forwards();
2903 check_added_monitors!(nodes[1], 1);
2905 let events = nodes[1].node.get_and_clear_pending_msg_events();
2906 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2907 match events[if deliver_bs_raa { 1 } else { 0 }] {
2908 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2909 _ => panic!("Unexpected event"),
2913 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, .. } } => {
2914 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2915 assert_eq!(update_add_htlcs.len(), 1);
2916 assert!(update_fulfill_htlcs.is_empty());
2917 assert!(update_fail_htlcs.is_empty());
2918 assert!(update_fail_malformed_htlcs.is_empty());
2920 _ => panic!("Unexpected event"),
2923 match events[if deliver_bs_raa { 2 } else { 1 }] {
2924 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, .. } } => {
2925 assert!(update_add_htlcs.is_empty());
2926 assert_eq!(update_fail_htlcs.len(), 3);
2927 assert!(update_fulfill_htlcs.is_empty());
2928 assert!(update_fail_malformed_htlcs.is_empty());
2929 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2931 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2932 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2933 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2935 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2937 let events = nodes[0].node.get_and_clear_pending_msg_events();
2938 // If we delivered B's RAA we got an unknown preimage error, not something
2939 // that we should update our routing table for.
2940 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2941 for event in events {
2943 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2944 _ => panic!("Unexpected event"),
2947 let events = nodes[0].node.get_and_clear_pending_events();
2948 assert_eq!(events.len(), 3);
2950 Event::PaymentFailed { ref payment_hash, .. } => {
2951 assert!(failed_htlcs.insert(payment_hash.0));
2953 _ => panic!("Unexpected event"),
2956 Event::PaymentFailed { ref payment_hash, .. } => {
2957 assert!(failed_htlcs.insert(payment_hash.0));
2959 _ => panic!("Unexpected event"),
2962 Event::PaymentFailed { ref payment_hash, .. } => {
2963 assert!(failed_htlcs.insert(payment_hash.0));
2965 _ => panic!("Unexpected event"),
2968 _ => panic!("Unexpected event"),
2971 assert!(failed_htlcs.contains(&first_payment_hash.0));
2972 assert!(failed_htlcs.contains(&second_payment_hash.0));
2973 assert!(failed_htlcs.contains(&third_payment_hash.0));
2977 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2978 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2979 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2980 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2981 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2985 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2986 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2987 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2988 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2989 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2993 fn test_htlc_ignore_latest_remote_commitment() {
2994 // Test that HTLC transactions spending the latest remote commitment transaction are simply
2995 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2996 let chanmon_cfgs = create_chanmon_cfgs(2);
2997 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2998 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2999 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3000 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3002 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3003 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3004 check_closed_broadcast!(nodes[0], false);
3005 check_added_monitors!(nodes[0], 1);
3007 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3008 assert_eq!(node_txn.len(), 2);
3010 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3011 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3012 check_closed_broadcast!(nodes[1], false);
3013 check_added_monitors!(nodes[1], 1);
3015 // Duplicate the block_connected call since this may happen due to other listeners
3016 // registering new transactions
3017 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3021 fn test_force_close_fail_back() {
3022 // Check which HTLCs are failed-backwards on channel force-closure
3023 let chanmon_cfgs = create_chanmon_cfgs(3);
3024 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3025 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3026 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3027 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3028 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
3030 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
3032 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3034 let mut payment_event = {
3035 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
3036 check_added_monitors!(nodes[0], 1);
3038 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3039 assert_eq!(events.len(), 1);
3040 SendEvent::from_event(events.remove(0))
3043 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3044 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3046 expect_pending_htlcs_forwardable!(nodes[1]);
3048 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3049 assert_eq!(events_2.len(), 1);
3050 payment_event = SendEvent::from_event(events_2.remove(0));
3051 assert_eq!(payment_event.msgs.len(), 1);
3053 check_added_monitors!(nodes[1], 1);
3054 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3055 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3056 check_added_monitors!(nodes[2], 1);
3057 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3059 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3060 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3061 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3063 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3064 check_closed_broadcast!(nodes[2], false);
3065 check_added_monitors!(nodes[2], 1);
3067 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3068 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3069 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3070 // back to nodes[1] upon timeout otherwise.
3071 assert_eq!(node_txn.len(), 1);
3075 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3076 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3078 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3079 check_closed_broadcast!(nodes[1], false);
3080 check_added_monitors!(nodes[1], 1);
3082 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3084 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3085 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
3086 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3088 nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3089 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3090 assert_eq!(node_txn.len(), 1);
3091 assert_eq!(node_txn[0].input.len(), 1);
3092 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3093 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3094 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3096 check_spends!(node_txn[0], tx);
3100 fn test_unconf_chan() {
3101 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3102 let chanmon_cfgs = create_chanmon_cfgs(2);
3103 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3104 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3105 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3106 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3108 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3109 assert_eq!(channel_state.by_id.len(), 1);
3110 assert_eq!(channel_state.short_to_id.len(), 1);
3111 mem::drop(channel_state);
3113 let mut headers = Vec::new();
3114 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3115 headers.push(header.clone());
3117 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3118 headers.push(header.clone());
3120 let mut height = 99;
3121 while !headers.is_empty() {
3122 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3125 check_closed_broadcast!(nodes[0], false);
3126 check_added_monitors!(nodes[0], 1);
3127 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3128 assert_eq!(channel_state.by_id.len(), 0);
3129 assert_eq!(channel_state.short_to_id.len(), 0);
3133 fn test_simple_peer_disconnect() {
3134 // Test that we can reconnect when there are no lost messages
3135 let chanmon_cfgs = create_chanmon_cfgs(3);
3136 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3137 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3138 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3139 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3140 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
3142 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3143 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3144 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3146 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3147 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3148 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3149 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3151 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3152 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3153 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3155 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3156 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3157 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3158 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3160 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3161 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3163 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3164 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3166 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3168 let events = nodes[0].node.get_and_clear_pending_events();
3169 assert_eq!(events.len(), 2);
3171 Event::PaymentSent { payment_preimage } => {
3172 assert_eq!(payment_preimage, payment_preimage_3);
3174 _ => panic!("Unexpected event"),
3177 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3178 assert_eq!(payment_hash, payment_hash_5);
3179 assert!(rejected_by_dest);
3181 _ => panic!("Unexpected event"),
3185 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3186 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3189 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3190 // Test that we can reconnect when in-flight HTLC updates get dropped
3191 let chanmon_cfgs = create_chanmon_cfgs(2);
3192 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3193 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3194 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3195 if messages_delivered == 0 {
3196 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3197 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3199 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3202 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3203 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3205 let payment_event = {
3206 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
3207 check_added_monitors!(nodes[0], 1);
3209 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3210 assert_eq!(events.len(), 1);
3211 SendEvent::from_event(events.remove(0))
3213 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3215 if messages_delivered < 2 {
3216 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3218 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3219 if messages_delivered >= 3 {
3220 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3221 check_added_monitors!(nodes[1], 1);
3222 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3224 if messages_delivered >= 4 {
3225 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3226 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3227 check_added_monitors!(nodes[0], 1);
3229 if messages_delivered >= 5 {
3230 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3231 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3232 // No commitment_signed so get_event_msg's assert(len == 1) passes
3233 check_added_monitors!(nodes[0], 1);
3235 if messages_delivered >= 6 {
3236 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3237 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3238 check_added_monitors!(nodes[1], 1);
3245 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3246 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3247 if messages_delivered < 3 {
3248 // Even if the funding_locked messages get exchanged, as long as nothing further was
3249 // received on either side, both sides will need to resend them.
3250 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3251 } else if messages_delivered == 3 {
3252 // nodes[0] still wants its RAA + commitment_signed
3253 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3254 } else if messages_delivered == 4 {
3255 // nodes[0] still wants its commitment_signed
3256 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3257 } else if messages_delivered == 5 {
3258 // nodes[1] still wants its final RAA
3259 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3260 } else if messages_delivered == 6 {
3261 // Everything was delivered...
3262 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3265 let events_1 = nodes[1].node.get_and_clear_pending_events();
3266 assert_eq!(events_1.len(), 1);
3268 Event::PendingHTLCsForwardable { .. } => { },
3269 _ => panic!("Unexpected event"),
3272 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3273 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3274 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3276 nodes[1].node.process_pending_htlc_forwards();
3278 let events_2 = nodes[1].node.get_and_clear_pending_events();
3279 assert_eq!(events_2.len(), 1);
3281 Event::PaymentReceived { ref payment_hash, amt } => {
3282 assert_eq!(payment_hash_1, *payment_hash);
3283 assert_eq!(amt, 1000000);
3285 _ => panic!("Unexpected event"),
3288 nodes[1].node.claim_funds(payment_preimage_1, 1_000_000);
3289 check_added_monitors!(nodes[1], 1);
3291 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3292 assert_eq!(events_3.len(), 1);
3293 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3294 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3295 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3296 assert!(updates.update_add_htlcs.is_empty());
3297 assert!(updates.update_fail_htlcs.is_empty());
3298 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3299 assert!(updates.update_fail_malformed_htlcs.is_empty());
3300 assert!(updates.update_fee.is_none());
3301 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3303 _ => panic!("Unexpected event"),
3306 if messages_delivered >= 1 {
3307 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3309 let events_4 = nodes[0].node.get_and_clear_pending_events();
3310 assert_eq!(events_4.len(), 1);
3312 Event::PaymentSent { ref payment_preimage } => {
3313 assert_eq!(payment_preimage_1, *payment_preimage);
3315 _ => panic!("Unexpected event"),
3318 if messages_delivered >= 2 {
3319 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3320 check_added_monitors!(nodes[0], 1);
3321 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3323 if messages_delivered >= 3 {
3324 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3325 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3326 check_added_monitors!(nodes[1], 1);
3328 if messages_delivered >= 4 {
3329 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3330 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3331 // No commitment_signed so get_event_msg's assert(len == 1) passes
3332 check_added_monitors!(nodes[1], 1);
3334 if messages_delivered >= 5 {
3335 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3336 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3337 check_added_monitors!(nodes[0], 1);
3344 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3345 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3346 if messages_delivered < 2 {
3347 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3348 //TODO: Deduplicate PaymentSent events, then enable this if:
3349 //if messages_delivered < 1 {
3350 let events_4 = nodes[0].node.get_and_clear_pending_events();
3351 assert_eq!(events_4.len(), 1);
3353 Event::PaymentSent { ref payment_preimage } => {
3354 assert_eq!(payment_preimage_1, *payment_preimage);
3356 _ => panic!("Unexpected event"),
3359 } else if messages_delivered == 2 {
3360 // nodes[0] still wants its RAA + commitment_signed
3361 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3362 } else if messages_delivered == 3 {
3363 // nodes[0] still wants its commitment_signed
3364 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3365 } else if messages_delivered == 4 {
3366 // nodes[1] still wants its final RAA
3367 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3368 } else if messages_delivered == 5 {
3369 // Everything was delivered...
3370 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3373 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3374 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3375 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3377 // Channel should still work fine...
3378 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3379 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3383 fn test_drop_messages_peer_disconnect_a() {
3384 do_test_drop_messages_peer_disconnect(0);
3385 do_test_drop_messages_peer_disconnect(1);
3386 do_test_drop_messages_peer_disconnect(2);
3387 do_test_drop_messages_peer_disconnect(3);
3391 fn test_drop_messages_peer_disconnect_b() {
3392 do_test_drop_messages_peer_disconnect(4);
3393 do_test_drop_messages_peer_disconnect(5);
3394 do_test_drop_messages_peer_disconnect(6);
3398 fn test_funding_peer_disconnect() {
3399 // Test that we can lock in our funding tx while disconnected
3400 let chanmon_cfgs = create_chanmon_cfgs(2);
3401 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3402 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3403 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3404 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
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);
3409 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3410 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3411 assert_eq!(events_1.len(), 1);
3413 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3414 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3416 _ => panic!("Unexpected event"),
3419 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3421 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3422 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3424 confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3425 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3426 assert_eq!(events_2.len(), 2);
3427 let funding_locked = match events_2[0] {
3428 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3429 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3432 _ => panic!("Unexpected event"),
3434 let bs_announcement_sigs = match events_2[1] {
3435 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3436 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3439 _ => panic!("Unexpected event"),
3442 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3444 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3445 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3446 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3447 assert_eq!(events_3.len(), 2);
3448 let as_announcement_sigs = match events_3[0] {
3449 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3450 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3453 _ => panic!("Unexpected event"),
3455 let (as_announcement, as_update) = match events_3[1] {
3456 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3457 (msg.clone(), update_msg.clone())
3459 _ => panic!("Unexpected event"),
3462 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3463 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3464 assert_eq!(events_4.len(), 1);
3465 let (_, bs_update) = match events_4[0] {
3466 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3467 (msg.clone(), update_msg.clone())
3469 _ => panic!("Unexpected event"),
3472 nodes[0].router.handle_channel_announcement(&as_announcement).unwrap();
3473 nodes[0].router.handle_channel_update(&bs_update).unwrap();
3474 nodes[0].router.handle_channel_update(&as_update).unwrap();
3476 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3477 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3478 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3482 fn test_drop_messages_peer_disconnect_dual_htlc() {
3483 // Test that we can handle reconnecting when both sides of a channel have pending
3484 // commitment_updates when we disconnect.
3485 let chanmon_cfgs = create_chanmon_cfgs(2);
3486 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3487 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3488 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3489 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3491 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3493 // Now try to send a second payment which will fail to send
3494 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3495 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3497 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3498 check_added_monitors!(nodes[0], 1);
3500 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3501 assert_eq!(events_1.len(), 1);
3503 MessageSendEvent::UpdateHTLCs { .. } => {},
3504 _ => panic!("Unexpected event"),
3507 assert!(nodes[1].node.claim_funds(payment_preimage_1, 1_000_000));
3508 check_added_monitors!(nodes[1], 1);
3510 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3511 assert_eq!(events_2.len(), 1);
3513 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 } } => {
3514 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3515 assert!(update_add_htlcs.is_empty());
3516 assert_eq!(update_fulfill_htlcs.len(), 1);
3517 assert!(update_fail_htlcs.is_empty());
3518 assert!(update_fail_malformed_htlcs.is_empty());
3519 assert!(update_fee.is_none());
3521 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3522 let events_3 = nodes[0].node.get_and_clear_pending_events();
3523 assert_eq!(events_3.len(), 1);
3525 Event::PaymentSent { ref payment_preimage } => {
3526 assert_eq!(*payment_preimage, payment_preimage_1);
3528 _ => panic!("Unexpected event"),
3531 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3532 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3533 // No commitment_signed so get_event_msg's assert(len == 1) passes
3534 check_added_monitors!(nodes[0], 1);
3536 _ => panic!("Unexpected event"),
3539 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3540 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3542 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3543 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3544 assert_eq!(reestablish_1.len(), 1);
3545 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3546 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3547 assert_eq!(reestablish_2.len(), 1);
3549 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3550 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3551 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3552 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3554 assert!(as_resp.0.is_none());
3555 assert!(bs_resp.0.is_none());
3557 assert!(bs_resp.1.is_none());
3558 assert!(bs_resp.2.is_none());
3560 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3562 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3563 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3564 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3565 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3566 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3567 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3568 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3569 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3570 // No commitment_signed so get_event_msg's assert(len == 1) passes
3571 check_added_monitors!(nodes[1], 1);
3573 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3574 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3575 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3576 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3577 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3578 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3579 assert!(bs_second_commitment_signed.update_fee.is_none());
3580 check_added_monitors!(nodes[1], 1);
3582 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3583 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3584 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3585 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3586 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3587 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3588 assert!(as_commitment_signed.update_fee.is_none());
3589 check_added_monitors!(nodes[0], 1);
3591 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3592 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3593 // No commitment_signed so get_event_msg's assert(len == 1) passes
3594 check_added_monitors!(nodes[0], 1);
3596 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3597 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3598 // No commitment_signed so get_event_msg's assert(len == 1) passes
3599 check_added_monitors!(nodes[1], 1);
3601 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3602 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3603 check_added_monitors!(nodes[1], 1);
3605 expect_pending_htlcs_forwardable!(nodes[1]);
3607 let events_5 = nodes[1].node.get_and_clear_pending_events();
3608 assert_eq!(events_5.len(), 1);
3610 Event::PaymentReceived { ref payment_hash, amt: _ } => {
3611 assert_eq!(payment_hash_2, *payment_hash);
3613 _ => panic!("Unexpected event"),
3616 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3617 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3618 check_added_monitors!(nodes[0], 1);
3620 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3624 fn test_invalid_channel_announcement() {
3625 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3626 let secp_ctx = Secp256k1::new();
3627 let chanmon_cfgs = create_chanmon_cfgs(2);
3628 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3629 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3630 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3632 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::supported(), InitFeatures::supported());
3634 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3635 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3636 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3637 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3639 nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3641 let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3642 let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3644 let as_network_key = nodes[0].node.get_our_node_id();
3645 let bs_network_key = nodes[1].node.get_our_node_id();
3647 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3649 let mut chan_announcement;
3651 macro_rules! dummy_unsigned_msg {
3653 msgs::UnsignedChannelAnnouncement {
3654 features: ChannelFeatures::supported(),
3655 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3656 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3657 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3658 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3659 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3660 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3661 excess_data: Vec::new(),
3666 macro_rules! sign_msg {
3667 ($unsigned_msg: expr) => {
3668 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3669 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3670 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3671 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3672 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3673 chan_announcement = msgs::ChannelAnnouncement {
3674 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3675 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3676 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3677 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3678 contents: $unsigned_msg
3683 let unsigned_msg = dummy_unsigned_msg!();
3684 sign_msg!(unsigned_msg);
3685 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3686 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3688 // Configured with Network::Testnet
3689 let mut unsigned_msg = dummy_unsigned_msg!();
3690 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3691 sign_msg!(unsigned_msg);
3692 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3694 let mut unsigned_msg = dummy_unsigned_msg!();
3695 unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3696 sign_msg!(unsigned_msg);
3697 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3701 fn test_no_txn_manager_serialize_deserialize() {
3702 let chanmon_cfgs = create_chanmon_cfgs(2);
3703 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3704 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3705 let fee_estimator: test_utils::TestFeeEstimator;
3706 let new_chan_monitor: test_utils::TestChannelMonitor;
3707 let keys_manager: test_utils::TestKeysInterface;
3708 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3709 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3711 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3713 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3715 let nodes_0_serialized = nodes[0].node.encode();
3716 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3717 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3719 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3720 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);
3721 nodes[0].chan_monitor = &new_chan_monitor;
3722 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3723 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3724 assert!(chan_0_monitor_read.is_empty());
3726 let mut nodes_0_read = &nodes_0_serialized[..];
3727 let config = UserConfig::default();
3728 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3729 let (_, nodes_0_deserialized_tmp) = {
3730 let mut channel_monitors = HashMap::new();
3731 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &mut chan_0_monitor);
3732 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3733 default_config: config,
3734 keys_manager: &keys_manager,
3735 fee_estimator: &fee_estimator,
3736 monitor: nodes[0].chan_monitor,
3737 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3738 logger: Arc::new(test_utils::TestLogger::new()),
3739 channel_monitors: &mut channel_monitors,
3742 nodes_0_deserialized = nodes_0_deserialized_tmp;
3743 assert!(nodes_0_read.is_empty());
3745 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3746 nodes[0].node = &nodes_0_deserialized;
3747 nodes[0].block_notifier.register_listener(nodes[0].node);
3748 assert_eq!(nodes[0].node.list_channels().len(), 1);
3749 check_added_monitors!(nodes[0], 1);
3751 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3752 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3753 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3754 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3756 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3757 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3758 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3759 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3761 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3762 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3763 for node in nodes.iter() {
3764 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3765 node.router.handle_channel_update(&as_update).unwrap();
3766 node.router.handle_channel_update(&bs_update).unwrap();
3769 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3773 fn test_simple_manager_serialize_deserialize() {
3774 let chanmon_cfgs = create_chanmon_cfgs(2);
3775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3777 let fee_estimator: test_utils::TestFeeEstimator;
3778 let new_chan_monitor: test_utils::TestChannelMonitor;
3779 let keys_manager: test_utils::TestKeysInterface;
3780 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3781 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3782 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3784 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3785 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3787 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3789 let nodes_0_serialized = nodes[0].node.encode();
3790 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3791 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3793 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3794 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);
3795 nodes[0].chan_monitor = &new_chan_monitor;
3796 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3797 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3798 assert!(chan_0_monitor_read.is_empty());
3800 let mut nodes_0_read = &nodes_0_serialized[..];
3801 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3802 let (_, nodes_0_deserialized_tmp) = {
3803 let mut channel_monitors = HashMap::new();
3804 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &mut chan_0_monitor);
3805 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3806 default_config: UserConfig::default(),
3807 keys_manager: &keys_manager,
3808 fee_estimator: &fee_estimator,
3809 monitor: nodes[0].chan_monitor,
3810 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3811 logger: Arc::new(test_utils::TestLogger::new()),
3812 channel_monitors: &mut channel_monitors,
3815 nodes_0_deserialized = nodes_0_deserialized_tmp;
3816 assert!(nodes_0_read.is_empty());
3818 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3819 nodes[0].node = &nodes_0_deserialized;
3820 check_added_monitors!(nodes[0], 1);
3822 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3824 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3825 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
3829 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3830 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3831 let chanmon_cfgs = create_chanmon_cfgs(4);
3832 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3833 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3834 let fee_estimator: test_utils::TestFeeEstimator;
3835 let new_chan_monitor: test_utils::TestChannelMonitor;
3836 let keys_manager: test_utils::TestKeysInterface;
3837 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3838 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3839 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3840 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::supported(), InitFeatures::supported());
3841 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::supported(), InitFeatures::supported());
3843 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3845 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3846 let nodes_0_serialized = nodes[0].node.encode();
3848 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3849 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3850 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3851 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3853 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3855 let mut node_0_monitors_serialized = Vec::new();
3856 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3857 let mut writer = test_utils::TestVecWriter(Vec::new());
3858 monitor.1.write_for_disk(&mut writer).unwrap();
3859 node_0_monitors_serialized.push(writer.0);
3862 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3863 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);
3864 nodes[0].chan_monitor = &new_chan_monitor;
3865 let mut node_0_monitors = Vec::new();
3866 for serialized in node_0_monitors_serialized.iter() {
3867 let mut read = &serialized[..];
3868 let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3869 assert!(read.is_empty());
3870 node_0_monitors.push(monitor);
3873 let mut nodes_0_read = &nodes_0_serialized[..];
3874 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3875 let (_, nodes_0_deserialized_tmp) = <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3876 default_config: UserConfig::default(),
3877 keys_manager: &keys_manager,
3878 fee_estimator: &fee_estimator,
3879 monitor: nodes[0].chan_monitor,
3880 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3881 logger: Arc::new(test_utils::TestLogger::new()),
3882 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
3884 nodes_0_deserialized = nodes_0_deserialized_tmp;
3885 assert!(nodes_0_read.is_empty());
3887 { // Channel close should result in a commitment tx and an HTLC tx
3888 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3889 assert_eq!(txn.len(), 2);
3890 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3891 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3894 for monitor in node_0_monitors.drain(..) {
3895 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
3896 check_added_monitors!(nodes[0], 1);
3898 nodes[0].node = &nodes_0_deserialized;
3900 // nodes[1] and nodes[2] have no lost state with nodes[0]...
3901 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3902 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3903 //... and we can even still claim the payment!
3904 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
3906 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3907 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3908 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3909 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
3910 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3911 assert_eq!(msg_events.len(), 1);
3912 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
3914 &ErrorAction::SendErrorMessage { ref msg } => {
3915 assert_eq!(msg.channel_id, channel_id);
3917 _ => panic!("Unexpected event!"),
3922 macro_rules! check_spendable_outputs {
3923 ($node: expr, $der_idx: expr) => {
3925 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3926 let mut txn = Vec::new();
3927 for event in events {
3929 Event::SpendableOutputs { ref outputs } => {
3930 for outp in outputs {
3932 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
3934 previous_output: outpoint.clone(),
3935 script_sig: Script::new(),
3937 witness: Vec::new(),
3940 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3941 value: output.value,
3943 let mut spend_tx = Transaction {
3949 let secp_ctx = Secp256k1::new();
3950 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
3951 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
3952 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3953 let remotesig = secp_ctx.sign(&sighash, key);
3954 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
3955 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3956 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
3959 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
3961 previous_output: outpoint.clone(),
3962 script_sig: Script::new(),
3963 sequence: *to_self_delay as u32,
3964 witness: Vec::new(),
3967 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3968 value: output.value,
3970 let mut spend_tx = Transaction {
3976 let secp_ctx = Secp256k1::new();
3977 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
3978 let local_delaysig = secp_ctx.sign(&sighash, key);
3979 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
3980 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3981 spend_tx.input[0].witness.push(vec!(0));
3982 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
3985 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
3986 let secp_ctx = Secp256k1::new();
3988 previous_output: outpoint.clone(),
3989 script_sig: Script::new(),
3991 witness: Vec::new(),
3994 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3995 value: output.value,
3997 let mut spend_tx = Transaction {
4001 output: vec![outp.clone()],
4004 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4006 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4008 Err(_) => panic!("Your RNG is busted"),
4011 Err(_) => panic!("Your rng is busted"),
4014 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4015 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4016 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4017 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4018 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4019 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4020 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4026 _ => panic!("Unexpected event"),
4035 fn test_claim_sizeable_push_msat() {
4036 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4037 let chanmon_cfgs = create_chanmon_cfgs(2);
4038 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4039 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4040 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4042 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4043 nodes[1].node.force_close_channel(&chan.2);
4044 check_closed_broadcast!(nodes[1], false);
4045 check_added_monitors!(nodes[1], 1);
4046 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4047 assert_eq!(node_txn.len(), 1);
4048 check_spends!(node_txn[0], chan.3);
4049 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
4051 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4052 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4053 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4054 assert_eq!(spend_txn.len(), 1);
4055 check_spends!(spend_txn[0], node_txn[0]);
4059 fn test_claim_on_remote_sizeable_push_msat() {
4060 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4061 // to_remote output is encumbered by a P2WPKH
4062 let chanmon_cfgs = create_chanmon_cfgs(2);
4063 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4064 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4065 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4067 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4068 nodes[0].node.force_close_channel(&chan.2);
4069 check_closed_broadcast!(nodes[0], false);
4070 check_added_monitors!(nodes[0], 1);
4072 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4073 assert_eq!(node_txn.len(), 1);
4074 check_spends!(node_txn[0], chan.3);
4075 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
4077 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4078 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4079 check_closed_broadcast!(nodes[1], false);
4080 check_added_monitors!(nodes[1], 1);
4081 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4082 assert_eq!(spend_txn.len(), 2);
4083 assert_eq!(spend_txn[0], spend_txn[1]);
4084 check_spends!(spend_txn[0], node_txn[0]);
4088 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4089 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4090 // to_remote output is encumbered by a P2WPKH
4092 let chanmon_cfgs = create_chanmon_cfgs(2);
4093 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4094 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4095 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4097 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::supported(), InitFeatures::supported());
4098 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4099 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4100 assert_eq!(revoked_local_txn[0].input.len(), 1);
4101 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4103 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4104 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4105 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4106 check_closed_broadcast!(nodes[1], false);
4107 check_added_monitors!(nodes[1], 1);
4109 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4110 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4111 assert_eq!(spend_txn.len(), 3);
4112 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
4113 check_spends!(spend_txn[0], revoked_local_txn[0]);
4114 check_spends!(spend_txn[1], node_txn[0]);
4118 fn test_static_spendable_outputs_preimage_tx() {
4119 let chanmon_cfgs = create_chanmon_cfgs(2);
4120 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4121 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4122 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4124 // Create some initial channels
4125 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4127 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4129 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4130 assert_eq!(commitment_tx[0].input.len(), 1);
4131 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4133 // Settle A's commitment tx on B's chain
4134 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4135 assert!(nodes[1].node.claim_funds(payment_preimage, 3_000_000));
4136 check_added_monitors!(nodes[1], 1);
4137 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4138 check_added_monitors!(nodes[1], 1);
4139 let events = nodes[1].node.get_and_clear_pending_msg_events();
4141 MessageSendEvent::UpdateHTLCs { .. } => {},
4142 _ => panic!("Unexpected event"),
4145 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4146 _ => panic!("Unexepected event"),
4149 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4150 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4151 assert_eq!(node_txn.len(), 3);
4152 check_spends!(node_txn[0], commitment_tx[0]);
4153 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4154 eprintln!("{:?}", node_txn[1]);
4155 check_spends!(node_txn[1], chan_1.3);
4156 check_spends!(node_txn[2], node_txn[1]);
4158 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
4159 assert_eq!(spend_txn.len(), 1);
4160 check_spends!(spend_txn[0], node_txn[0]);
4164 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4165 let chanmon_cfgs = create_chanmon_cfgs(2);
4166 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4167 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4168 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4170 // Create some initial channels
4171 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4173 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4174 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter_mut().next().unwrap().1.channel_monitor().get_latest_local_commitment_txn();
4175 assert_eq!(revoked_local_txn[0].input.len(), 1);
4176 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4178 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4180 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4181 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4182 check_closed_broadcast!(nodes[1], false);
4183 check_added_monitors!(nodes[1], 1);
4185 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4186 assert_eq!(node_txn.len(), 2);
4187 assert_eq!(node_txn[0].input.len(), 2);
4188 check_spends!(node_txn[0], revoked_local_txn[0]);
4190 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4191 assert_eq!(spend_txn.len(), 1);
4192 check_spends!(spend_txn[0], node_txn[0]);
4196 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4197 let chanmon_cfgs = create_chanmon_cfgs(2);
4198 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4199 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4200 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4202 // Create some initial channels
4203 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4205 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4206 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4207 assert_eq!(revoked_local_txn[0].input.len(), 1);
4208 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4210 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4212 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4213 // A will generate HTLC-Timeout from revoked commitment tx
4214 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4215 check_closed_broadcast!(nodes[0], false);
4216 check_added_monitors!(nodes[0], 1);
4218 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4219 assert_eq!(revoked_htlc_txn.len(), 3);
4220 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
4221 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4222 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4223 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4224 check_spends!(revoked_htlc_txn[1], chan_1.3);
4226 // B will generate justice tx from A's revoked commitment/HTLC tx
4227 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4228 check_closed_broadcast!(nodes[1], false);
4229 check_added_monitors!(nodes[1], 1);
4231 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4232 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
4233 assert_eq!(node_txn[0].input.len(), 2);
4234 check_spends!(node_txn[0], revoked_local_txn[0]);
4235 check_spends!(node_txn[1], chan_1.3);
4236 assert_eq!(node_txn[2].input.len(), 1);
4237 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4238 assert_eq!(node_txn[3].input.len(), 1);
4239 check_spends!(node_txn[3], revoked_local_txn[0]);
4241 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4242 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4243 assert_eq!(spend_txn.len(), 2);
4244 check_spends!(spend_txn[0], node_txn[0]);
4245 check_spends!(spend_txn[1], node_txn[2]);
4249 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4250 let chanmon_cfgs = create_chanmon_cfgs(2);
4251 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4252 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4253 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4255 // Create some initial channels
4256 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4258 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4259 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4260 assert_eq!(revoked_local_txn[0].input.len(), 1);
4261 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4263 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4265 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4266 // B will generate HTLC-Success from revoked commitment tx
4267 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4268 check_closed_broadcast!(nodes[1], false);
4269 check_added_monitors!(nodes[1], 1);
4270 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4272 assert_eq!(revoked_htlc_txn.len(), 3);
4273 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
4274 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4275 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4276 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4278 // A will generate justice tx from B's revoked commitment/HTLC tx
4279 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4280 check_closed_broadcast!(nodes[0], false);
4281 check_added_monitors!(nodes[0], 1);
4283 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4284 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4285 assert_eq!(node_txn[2].input.len(), 1);
4286 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4288 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4289 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4290 assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4291 assert_eq!(spend_txn[0], spend_txn[2]);
4292 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4293 check_spends!(spend_txn[1], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4294 check_spends!(spend_txn[3], node_txn[2]); // spending justice tx output on htlc success tx
4298 fn test_onchain_to_onchain_claim() {
4299 // Test that in case of channel closure, we detect the state of output thanks to
4300 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4301 // First, have C claim an HTLC against its own latest commitment transaction.
4302 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4304 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4307 let chanmon_cfgs = create_chanmon_cfgs(3);
4308 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4309 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4310 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4312 // Create some initial channels
4313 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4314 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4316 // Rebalance the network a bit by relaying one payment through all the channels ...
4317 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4318 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4320 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4321 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4322 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4323 check_spends!(commitment_tx[0], chan_2.3);
4324 nodes[2].node.claim_funds(payment_preimage, 3_000_000);
4325 check_added_monitors!(nodes[2], 1);
4326 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4327 assert!(updates.update_add_htlcs.is_empty());
4328 assert!(updates.update_fail_htlcs.is_empty());
4329 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4330 assert!(updates.update_fail_malformed_htlcs.is_empty());
4332 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4333 check_closed_broadcast!(nodes[2], false);
4334 check_added_monitors!(nodes[2], 1);
4336 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4337 assert_eq!(c_txn.len(), 4);
4338 assert_eq!(c_txn[0], c_txn[2]);
4339 assert_eq!(c_txn[0], c_txn[3]);
4340 assert_eq!(commitment_tx[0], c_txn[1]);
4341 check_spends!(c_txn[1], chan_2.3);
4342 check_spends!(c_txn[2], c_txn[1]);
4343 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4344 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4345 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4346 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4348 // 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
4349 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4351 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4352 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4353 assert_eq!(b_txn.len(), 3);
4354 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4355 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4356 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4357 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4358 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4359 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4360 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4361 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4362 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4365 check_added_monitors!(nodes[1], 1);
4366 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4367 check_added_monitors!(nodes[1], 1);
4368 match msg_events[0] {
4369 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4370 _ => panic!("Unexpected event"),
4372 match msg_events[1] {
4373 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, .. } } => {
4374 assert!(update_add_htlcs.is_empty());
4375 assert!(update_fail_htlcs.is_empty());
4376 assert_eq!(update_fulfill_htlcs.len(), 1);
4377 assert!(update_fail_malformed_htlcs.is_empty());
4378 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4380 _ => panic!("Unexpected event"),
4382 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4383 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4384 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4385 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4386 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4387 assert_eq!(b_txn.len(), 3);
4388 check_spends!(b_txn[1], chan_1.3);
4389 check_spends!(b_txn[2], b_txn[1]);
4390 check_spends!(b_txn[0], commitment_tx[0]);
4391 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4392 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4393 assert_eq!(b_txn[0].lock_time, 0); // Success tx
4395 check_closed_broadcast!(nodes[1], false);
4396 check_added_monitors!(nodes[1], 1);
4400 fn test_duplicate_payment_hash_one_failure_one_success() {
4401 // Topology : A --> B --> C
4402 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4403 let chanmon_cfgs = create_chanmon_cfgs(3);
4404 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4405 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4406 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4408 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4409 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4411 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4412 *nodes[0].network_payment_count.borrow_mut() -= 1;
4413 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4415 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get_mut(&chan_2.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4416 assert_eq!(commitment_txn[0].input.len(), 1);
4417 check_spends!(commitment_txn[0], chan_2.3);
4419 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4420 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4421 check_closed_broadcast!(nodes[1], false);
4422 check_added_monitors!(nodes[1], 1);
4424 let htlc_timeout_tx;
4425 { // Extract one of the two HTLC-Timeout transaction
4426 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4427 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4428 assert_eq!(node_txn.len(), 5);
4429 check_spends!(node_txn[0], commitment_txn[0]);
4430 assert_eq!(node_txn[0].input.len(), 1);
4431 check_spends!(node_txn[1], commitment_txn[0]);
4432 assert_eq!(node_txn[1].input.len(), 1);
4433 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4434 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4435 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4436 check_spends!(node_txn[2], chan_2.3);
4437 check_spends!(node_txn[3], node_txn[2]);
4438 check_spends!(node_txn[4], node_txn[2]);
4439 htlc_timeout_tx = node_txn[1].clone();
4442 nodes[2].node.claim_funds(our_payment_preimage, 900_000);
4443 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4444 check_added_monitors!(nodes[2], 3);
4445 let events = nodes[2].node.get_and_clear_pending_msg_events();
4447 MessageSendEvent::UpdateHTLCs { .. } => {},
4448 _ => panic!("Unexpected event"),
4451 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4452 _ => panic!("Unexepected event"),
4454 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4455 assert_eq!(htlc_success_txn.len(), 7);
4456 check_spends!(htlc_success_txn[2], chan_2.3);
4457 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4458 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4459 assert_eq!(htlc_success_txn[0], htlc_success_txn[5]);
4460 assert_eq!(htlc_success_txn[0].input.len(), 1);
4461 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4462 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4463 assert_eq!(htlc_success_txn[1].input.len(), 1);
4464 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4465 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4466 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4467 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4469 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4470 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4471 expect_pending_htlcs_forwardable!(nodes[1]);
4472 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4473 assert!(htlc_updates.update_add_htlcs.is_empty());
4474 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4475 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4476 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4477 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4478 check_added_monitors!(nodes[1], 1);
4480 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4481 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4483 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4484 let events = nodes[0].node.get_and_clear_pending_msg_events();
4485 assert_eq!(events.len(), 1);
4487 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
4489 _ => { panic!("Unexpected event"); }
4492 let events = nodes[0].node.get_and_clear_pending_events();
4494 Event::PaymentFailed { ref payment_hash, .. } => {
4495 assert_eq!(*payment_hash, duplicate_payment_hash);
4497 _ => panic!("Unexpected event"),
4500 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4501 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4502 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4503 assert!(updates.update_add_htlcs.is_empty());
4504 assert!(updates.update_fail_htlcs.is_empty());
4505 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4506 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4507 assert!(updates.update_fail_malformed_htlcs.is_empty());
4508 check_added_monitors!(nodes[1], 1);
4510 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4511 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4513 let events = nodes[0].node.get_and_clear_pending_events();
4515 Event::PaymentSent { ref payment_preimage } => {
4516 assert_eq!(*payment_preimage, our_payment_preimage);
4518 _ => panic!("Unexpected event"),
4523 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4524 let chanmon_cfgs = create_chanmon_cfgs(2);
4525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4527 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4529 // Create some initial channels
4530 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4532 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4533 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4534 assert_eq!(local_txn[0].input.len(), 1);
4535 check_spends!(local_txn[0], chan_1.3);
4537 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4538 nodes[1].node.claim_funds(payment_preimage, 9_000_000);
4539 check_added_monitors!(nodes[1], 1);
4540 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4541 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4542 check_added_monitors!(nodes[1], 1);
4543 let events = nodes[1].node.get_and_clear_pending_msg_events();
4545 MessageSendEvent::UpdateHTLCs { .. } => {},
4546 _ => panic!("Unexpected event"),
4549 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4550 _ => panic!("Unexepected event"),
4552 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4553 assert_eq!(node_txn[0].input.len(), 1);
4554 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4555 check_spends!(node_txn[0], local_txn[0]);
4557 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4558 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4559 assert_eq!(spend_txn.len(), 2);
4560 check_spends!(spend_txn[0], node_txn[0]);
4561 check_spends!(spend_txn[1], node_txn[2]);
4564 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4565 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4566 // unrevoked commitment transaction.
4567 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4568 // a remote RAA before they could be failed backwards (and combinations thereof).
4569 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4570 // use the same payment hashes.
4571 // Thus, we use a six-node network:
4576 // And test where C fails back to A/B when D announces its latest commitment transaction
4577 let chanmon_cfgs = create_chanmon_cfgs(6);
4578 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4579 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
4580 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4582 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::supported(), InitFeatures::supported());
4583 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4584 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
4585 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
4586 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
4588 // Rebalance and check output sanity...
4589 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4590 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4591 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn()[0].output.len(), 2);
4593 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4595 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
4597 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
4598 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4600 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
4602 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
4604 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4606 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4607 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4609 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4611 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4614 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4616 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
4617 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
4620 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
4622 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4623 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4625 // Double-check that six of the new HTLC were added
4626 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4627 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4628 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn().len(), 1);
4629 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn()[0].output.len(), 8);
4631 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4632 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4633 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
4634 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
4635 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
4636 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
4637 check_added_monitors!(nodes[4], 0);
4638 expect_pending_htlcs_forwardable!(nodes[4]);
4639 check_added_monitors!(nodes[4], 1);
4641 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4642 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4643 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4644 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4645 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4646 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4648 // Fail 3rd below-dust and 7th above-dust HTLCs
4649 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
4650 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
4651 check_added_monitors!(nodes[5], 0);
4652 expect_pending_htlcs_forwardable!(nodes[5]);
4653 check_added_monitors!(nodes[5], 1);
4655 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4656 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4657 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4658 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4660 let ds_prev_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4662 expect_pending_htlcs_forwardable!(nodes[3]);
4663 check_added_monitors!(nodes[3], 1);
4664 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4665 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4666 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4667 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4668 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4669 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4670 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4671 if deliver_last_raa {
4672 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4674 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4677 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4678 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4679 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4680 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4682 // We now broadcast the latest commitment transaction, which *should* result in failures for
4683 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4684 // the non-broadcast above-dust HTLCs.
4686 // Alternatively, we may broadcast the previous commitment transaction, which should only
4687 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4688 let ds_last_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4690 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4691 if announce_latest {
4692 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4694 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4696 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4697 check_closed_broadcast!(nodes[2], false);
4698 expect_pending_htlcs_forwardable!(nodes[2]);
4699 check_added_monitors!(nodes[2], 3);
4701 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4702 assert_eq!(cs_msgs.len(), 2);
4703 let mut a_done = false;
4704 for msg in cs_msgs {
4706 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4707 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4708 // should be failed-backwards here.
4709 let target = if *node_id == nodes[0].node.get_our_node_id() {
4710 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4711 for htlc in &updates.update_fail_htlcs {
4712 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 });
4714 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4719 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4720 for htlc in &updates.update_fail_htlcs {
4721 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4723 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4724 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4727 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4728 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
4729 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
4730 if announce_latest {
4731 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
4732 if *node_id == nodes[0].node.get_our_node_id() {
4733 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
4736 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4738 _ => panic!("Unexpected event"),
4742 let as_events = nodes[0].node.get_and_clear_pending_events();
4743 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4744 let mut as_failds = HashSet::new();
4745 for event in as_events.iter() {
4746 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4747 assert!(as_failds.insert(*payment_hash));
4748 if *payment_hash != payment_hash_2 {
4749 assert_eq!(*rejected_by_dest, deliver_last_raa);
4751 assert!(!rejected_by_dest);
4753 } else { panic!("Unexpected event"); }
4755 assert!(as_failds.contains(&payment_hash_1));
4756 assert!(as_failds.contains(&payment_hash_2));
4757 if announce_latest {
4758 assert!(as_failds.contains(&payment_hash_3));
4759 assert!(as_failds.contains(&payment_hash_5));
4761 assert!(as_failds.contains(&payment_hash_6));
4763 let bs_events = nodes[1].node.get_and_clear_pending_events();
4764 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4765 let mut bs_failds = HashSet::new();
4766 for event in bs_events.iter() {
4767 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4768 assert!(bs_failds.insert(*payment_hash));
4769 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4770 assert_eq!(*rejected_by_dest, deliver_last_raa);
4772 assert!(!rejected_by_dest);
4774 } else { panic!("Unexpected event"); }
4776 assert!(bs_failds.contains(&payment_hash_1));
4777 assert!(bs_failds.contains(&payment_hash_2));
4778 if announce_latest {
4779 assert!(bs_failds.contains(&payment_hash_4));
4781 assert!(bs_failds.contains(&payment_hash_5));
4783 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4784 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4785 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4786 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4787 // PaymentFailureNetworkUpdates.
4788 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4789 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4790 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4791 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4792 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4794 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4795 _ => panic!("Unexpected event"),
4801 fn test_fail_backwards_latest_remote_announce_a() {
4802 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4806 fn test_fail_backwards_latest_remote_announce_b() {
4807 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4811 fn test_fail_backwards_previous_remote_announce() {
4812 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4813 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4814 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4818 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4819 let chanmon_cfgs = create_chanmon_cfgs(2);
4820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4822 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4824 // Create some initial channels
4825 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4827 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4828 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
4829 assert_eq!(local_txn[0].input.len(), 1);
4830 check_spends!(local_txn[0], chan_1.3);
4832 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4833 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4834 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4835 check_closed_broadcast!(nodes[0], false);
4836 check_added_monitors!(nodes[0], 1);
4838 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4839 assert_eq!(node_txn[0].input.len(), 1);
4840 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4841 check_spends!(node_txn[0], local_txn[0]);
4843 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4844 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4845 assert_eq!(spend_txn.len(), 8);
4846 assert_eq!(spend_txn[0], spend_txn[2]);
4847 assert_eq!(spend_txn[0], spend_txn[4]);
4848 assert_eq!(spend_txn[0], spend_txn[6]);
4849 assert_eq!(spend_txn[1], spend_txn[3]);
4850 assert_eq!(spend_txn[1], spend_txn[5]);
4851 assert_eq!(spend_txn[1], spend_txn[7]);
4852 check_spends!(spend_txn[0], local_txn[0]);
4853 check_spends!(spend_txn[1], node_txn[0]);
4857 fn test_static_output_closing_tx() {
4858 let chanmon_cfgs = create_chanmon_cfgs(2);
4859 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4860 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4861 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4863 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4865 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4866 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4868 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4869 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4870 let spend_txn = check_spendable_outputs!(nodes[0], 2);
4871 assert_eq!(spend_txn.len(), 1);
4872 check_spends!(spend_txn[0], closing_tx);
4874 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4875 let spend_txn = check_spendable_outputs!(nodes[1], 2);
4876 assert_eq!(spend_txn.len(), 1);
4877 check_spends!(spend_txn[0], closing_tx);
4880 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4881 let chanmon_cfgs = create_chanmon_cfgs(2);
4882 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4883 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4884 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4885 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4887 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4889 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4890 // present in B's local commitment transaction, but none of A's commitment transactions.
4891 assert!(nodes[1].node.claim_funds(our_payment_preimage, if use_dust { 50_000 } else { 3_000_000 }));
4892 check_added_monitors!(nodes[1], 1);
4894 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4895 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
4896 let events = nodes[0].node.get_and_clear_pending_events();
4897 assert_eq!(events.len(), 1);
4899 Event::PaymentSent { payment_preimage } => {
4900 assert_eq!(payment_preimage, our_payment_preimage);
4902 _ => panic!("Unexpected event"),
4905 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4906 check_added_monitors!(nodes[0], 1);
4907 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4908 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4909 check_added_monitors!(nodes[1], 1);
4911 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4912 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4913 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4914 header.prev_blockhash = header.bitcoin_hash();
4916 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4917 check_closed_broadcast!(nodes[1], false);
4918 check_added_monitors!(nodes[1], 1);
4921 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4922 let chanmon_cfgs = create_chanmon_cfgs(2);
4923 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4924 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4925 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4926 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4928 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV).unwrap();
4929 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4930 nodes[0].node.send_payment(route, payment_hash).unwrap();
4931 check_added_monitors!(nodes[0], 1);
4933 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4935 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4936 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4937 // to "time out" the HTLC.
4939 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4941 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4942 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
4943 header.prev_blockhash = header.bitcoin_hash();
4945 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4946 check_closed_broadcast!(nodes[0], false);
4947 check_added_monitors!(nodes[0], 1);
4950 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4951 let chanmon_cfgs = create_chanmon_cfgs(3);
4952 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4953 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4954 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4955 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4957 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4958 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4959 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4960 // actually revoked.
4961 let htlc_value = if use_dust { 50000 } else { 3000000 };
4962 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4963 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4964 expect_pending_htlcs_forwardable!(nodes[1]);
4965 check_added_monitors!(nodes[1], 1);
4967 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4968 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
4969 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4970 check_added_monitors!(nodes[0], 1);
4971 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4972 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4973 check_added_monitors!(nodes[1], 1);
4974 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
4975 check_added_monitors!(nodes[1], 1);
4976 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4978 if check_revoke_no_close {
4979 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4980 check_added_monitors!(nodes[0], 1);
4983 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4984 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4985 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4986 header.prev_blockhash = header.bitcoin_hash();
4988 if !check_revoke_no_close {
4989 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4990 check_closed_broadcast!(nodes[0], false);
4991 check_added_monitors!(nodes[0], 1);
4993 let events = nodes[0].node.get_and_clear_pending_events();
4994 assert_eq!(events.len(), 1);
4996 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4997 assert_eq!(payment_hash, our_payment_hash);
4998 assert!(rejected_by_dest);
5000 _ => panic!("Unexpected event"),
5005 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5006 // There are only a few cases to test here:
5007 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5008 // broadcastable commitment transactions result in channel closure,
5009 // * its included in an unrevoked-but-previous remote commitment transaction,
5010 // * its included in the latest remote or local commitment transactions.
5011 // We test each of the three possible commitment transactions individually and use both dust and
5013 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5014 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5015 // tested for at least one of the cases in other tests.
5017 fn htlc_claim_single_commitment_only_a() {
5018 do_htlc_claim_local_commitment_only(true);
5019 do_htlc_claim_local_commitment_only(false);
5021 do_htlc_claim_current_remote_commitment_only(true);
5022 do_htlc_claim_current_remote_commitment_only(false);
5026 fn htlc_claim_single_commitment_only_b() {
5027 do_htlc_claim_previous_remote_commitment_only(true, false);
5028 do_htlc_claim_previous_remote_commitment_only(false, false);
5029 do_htlc_claim_previous_remote_commitment_only(true, true);
5030 do_htlc_claim_previous_remote_commitment_only(false, true);
5033 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>)
5034 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5037 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);
5041 // 0: node1 fails backward
5042 // 1: final node fails backward
5043 // 2: payment completed but the user rejects the payment
5044 // 3: final node fails backward (but tamper onion payloads from node0)
5045 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5046 // 200: trigger error in the final node and tamper returning fail_htlc
5047 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>)
5048 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5049 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5053 // reset block height
5054 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5055 for ix in 0..nodes.len() {
5056 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5059 macro_rules! expect_event {
5060 ($node: expr, $event_type: path) => {{
5061 let events = $node.node.get_and_clear_pending_events();
5062 assert_eq!(events.len(), 1);
5064 $event_type { .. } => {},
5065 _ => panic!("Unexpected event"),
5070 macro_rules! expect_htlc_forward {
5072 expect_event!($node, Event::PendingHTLCsForwardable);
5073 $node.node.process_pending_htlc_forwards();
5077 // 0 ~~> 2 send payment
5078 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
5079 check_added_monitors!(nodes[0], 1);
5080 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5081 // temper update_add (0 => 1)
5082 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5083 if test_case == 0 || test_case == 3 || test_case == 100 {
5084 callback_msg(&mut update_add_0);
5087 // 0 => 1 update_add & CS
5088 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5089 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5091 let update_1_0 = match test_case {
5092 0|100 => { // intermediate node failure; fail backward to 0
5093 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5094 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));
5097 1|2|3|200 => { // final node failure; forwarding to 2
5098 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5100 if test_case != 200 {
5103 expect_htlc_forward!(&nodes[1]);
5105 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5106 check_added_monitors!(&nodes[1], 1);
5107 assert_eq!(update_1.update_add_htlcs.len(), 1);
5108 // tamper update_add (1 => 2)
5109 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5110 if test_case != 3 && test_case != 200 {
5111 callback_msg(&mut update_add_1);
5115 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5116 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5118 if test_case == 2 || test_case == 200 {
5119 expect_htlc_forward!(&nodes[2]);
5120 expect_event!(&nodes[2], Event::PaymentReceived);
5122 expect_pending_htlcs_forwardable!(nodes[2]);
5125 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5126 if test_case == 2 || test_case == 200 {
5127 check_added_monitors!(&nodes[2], 1);
5129 assert!(update_2_1.update_fail_htlcs.len() == 1);
5131 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5132 if test_case == 200 {
5133 callback_fail(&mut fail_msg);
5137 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5138 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5140 // backward fail on 1
5141 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5142 assert!(update_1_0.update_fail_htlcs.len() == 1);
5145 _ => unreachable!(),
5148 // 1 => 0 commitment_signed_dance
5149 if update_1_0.update_fail_htlcs.len() > 0 {
5150 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5151 if test_case == 100 {
5152 callback_fail(&mut fail_msg);
5154 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5156 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5159 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5161 let events = nodes[0].node.get_and_clear_pending_events();
5162 assert_eq!(events.len(), 1);
5163 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
5164 assert_eq!(*rejected_by_dest, !expected_retryable);
5165 assert_eq!(*error_code, expected_error_code);
5167 panic!("Uexpected event");
5170 let events = nodes[0].node.get_and_clear_pending_msg_events();
5171 if expected_channel_update.is_some() {
5172 assert_eq!(events.len(), 1);
5174 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5176 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5177 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5178 panic!("channel_update not found!");
5181 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5182 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5183 assert!(*short_channel_id == *expected_short_channel_id);
5184 assert!(*is_permanent == *expected_is_permanent);
5186 panic!("Unexpected message event");
5189 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5190 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5191 assert!(*node_id == *expected_node_id);
5192 assert!(*is_permanent == *expected_is_permanent);
5194 panic!("Unexpected message event");
5199 _ => panic!("Unexpected message event"),
5202 assert_eq!(events.len(), 0);
5206 impl msgs::ChannelUpdate {
5207 fn dummy() -> msgs::ChannelUpdate {
5208 use secp256k1::ffi::Signature as FFISignature;
5209 use secp256k1::Signature;
5210 msgs::ChannelUpdate {
5211 signature: Signature::from(FFISignature::new()),
5212 contents: msgs::UnsignedChannelUpdate {
5213 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
5214 short_channel_id: 0,
5217 cltv_expiry_delta: 0,
5218 htlc_minimum_msat: 0,
5220 fee_proportional_millionths: 0,
5221 excess_data: vec![],
5227 struct BogusOnionHopData {
5230 impl BogusOnionHopData {
5231 fn new(orig: msgs::OnionHopData) -> Self {
5232 Self { data: orig.encode() }
5235 impl Writeable for BogusOnionHopData {
5236 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5237 writer.write_all(&self.data[..])
5242 fn test_onion_failure() {
5243 use ln::msgs::ChannelUpdate;
5244 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5247 const BADONION: u16 = 0x8000;
5248 const PERM: u16 = 0x4000;
5249 const NODE: u16 = 0x2000;
5250 const UPDATE: u16 = 0x1000;
5252 let chanmon_cfgs = create_chanmon_cfgs(3);
5253 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5254 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5255 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5256 for node in nodes.iter() {
5257 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5259 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported())];
5260 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5261 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
5263 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5265 // intermediate node failure
5266 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5267 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5268 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5269 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5270 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5271 let mut new_payloads = Vec::new();
5272 for payload in onion_payloads.drain(..) {
5273 new_payloads.push(BogusOnionHopData::new(payload));
5275 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5276 // describing a length-1 TLV payload, which is obviously bogus.
5277 new_payloads[0].data[0] = 1;
5278 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5279 }, ||{}, 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
5281 // final node failure
5282 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5283 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5284 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5285 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5286 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5287 let mut new_payloads = Vec::new();
5288 for payload in onion_payloads.drain(..) {
5289 new_payloads.push(BogusOnionHopData::new(payload));
5291 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5292 // length-1 TLV payload, which is obviously bogus.
5293 new_payloads[1].data[0] = 1;
5294 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5295 }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5297 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5298 // receiving simulated fail messages
5299 // intermediate node failure
5300 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5302 msg.amount_msat -= 1;
5304 // and tamper returning error message
5305 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5306 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5307 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5308 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
5310 // final node failure
5311 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5312 // and tamper returning error message
5313 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5314 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5315 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5317 nodes[2].node.fail_htlc_backwards(&payment_hash);
5318 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
5320 // intermediate node failure
5321 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5322 msg.amount_msat -= 1;
5324 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5325 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5326 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5327 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
5329 // final node failure
5330 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5331 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5332 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5333 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5335 nodes[2].node.fail_htlc_backwards(&payment_hash);
5336 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
5338 // intermediate node failure
5339 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5340 msg.amount_msat -= 1;
5342 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5343 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5344 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5346 nodes[2].node.fail_htlc_backwards(&payment_hash);
5347 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
5349 // final node failure
5350 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5351 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5352 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5353 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5355 nodes[2].node.fail_htlc_backwards(&payment_hash);
5356 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
5358 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5359 Some(BADONION|PERM|4), None);
5361 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5362 Some(BADONION|PERM|5), None);
5364 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5365 Some(BADONION|PERM|6), None);
5367 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5368 msg.amount_msat -= 1;
5370 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5371 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5372 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5373 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5375 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5376 msg.amount_msat -= 1;
5378 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5379 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5380 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5381 // short_channel_id from the processing node
5382 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5384 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5385 msg.amount_msat -= 1;
5387 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5388 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5389 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5390 // short_channel_id from the processing node
5391 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5393 let mut bogus_route = route.clone();
5394 bogus_route.hops[1].short_channel_id -= 1;
5395 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5396 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
5398 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5399 let mut bogus_route = route.clone();
5400 let route_len = bogus_route.hops.len();
5401 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
5402 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5404 //TODO: with new config API, we will be able to generate both valid and
5405 //invalid channel_update cases.
5406 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5407 msg.amount_msat -= 1;
5408 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5410 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5411 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5412 msg.cltv_expiry -= 1;
5413 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5415 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5416 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5417 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5419 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5420 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5422 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5423 nodes[2].node.fail_htlc_backwards(&payment_hash);
5424 }, false, Some(PERM|15), None);
5426 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5427 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5428 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5430 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5431 }, || {}, true, Some(17), None);
5433 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5434 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5435 for f in pending_forwards.iter_mut() {
5437 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5438 forward_info.outgoing_cltv_value += 1,
5443 }, true, Some(18), None);
5445 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5446 // violate amt_to_forward > msg.amount_msat
5447 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5448 for f in pending_forwards.iter_mut() {
5450 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5451 forward_info.amt_to_forward -= 1,
5456 }, true, Some(19), None);
5458 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5459 // disconnect event to the channel between nodes[1] ~ nodes[2]
5460 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5461 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5462 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5463 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5465 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5466 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5467 let mut route = route.clone();
5469 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
5470 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5471 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
5472 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5473 msg.cltv_expiry = htlc_cltv;
5474 msg.onion_routing_packet = onion_packet;
5475 }, ||{}, true, Some(21), None);
5480 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5481 let chanmon_cfgs = create_chanmon_cfgs(2);
5482 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5483 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5484 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5485 //Force duplicate channel ids
5486 for node in nodes.iter() {
5487 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5490 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5491 let channel_value_satoshis=10000;
5492 let push_msat=10001;
5493 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5494 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5495 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &node0_to_1_send_open_channel);
5497 //Create a second channel with a channel_id collision
5498 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5502 fn bolt2_open_channel_sending_node_checks_part2() {
5503 let chanmon_cfgs = create_chanmon_cfgs(2);
5504 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5505 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5506 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5508 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5509 let channel_value_satoshis=2^24;
5510 let push_msat=10001;
5511 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5513 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5514 let channel_value_satoshis=10000;
5515 // Test when push_msat is equal to 1000 * funding_satoshis.
5516 let push_msat=1000*channel_value_satoshis+1;
5517 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5519 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5520 let channel_value_satoshis=10000;
5521 let push_msat=10001;
5522 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
5523 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5524 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5526 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5527 // 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
5528 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5530 // 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.
5531 assert!(BREAKDOWN_TIMEOUT>0);
5532 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5534 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5535 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5536 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5538 // 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.
5539 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5540 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5541 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5542 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
5543 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5546 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5547 // 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.
5548 //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.
5551 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5552 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5553 let chanmon_cfgs = create_chanmon_cfgs(2);
5554 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5555 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5556 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5557 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5558 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5559 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5561 route.hops[0].fee_msat = 100;
5563 let err = nodes[0].node.send_payment(route, our_payment_hash);
5565 if let Err(APIError::ChannelUnavailable{err}) = err {
5566 assert_eq!(err, "Cannot send less than their minimum HTLC value");
5570 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5571 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5575 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5576 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5577 let chanmon_cfgs = create_chanmon_cfgs(2);
5578 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5579 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5580 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5581 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5582 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5583 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5585 route.hops[0].fee_msat = 0;
5587 let err = nodes[0].node.send_payment(route, our_payment_hash);
5589 if let Err(APIError::ChannelUnavailable{err}) = err {
5590 assert_eq!(err, "Cannot send 0-msat HTLC");
5594 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5595 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5599 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5600 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5601 let chanmon_cfgs = create_chanmon_cfgs(2);
5602 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5603 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5604 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5605 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5606 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5607 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5609 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5610 check_added_monitors!(nodes[0], 1);
5611 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5612 updates.update_add_htlcs[0].amount_msat = 0;
5614 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5615 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5616 check_closed_broadcast!(nodes[1], true).unwrap();
5617 check_added_monitors!(nodes[1], 1);
5621 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5622 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5623 //It is enforced when constructing a route.
5624 let chanmon_cfgs = create_chanmon_cfgs(2);
5625 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5626 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5627 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5628 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::supported(), InitFeatures::supported());
5629 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5630 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5632 let err = nodes[0].node.send_payment(route, our_payment_hash);
5634 if let Err(APIError::RouteError{err}) = err {
5635 assert_eq!(err, "Channel CLTV overflowed?!");
5642 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5643 //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.
5644 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5645 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5646 let chanmon_cfgs = create_chanmon_cfgs(2);
5647 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5648 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5649 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5650 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::supported(), InitFeatures::supported());
5651 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5653 for i in 0..max_accepted_htlcs {
5654 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5655 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5656 let payment_event = {
5657 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5658 check_added_monitors!(nodes[0], 1);
5660 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5661 assert_eq!(events.len(), 1);
5662 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5663 assert_eq!(htlcs[0].htlc_id, i);
5667 SendEvent::from_event(events.remove(0))
5669 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5670 check_added_monitors!(nodes[1], 0);
5671 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5673 expect_pending_htlcs_forwardable!(nodes[1]);
5674 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5676 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5677 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5678 let err = nodes[0].node.send_payment(route, our_payment_hash);
5680 if let Err(APIError::ChannelUnavailable{err}) = err {
5681 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
5685 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5686 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
5690 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5691 //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.
5692 let chanmon_cfgs = create_chanmon_cfgs(2);
5693 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5694 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5695 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5696 let channel_value = 100000;
5697 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::supported(), InitFeatures::supported());
5698 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5700 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5702 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5703 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5704 let err = nodes[0].node.send_payment(route, our_payment_hash);
5706 if let Err(APIError::ChannelUnavailable{err}) = err {
5707 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept");
5711 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5712 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);
5714 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5717 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5719 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5720 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5721 let chanmon_cfgs = create_chanmon_cfgs(2);
5722 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5723 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5724 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5725 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5726 let htlc_minimum_msat: u64;
5728 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5729 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5730 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5732 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5733 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5734 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5735 check_added_monitors!(nodes[0], 1);
5736 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5737 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5738 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5739 assert!(nodes[1].node.list_channels().is_empty());
5740 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5741 assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
5742 check_added_monitors!(nodes[1], 1);
5746 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5747 //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
5748 let chanmon_cfgs = create_chanmon_cfgs(2);
5749 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5750 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5751 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5752 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5754 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5756 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5757 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5758 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5759 check_added_monitors!(nodes[0], 1);
5760 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5762 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5763 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5765 assert!(nodes[1].node.list_channels().is_empty());
5766 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5767 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
5768 check_added_monitors!(nodes[1], 1);
5772 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5773 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5774 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5775 let chanmon_cfgs = create_chanmon_cfgs(2);
5776 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5777 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5778 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5779 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5780 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5781 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5783 let session_priv = SecretKey::from_slice(&{
5784 let mut session_key = [0; 32];
5785 let mut rng = thread_rng();
5786 rng.fill_bytes(&mut session_key);
5788 }).expect("RNG is bad!");
5790 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5791 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
5792 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5793 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
5795 let mut msg = msgs::UpdateAddHTLC {
5799 payment_hash: our_payment_hash,
5800 cltv_expiry: htlc_cltv,
5801 onion_routing_packet: onion_packet.clone(),
5804 for i in 0..super::channel::OUR_MAX_HTLCS {
5805 msg.htlc_id = i as u64;
5806 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5808 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5809 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5811 assert!(nodes[1].node.list_channels().is_empty());
5812 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5813 assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
5814 check_added_monitors!(nodes[1], 1);
5818 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5819 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5820 let chanmon_cfgs = create_chanmon_cfgs(2);
5821 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5822 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5823 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5824 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
5825 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5826 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5827 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5828 check_added_monitors!(nodes[0], 1);
5829 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5830 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5831 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5833 assert!(nodes[1].node.list_channels().is_empty());
5834 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5835 assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
5836 check_added_monitors!(nodes[1], 1);
5840 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5841 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
5842 let chanmon_cfgs = create_chanmon_cfgs(2);
5843 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5844 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5845 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5846 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5847 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5848 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5849 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5850 check_added_monitors!(nodes[0], 1);
5851 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5852 updates.update_add_htlcs[0].cltv_expiry = 500000000;
5853 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5855 assert!(nodes[1].node.list_channels().is_empty());
5856 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5857 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
5858 check_added_monitors!(nodes[1], 1);
5862 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5863 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5864 // We test this by first testing that that repeated HTLCs pass commitment signature checks
5865 // after disconnect and that non-sequential htlc_ids result in a channel failure.
5866 let chanmon_cfgs = create_chanmon_cfgs(2);
5867 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5868 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5869 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5870 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5871 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5872 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5873 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5874 check_added_monitors!(nodes[0], 1);
5875 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5876 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5878 //Disconnect and Reconnect
5879 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5880 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5881 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5882 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5883 assert_eq!(reestablish_1.len(), 1);
5884 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5885 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5886 assert_eq!(reestablish_2.len(), 1);
5887 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
5888 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5889 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
5890 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5893 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5894 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5895 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
5896 check_added_monitors!(nodes[1], 1);
5897 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5899 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5901 assert!(nodes[1].node.list_channels().is_empty());
5902 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5903 assert_eq!(err_msg.data, "Remote skipped HTLC ID");
5904 check_added_monitors!(nodes[1], 1);
5908 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5909 //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.
5911 let chanmon_cfgs = create_chanmon_cfgs(2);
5912 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5913 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5914 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5915 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5917 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5918 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5919 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5920 check_added_monitors!(nodes[0], 1);
5921 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5922 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5924 let update_msg = msgs::UpdateFulfillHTLC{
5927 payment_preimage: our_payment_preimage,
5930 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5932 assert!(nodes[0].node.list_channels().is_empty());
5933 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5934 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5935 check_added_monitors!(nodes[0], 1);
5939 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5940 //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.
5942 let chanmon_cfgs = create_chanmon_cfgs(2);
5943 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5944 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5945 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5946 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5948 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5949 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5950 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5951 check_added_monitors!(nodes[0], 1);
5952 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5953 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5955 let update_msg = msgs::UpdateFailHTLC{
5958 reason: msgs::OnionErrorPacket { data: Vec::new()},
5961 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5963 assert!(nodes[0].node.list_channels().is_empty());
5964 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5965 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5966 check_added_monitors!(nodes[0], 1);
5970 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5971 //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.
5973 let chanmon_cfgs = create_chanmon_cfgs(2);
5974 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5975 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5976 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5977 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5979 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5980 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5981 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5982 check_added_monitors!(nodes[0], 1);
5983 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5984 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5986 let update_msg = msgs::UpdateFailMalformedHTLC{
5989 sha256_of_onion: [1; 32],
5990 failure_code: 0x8000,
5993 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5995 assert!(nodes[0].node.list_channels().is_empty());
5996 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5997 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5998 check_added_monitors!(nodes[0], 1);
6002 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6003 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6005 let chanmon_cfgs = create_chanmon_cfgs(2);
6006 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6007 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6008 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6009 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6011 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6013 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
6014 check_added_monitors!(nodes[1], 1);
6016 let events = nodes[1].node.get_and_clear_pending_msg_events();
6017 assert_eq!(events.len(), 1);
6018 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6020 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, .. } } => {
6021 assert!(update_add_htlcs.is_empty());
6022 assert_eq!(update_fulfill_htlcs.len(), 1);
6023 assert!(update_fail_htlcs.is_empty());
6024 assert!(update_fail_malformed_htlcs.is_empty());
6025 assert!(update_fee.is_none());
6026 update_fulfill_htlcs[0].clone()
6028 _ => panic!("Unexpected event"),
6032 update_fulfill_msg.htlc_id = 1;
6034 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6036 assert!(nodes[0].node.list_channels().is_empty());
6037 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6038 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6039 check_added_monitors!(nodes[0], 1);
6043 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6044 //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.
6046 let chanmon_cfgs = create_chanmon_cfgs(2);
6047 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6048 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6049 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6050 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6052 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6054 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
6055 check_added_monitors!(nodes[1], 1);
6057 let events = nodes[1].node.get_and_clear_pending_msg_events();
6058 assert_eq!(events.len(), 1);
6059 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6061 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, .. } } => {
6062 assert!(update_add_htlcs.is_empty());
6063 assert_eq!(update_fulfill_htlcs.len(), 1);
6064 assert!(update_fail_htlcs.is_empty());
6065 assert!(update_fail_malformed_htlcs.is_empty());
6066 assert!(update_fee.is_none());
6067 update_fulfill_htlcs[0].clone()
6069 _ => panic!("Unexpected event"),
6073 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6075 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6077 assert!(nodes[0].node.list_channels().is_empty());
6078 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6079 assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6080 check_added_monitors!(nodes[0], 1);
6084 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6085 //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.
6087 let chanmon_cfgs = create_chanmon_cfgs(2);
6088 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6089 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6090 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6091 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6092 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6093 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6094 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6095 check_added_monitors!(nodes[0], 1);
6097 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6098 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6100 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6101 check_added_monitors!(nodes[1], 0);
6102 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6104 let events = nodes[1].node.get_and_clear_pending_msg_events();
6106 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6108 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, .. } } => {
6109 assert!(update_add_htlcs.is_empty());
6110 assert!(update_fulfill_htlcs.is_empty());
6111 assert!(update_fail_htlcs.is_empty());
6112 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6113 assert!(update_fee.is_none());
6114 update_fail_malformed_htlcs[0].clone()
6116 _ => panic!("Unexpected event"),
6119 update_msg.failure_code &= !0x8000;
6120 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6122 assert!(nodes[0].node.list_channels().is_empty());
6123 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6124 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6125 check_added_monitors!(nodes[0], 1);
6129 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6130 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6131 // * 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.
6133 let chanmon_cfgs = create_chanmon_cfgs(3);
6134 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6135 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6136 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6137 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6138 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6140 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
6141 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6144 let mut payment_event = {
6145 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6146 check_added_monitors!(nodes[0], 1);
6147 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6148 assert_eq!(events.len(), 1);
6149 SendEvent::from_event(events.remove(0))
6151 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6152 check_added_monitors!(nodes[1], 0);
6153 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6154 expect_pending_htlcs_forwardable!(nodes[1]);
6155 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6156 assert_eq!(events_2.len(), 1);
6157 check_added_monitors!(nodes[1], 1);
6158 payment_event = SendEvent::from_event(events_2.remove(0));
6159 assert_eq!(payment_event.msgs.len(), 1);
6162 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6163 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6164 check_added_monitors!(nodes[2], 0);
6165 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6167 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6168 assert_eq!(events_3.len(), 1);
6169 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6171 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 } } => {
6172 assert!(update_add_htlcs.is_empty());
6173 assert!(update_fulfill_htlcs.is_empty());
6174 assert!(update_fail_htlcs.is_empty());
6175 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6176 assert!(update_fee.is_none());
6177 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6179 _ => panic!("Unexpected event"),
6183 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6185 check_added_monitors!(nodes[1], 0);
6186 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6187 expect_pending_htlcs_forwardable!(nodes[1]);
6188 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6189 assert_eq!(events_4.len(), 1);
6191 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6193 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, .. } } => {
6194 assert!(update_add_htlcs.is_empty());
6195 assert!(update_fulfill_htlcs.is_empty());
6196 assert_eq!(update_fail_htlcs.len(), 1);
6197 assert!(update_fail_malformed_htlcs.is_empty());
6198 assert!(update_fee.is_none());
6200 _ => panic!("Unexpected event"),
6203 check_added_monitors!(nodes[1], 1);
6206 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6207 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6208 // 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
6209 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6211 let chanmon_cfgs = create_chanmon_cfgs(2);
6212 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6213 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6214 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6215 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6217 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6219 // We route 2 dust-HTLCs between A and B
6220 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6221 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6222 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6224 // Cache one local commitment tx as previous
6225 let as_prev_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6227 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6228 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6229 check_added_monitors!(nodes[1], 0);
6230 expect_pending_htlcs_forwardable!(nodes[1]);
6231 check_added_monitors!(nodes[1], 1);
6233 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6234 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6235 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6236 check_added_monitors!(nodes[0], 1);
6238 // Cache one local commitment tx as lastest
6239 let as_last_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6241 let events = nodes[0].node.get_and_clear_pending_msg_events();
6243 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6244 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6246 _ => panic!("Unexpected event"),
6249 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6250 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6252 _ => panic!("Unexpected event"),
6255 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6256 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6257 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6259 if announce_latest {
6260 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6262 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6265 check_closed_broadcast!(nodes[0], false);
6266 check_added_monitors!(nodes[0], 1);
6268 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6269 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
6270 let events = nodes[0].node.get_and_clear_pending_events();
6271 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6272 assert_eq!(events.len(), 2);
6273 let mut first_failed = false;
6274 for event in events {
6276 Event::PaymentFailed { payment_hash, .. } => {
6277 if payment_hash == payment_hash_1 {
6278 assert!(!first_failed);
6279 first_failed = true;
6281 assert_eq!(payment_hash, payment_hash_2);
6284 _ => panic!("Unexpected event"),
6290 fn test_failure_delay_dust_htlc_local_commitment() {
6291 do_test_failure_delay_dust_htlc_local_commitment(true);
6292 do_test_failure_delay_dust_htlc_local_commitment(false);
6296 fn test_no_failure_dust_htlc_local_commitment() {
6297 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6298 // prone to error, we test here that a dummy transaction don't fail them.
6300 let chanmon_cfgs = create_chanmon_cfgs(2);
6301 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6302 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6303 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6304 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6307 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6309 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6310 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6312 // We route 2 dust-HTLCs between A and B
6313 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6314 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6316 // Build a dummy invalid transaction trying to spend a commitment tx
6318 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6319 script_sig: Script::new(),
6321 witness: Vec::new(),
6325 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6329 let dummy_tx = Transaction {
6336 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6337 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6338 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6339 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6340 // We broadcast a few more block to check everything is all right
6341 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.bitcoin_hash());
6342 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6343 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6345 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6346 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6349 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6350 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6351 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6352 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6353 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6354 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6355 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6357 let chanmon_cfgs = create_chanmon_cfgs(3);
6358 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6359 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6360 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6361 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6363 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6365 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6366 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6368 let as_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6369 let bs_commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6371 // We revoked bs_commitment_tx
6373 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6374 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6377 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6378 let mut timeout_tx = Vec::new();
6380 // We fail dust-HTLC 1 by broadcast of local commitment tx
6381 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6382 check_closed_broadcast!(nodes[0], false);
6383 check_added_monitors!(nodes[0], 1);
6384 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6385 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6386 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6387 let events = nodes[0].node.get_and_clear_pending_events();
6388 assert_eq!(events.len(), 1);
6390 Event::PaymentFailed { payment_hash, .. } => {
6391 assert_eq!(payment_hash, dust_hash);
6393 _ => panic!("Unexpected event"),
6395 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6396 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6397 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6398 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6399 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6400 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6401 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6402 let events = nodes[0].node.get_and_clear_pending_events();
6403 assert_eq!(events.len(), 1);
6405 Event::PaymentFailed { payment_hash, .. } => {
6406 assert_eq!(payment_hash, non_dust_hash);
6408 _ => panic!("Unexpected event"),
6411 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6412 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6413 check_closed_broadcast!(nodes[0], false);
6414 check_added_monitors!(nodes[0], 1);
6415 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6416 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6417 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6418 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6420 let events = nodes[0].node.get_and_clear_pending_events();
6421 assert_eq!(events.len(), 1);
6423 Event::PaymentFailed { payment_hash, .. } => {
6424 assert_eq!(payment_hash, dust_hash);
6426 _ => panic!("Unexpected event"),
6428 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6429 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6430 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6431 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6432 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6433 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6434 let events = nodes[0].node.get_and_clear_pending_events();
6435 assert_eq!(events.len(), 1);
6437 Event::PaymentFailed { payment_hash, .. } => {
6438 assert_eq!(payment_hash, non_dust_hash);
6440 _ => panic!("Unexpected event"),
6443 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6445 let events = nodes[0].node.get_and_clear_pending_events();
6446 assert_eq!(events.len(), 2);
6449 Event::PaymentFailed { payment_hash, .. } => {
6450 if payment_hash == dust_hash { first = true; }
6451 else { first = false; }
6453 _ => panic!("Unexpected event"),
6456 Event::PaymentFailed { payment_hash, .. } => {
6457 if first { assert_eq!(payment_hash, non_dust_hash); }
6458 else { assert_eq!(payment_hash, dust_hash); }
6460 _ => panic!("Unexpected event"),
6467 fn test_sweep_outbound_htlc_failure_update() {
6468 do_test_sweep_outbound_htlc_failure_update(false, true);
6469 do_test_sweep_outbound_htlc_failure_update(false, false);
6470 do_test_sweep_outbound_htlc_failure_update(true, false);
6474 fn test_upfront_shutdown_script() {
6475 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6476 // enforce it at shutdown message
6478 let mut config = UserConfig::default();
6479 config.channel_options.announced_channel = true;
6480 config.peer_channel_config_limits.force_announced_channel_preference = false;
6481 config.channel_options.commit_upfront_shutdown_pubkey = false;
6482 let user_cfgs = [None, Some(config), None];
6483 let chanmon_cfgs = create_chanmon_cfgs(3);
6484 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6485 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6486 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6488 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6489 let flags = InitFeatures::supported();
6490 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6491 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6492 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6493 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6494 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
6495 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6496 assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6497 check_added_monitors!(nodes[2], 1);
6499 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6500 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6501 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6502 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6503 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6504 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6505 let events = nodes[2].node.get_and_clear_pending_msg_events();
6506 assert_eq!(events.len(), 1);
6508 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6509 _ => panic!("Unexpected event"),
6512 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6513 let mut flags_no = InitFeatures::supported();
6514 flags_no.unset_upfront_shutdown_script();
6515 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6516 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6517 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6518 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6519 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6520 let events = nodes[1].node.get_and_clear_pending_msg_events();
6521 assert_eq!(events.len(), 1);
6523 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6524 _ => panic!("Unexpected event"),
6527 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6528 // channel smoothly, opt-out is from channel initiator here
6529 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6530 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6531 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6532 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6533 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6534 let events = nodes[0].node.get_and_clear_pending_msg_events();
6535 assert_eq!(events.len(), 1);
6537 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6538 _ => panic!("Unexpected event"),
6541 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6542 //// channel smoothly
6543 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6544 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6545 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6546 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6547 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6548 let events = nodes[0].node.get_and_clear_pending_msg_events();
6549 assert_eq!(events.len(), 2);
6551 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6552 _ => panic!("Unexpected event"),
6555 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6556 _ => panic!("Unexpected event"),
6561 fn test_user_configurable_csv_delay() {
6562 // We test our channel constructors yield errors when we pass them absurd csv delay
6564 let mut low_our_to_self_config = UserConfig::default();
6565 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6566 let mut high_their_to_self_config = UserConfig::default();
6567 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6568 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6569 let chanmon_cfgs = create_chanmon_cfgs(2);
6570 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6571 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6572 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6574 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6575 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())));
6576 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) {
6578 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6579 _ => panic!("Unexpected event"),
6581 } else { assert!(false) }
6583 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6584 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6585 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6586 open_channel.to_self_delay = 200;
6587 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::supported(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
6589 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6590 _ => panic!("Unexpected event"),
6592 } else { assert!(false); }
6594 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6595 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6596 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
6597 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6598 accept_channel.to_self_delay = 200;
6599 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::supported(), &accept_channel);
6600 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6602 &ErrorAction::SendErrorMessage { ref msg } => {
6603 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6605 _ => { assert!(false); }
6607 } else { assert!(false); }
6609 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6610 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6611 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6612 open_channel.to_self_delay = 200;
6613 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::supported(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
6615 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6616 _ => panic!("Unexpected event"),
6618 } else { assert!(false); }
6622 fn test_data_loss_protect() {
6623 // We want to be sure that :
6624 // * we don't broadcast our Local Commitment Tx in case of fallen behind
6625 // * we close channel in case of detecting other being fallen behind
6626 // * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6632 let chanmon_cfgs = create_chanmon_cfgs(2);
6633 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6634 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6635 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6637 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6639 // Cache node A state before any channel update
6640 let previous_node_state = nodes[0].node.encode();
6641 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6642 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6644 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6645 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6647 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6648 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6650 // Restore node A from previous state
6651 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6652 let mut chan_monitor = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6653 let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6654 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
6655 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
6656 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger));
6657 monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), &tx_broadcaster, logger.clone(), &fee_estimator);
6659 let mut channel_monitors = HashMap::new();
6660 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
6661 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
6662 keys_manager: &keys_manager,
6663 fee_estimator: &fee_estimator,
6665 logger: Arc::clone(&logger),
6666 tx_broadcaster: &tx_broadcaster,
6667 default_config: UserConfig::default(),
6668 channel_monitors: &mut channel_monitors,
6671 nodes[0].node = &node_state_0;
6672 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
6673 nodes[0].chan_monitor = &monitor;
6674 nodes[0].chain_monitor = chain_monitor;
6676 nodes[0].block_notifier = BlockNotifier::new(nodes[0].chain_monitor.clone());
6677 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
6678 nodes[0].block_notifier.register_listener(nodes[0].node);
6680 check_added_monitors!(nodes[0], 1);
6682 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6683 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6685 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6687 // Check we update monitor following learning of per_commitment_point from B
6688 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6689 check_added_monitors!(nodes[0], 2);
6692 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6693 assert_eq!(node_txn.len(), 0);
6696 let mut reestablish_1 = Vec::with_capacity(1);
6697 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6698 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6699 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6700 reestablish_1.push(msg.clone());
6701 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6702 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
6704 &ErrorAction::SendErrorMessage { ref msg } => {
6705 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");
6707 _ => panic!("Unexpected event!"),
6710 panic!("Unexpected event")
6714 // Check we close channel detecting A is fallen-behind
6715 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6716 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
6717 check_added_monitors!(nodes[1], 1);
6720 // Check A is able to claim to_remote output
6721 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6722 assert_eq!(node_txn.len(), 1);
6723 check_spends!(node_txn[0], chan.3);
6724 assert_eq!(node_txn[0].output.len(), 2);
6725 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6726 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 1);
6727 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6728 assert_eq!(spend_txn.len(), 1);
6729 check_spends!(spend_txn[0], node_txn[0]);
6733 fn test_check_htlc_underpaying() {
6734 // Send payment through A -> B but A is maliciously
6735 // sending a probe payment (i.e less than expected value0
6736 // to B, B should refuse payment.
6738 let chanmon_cfgs = create_chanmon_cfgs(2);
6739 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6740 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6741 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6743 // Create some initial channels
6744 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6746 let (payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
6748 // Node 3 is expecting payment of 100_000 but receive 10_000,
6749 // fail htlc like we didn't know the preimage.
6750 nodes[1].node.claim_funds(payment_preimage, 100_000);
6751 nodes[1].node.process_pending_htlc_forwards();
6753 let events = nodes[1].node.get_and_clear_pending_msg_events();
6754 assert_eq!(events.len(), 1);
6755 let (update_fail_htlc, commitment_signed) = match events[0] {
6756 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 } } => {
6757 assert!(update_add_htlcs.is_empty());
6758 assert!(update_fulfill_htlcs.is_empty());
6759 assert_eq!(update_fail_htlcs.len(), 1);
6760 assert!(update_fail_malformed_htlcs.is_empty());
6761 assert!(update_fee.is_none());
6762 (update_fail_htlcs[0].clone(), commitment_signed)
6764 _ => panic!("Unexpected event"),
6766 check_added_monitors!(nodes[1], 1);
6768 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6769 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6771 let events = nodes[0].node.get_and_clear_pending_events();
6772 assert_eq!(events.len(), 1);
6773 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
6774 assert_eq!(*rejected_by_dest, true);
6775 assert_eq!(error_code.unwrap(), 0x4000|15);
6777 panic!("Unexpected event");
6779 nodes[1].node.get_and_clear_pending_events();
6783 fn test_announce_disable_channels() {
6784 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
6785 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6787 let chanmon_cfgs = create_chanmon_cfgs(2);
6788 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6789 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6790 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6792 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6793 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6794 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6797 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6798 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6800 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
6801 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
6802 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6803 assert_eq!(msg_events.len(), 3);
6804 for e in msg_events {
6806 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6807 let short_id = msg.contents.short_channel_id;
6808 // Check generated channel_update match list in PendingChannelUpdate
6809 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
6810 panic!("Generated ChannelUpdate for wrong chan!");
6813 _ => panic!("Unexpected event"),
6817 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6818 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6819 assert_eq!(reestablish_1.len(), 3);
6820 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6821 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6822 assert_eq!(reestablish_2.len(), 3);
6824 // Reestablish chan_1
6825 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6826 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6827 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6828 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6829 // Reestablish chan_2
6830 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
6831 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6832 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
6833 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6834 // Reestablish chan_3
6835 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
6836 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6837 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
6838 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6840 nodes[0].node.timer_chan_freshness_every_min();
6841 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6845 fn test_bump_penalty_txn_on_revoked_commitment() {
6846 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
6847 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
6849 let chanmon_cfgs = create_chanmon_cfgs(2);
6850 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6851 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6852 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6854 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6855 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6856 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30).unwrap();
6857 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
6859 let revoked_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6860 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
6861 assert_eq!(revoked_txn[0].output.len(), 4);
6862 assert_eq!(revoked_txn[0].input.len(), 1);
6863 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
6864 let revoked_txid = revoked_txn[0].txid();
6866 let mut penalty_sum = 0;
6867 for outp in revoked_txn[0].output.iter() {
6868 if outp.script_pubkey.is_v0_p2wsh() {
6869 penalty_sum += outp.value;
6873 // Connect blocks to change height_timer range to see if we use right soonest_timelock
6874 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
6876 // Actually revoke tx by claiming a HTLC
6877 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6878 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6879 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
6880 check_added_monitors!(nodes[1], 1);
6882 // One or more justice tx should have been broadcast, check it
6886 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6887 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
6888 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6889 assert_eq!(node_txn[0].output.len(), 1);
6890 check_spends!(node_txn[0], revoked_txn[0]);
6891 let fee_1 = penalty_sum - node_txn[0].output[0].value;
6892 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
6893 penalty_1 = node_txn[0].txid();
6897 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
6898 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.bitcoin_hash());
6899 let mut penalty_2 = penalty_1;
6900 let mut feerate_2 = 0;
6902 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6903 assert_eq!(node_txn.len(), 1);
6904 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6905 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6906 assert_eq!(node_txn[0].output.len(), 1);
6907 check_spends!(node_txn[0], revoked_txn[0]);
6908 penalty_2 = node_txn[0].txid();
6909 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6910 assert_ne!(penalty_2, penalty_1);
6911 let fee_2 = penalty_sum - node_txn[0].output[0].value;
6912 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
6913 // Verify 25% bump heuristic
6914 assert!(feerate_2 * 100 >= feerate_1 * 125);
6918 assert_ne!(feerate_2, 0);
6920 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
6921 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
6923 let mut feerate_3 = 0;
6925 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6926 assert_eq!(node_txn.len(), 1);
6927 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6928 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6929 assert_eq!(node_txn[0].output.len(), 1);
6930 check_spends!(node_txn[0], revoked_txn[0]);
6931 penalty_3 = node_txn[0].txid();
6932 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6933 assert_ne!(penalty_3, penalty_2);
6934 let fee_3 = penalty_sum - node_txn[0].output[0].value;
6935 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
6936 // Verify 25% bump heuristic
6937 assert!(feerate_3 * 100 >= feerate_2 * 125);
6941 assert_ne!(feerate_3, 0);
6943 nodes[1].node.get_and_clear_pending_events();
6944 nodes[1].node.get_and_clear_pending_msg_events();
6948 fn test_bump_penalty_txn_on_revoked_htlcs() {
6949 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
6950 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
6952 let chanmon_cfgs = create_chanmon_cfgs(2);
6953 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6954 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6955 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6957 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6958 // Lock HTLC in both directions
6959 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
6960 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
6962 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
6963 assert_eq!(revoked_local_txn[0].input.len(), 1);
6964 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
6966 // Revoke local commitment tx
6967 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6969 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6970 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
6971 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6972 check_closed_broadcast!(nodes[1], false);
6973 check_added_monitors!(nodes[1], 1);
6975 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6976 assert_eq!(revoked_htlc_txn.len(), 6);
6977 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6978 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
6979 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
6980 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
6981 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6982 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
6983 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6984 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
6985 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
6986 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
6987 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6988 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
6991 // Broadcast set of revoked txn on A
6992 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
6993 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6994 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);
6999 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7000 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7001 // Verify claim tx are spending revoked HTLC txn
7002 assert_eq!(node_txn[4].input.len(), 2);
7003 assert_eq!(node_txn[4].output.len(), 1);
7004 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7005 first = node_txn[4].txid();
7006 // Store both feerates for later comparison
7007 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7008 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7009 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7013 // Connect three more block to see if bumped penalty are issued for HTLC txn
7014 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7015 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7017 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7018 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7020 check_spends!(node_txn[0], revoked_local_txn[0]);
7021 check_spends!(node_txn[1], revoked_local_txn[0]);
7026 // Few more blocks to confirm penalty txn
7027 let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7028 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7029 let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7031 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7032 assert_eq!(node_txn.len(), 1);
7034 assert_eq!(node_txn[0].input.len(), 2);
7035 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7036 // Verify bumped tx is different and 25% bump heuristic
7037 assert_ne!(first, node_txn[0].txid());
7038 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7039 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7040 assert!(feerate_2 * 100 > feerate_1 * 125);
7041 let txn = vec![node_txn[0].clone()];
7045 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7046 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7047 nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7048 connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7050 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7051 // We verify than no new transaction has been broadcast because previously
7052 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7053 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7054 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7055 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7056 // up bumped justice generation.
7057 assert_eq!(node_txn.len(), 0);
7060 check_closed_broadcast!(nodes[0], false);
7061 check_added_monitors!(nodes[0], 1);
7065 fn test_bump_penalty_txn_on_remote_commitment() {
7066 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7067 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7070 // Provide preimage for one
7071 // Check aggregation
7073 let chanmon_cfgs = create_chanmon_cfgs(2);
7074 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7075 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7076 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7078 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7079 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7080 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7082 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7083 let remote_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
7084 assert_eq!(remote_txn[0].output.len(), 4);
7085 assert_eq!(remote_txn[0].input.len(), 1);
7086 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7088 // Claim a HTLC without revocation (provide B monitor with preimage)
7089 nodes[1].node.claim_funds(payment_preimage, 3_000_000);
7090 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7091 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7092 check_added_monitors!(nodes[1], 2);
7094 // One or more claim tx should have been broadcast, check it
7097 let feerate_timeout;
7098 let feerate_preimage;
7100 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7101 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7102 assert_eq!(node_txn[0].input.len(), 1);
7103 assert_eq!(node_txn[1].input.len(), 1);
7104 check_spends!(node_txn[0], remote_txn[0]);
7105 check_spends!(node_txn[1], remote_txn[0]);
7106 check_spends!(node_txn[2], chan.3);
7107 check_spends!(node_txn[3], node_txn[2]);
7108 check_spends!(node_txn[4], node_txn[2]);
7109 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7110 timeout = node_txn[0].txid();
7111 let index = node_txn[0].input[0].previous_output.vout;
7112 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7113 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7115 preimage = node_txn[1].txid();
7116 let index = node_txn[1].input[0].previous_output.vout;
7117 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7118 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7120 timeout = node_txn[1].txid();
7121 let index = node_txn[1].input[0].previous_output.vout;
7122 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7123 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7125 preimage = node_txn[0].txid();
7126 let index = node_txn[0].input[0].previous_output.vout;
7127 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7128 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7132 assert_ne!(feerate_timeout, 0);
7133 assert_ne!(feerate_preimage, 0);
7135 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7136 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.bitcoin_hash());
7138 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7139 assert_eq!(node_txn.len(), 2);
7140 assert_eq!(node_txn[0].input.len(), 1);
7141 assert_eq!(node_txn[1].input.len(), 1);
7142 check_spends!(node_txn[0], remote_txn[0]);
7143 check_spends!(node_txn[1], remote_txn[0]);
7144 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7145 let index = node_txn[0].input[0].previous_output.vout;
7146 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7147 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7148 assert!(new_feerate * 100 > feerate_timeout * 125);
7149 assert_ne!(timeout, node_txn[0].txid());
7151 let index = node_txn[1].input[0].previous_output.vout;
7152 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7153 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7154 assert!(new_feerate * 100 > feerate_preimage * 125);
7155 assert_ne!(preimage, node_txn[1].txid());
7157 let index = node_txn[1].input[0].previous_output.vout;
7158 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7159 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7160 assert!(new_feerate * 100 > feerate_timeout * 125);
7161 assert_ne!(timeout, node_txn[1].txid());
7163 let index = node_txn[0].input[0].previous_output.vout;
7164 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7165 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7166 assert!(new_feerate * 100 > feerate_preimage * 125);
7167 assert_ne!(preimage, node_txn[0].txid());
7172 nodes[1].node.get_and_clear_pending_events();
7173 nodes[1].node.get_and_clear_pending_msg_events();
7177 fn test_set_outpoints_partial_claiming() {
7178 // - remote party claim tx, new bump tx
7179 // - disconnect remote claiming tx, new bump
7180 // - disconnect tx, see no tx anymore
7181 let chanmon_cfgs = create_chanmon_cfgs(2);
7182 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7183 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7184 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7186 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7187 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7188 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7190 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7191 let remote_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
7192 assert_eq!(remote_txn.len(), 3);
7193 assert_eq!(remote_txn[0].output.len(), 4);
7194 assert_eq!(remote_txn[0].input.len(), 1);
7195 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7196 check_spends!(remote_txn[1], remote_txn[0]);
7197 check_spends!(remote_txn[2], remote_txn[0]);
7199 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7200 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7201 // Provide node A with both preimage
7202 nodes[0].node.claim_funds(payment_preimage_1, 3_000_000);
7203 nodes[0].node.claim_funds(payment_preimage_2, 3_000_000);
7204 check_added_monitors!(nodes[0], 2);
7205 nodes[0].node.get_and_clear_pending_events();
7206 nodes[0].node.get_and_clear_pending_msg_events();
7208 // Connect blocks on node A commitment transaction
7209 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7210 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7211 check_closed_broadcast!(nodes[0], false);
7212 check_added_monitors!(nodes[0], 1);
7213 // Verify node A broadcast tx claiming both HTLCs
7215 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7216 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7217 assert_eq!(node_txn.len(), 4);
7218 check_spends!(node_txn[0], remote_txn[0]);
7219 check_spends!(node_txn[1], chan.3);
7220 check_spends!(node_txn[2], node_txn[1]);
7221 check_spends!(node_txn[3], node_txn[1]);
7222 assert_eq!(node_txn[0].input.len(), 2);
7226 // Connect blocks on node B
7227 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7228 check_closed_broadcast!(nodes[1], false);
7229 check_added_monitors!(nodes[1], 1);
7230 // Verify node B broadcast 2 HTLC-timeout txn
7231 let partial_claim_tx = {
7232 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7233 assert_eq!(node_txn.len(), 3);
7234 check_spends!(node_txn[1], node_txn[0]);
7235 check_spends!(node_txn[2], node_txn[0]);
7236 assert_eq!(node_txn[1].input.len(), 1);
7237 assert_eq!(node_txn[2].input.len(), 1);
7241 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7242 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7243 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7245 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7246 assert_eq!(node_txn.len(), 1);
7247 check_spends!(node_txn[0], remote_txn[0]);
7248 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7251 nodes[0].node.get_and_clear_pending_msg_events();
7253 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7254 nodes[0].block_notifier.block_disconnected(&header, 102);
7256 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7257 assert_eq!(node_txn.len(), 1);
7258 check_spends!(node_txn[0], remote_txn[0]);
7259 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7263 //// Disconnect one more block and then reconnect multiple no transaction should be generated
7264 nodes[0].block_notifier.block_disconnected(&header, 101);
7265 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7267 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7268 assert_eq!(node_txn.len(), 0);
7274 fn test_counterparty_raa_skip_no_crash() {
7275 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7276 // commitment transaction, we would have happily carried on and provided them the next
7277 // commitment transaction based on one RAA forward. This would probably eventually have led to
7278 // channel closure, but it would not have resulted in funds loss. Still, our
7279 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7280 // check simply that the channel is closed in response to such an RAA, but don't check whether
7281 // we decide to punish our counterparty for revoking their funds (as we don't currently
7283 let chanmon_cfgs = create_chanmon_cfgs(2);
7284 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7285 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7286 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7287 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).2;
7289 let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7290 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7291 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7292 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7293 let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7295 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7296 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7297 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7298 check_added_monitors!(nodes[1], 1);
7302 fn test_bump_txn_sanitize_tracking_maps() {
7303 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7304 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7306 let chanmon_cfgs = create_chanmon_cfgs(2);
7307 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7308 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7309 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7311 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7312 // Lock HTLC in both directions
7313 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7314 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7316 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get_mut(&chan.2).unwrap().channel_monitor().get_latest_local_commitment_txn();
7317 assert_eq!(revoked_local_txn[0].input.len(), 1);
7318 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7320 // Revoke local commitment tx
7321 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7323 // Broadcast set of revoked txn on A
7324 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7325 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7326 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7327 check_closed_broadcast!(nodes[0], false);
7328 check_added_monitors!(nodes[0], 1);
7330 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7331 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7332 check_spends!(node_txn[0], revoked_local_txn[0]);
7333 check_spends!(node_txn[1], revoked_local_txn[0]);
7334 check_spends!(node_txn[2], revoked_local_txn[0]);
7335 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7339 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7340 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7341 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.bitcoin_hash());
7343 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7344 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7345 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7346 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7352 fn test_override_channel_config() {
7353 let chanmon_cfgs = create_chanmon_cfgs(2);
7354 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7355 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7356 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7358 // Node0 initiates a channel to node1 using the override config.
7359 let mut override_config = UserConfig::default();
7360 override_config.own_channel_config.our_to_self_delay = 200;
7362 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7364 // Assert the channel created by node0 is using the override config.
7365 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7366 assert_eq!(res.channel_flags, 0);
7367 assert_eq!(res.to_self_delay, 200);
7371 fn test_override_0msat_htlc_minimum() {
7372 let mut zero_config = UserConfig::default();
7373 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7374 let chanmon_cfgs = create_chanmon_cfgs(2);
7375 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7376 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7377 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7379 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7380 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7381 assert_eq!(res.htlc_minimum_msat, 1);
7383 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &res);
7384 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7385 assert_eq!(res.htlc_minimum_msat, 1);