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 commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
585 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
586 let num_htlcs = commitment_tx.output.len() - 2;
587 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
588 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
589 actual_fee = channel_value - actual_fee;
590 assert_eq!(total_fee, actual_fee);
593 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
594 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
595 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
596 check_added_monitors!(nodes[0], 1);
598 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
600 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
602 //While producing the commitment_signed response after handling a received update_fee request the
603 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
604 //Should produce and error.
605 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
606 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
607 check_added_monitors!(nodes[1], 1);
608 check_closed_broadcast!(nodes[1], true);
612 fn test_update_fee_with_fundee_update_add_htlc() {
613 let chanmon_cfgs = create_chanmon_cfgs(2);
614 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
615 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
616 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
617 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
618 let channel_id = chan.2;
621 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
623 let feerate = get_feerate!(nodes[0], channel_id);
624 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
625 check_added_monitors!(nodes[0], 1);
627 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
628 assert_eq!(events_0.len(), 1);
629 let (update_msg, commitment_signed) = match events_0[0] {
630 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 } } => {
631 (update_fee.as_ref(), commitment_signed)
633 _ => panic!("Unexpected event"),
635 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
636 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
637 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
638 check_added_monitors!(nodes[1], 1);
640 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
642 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
644 // nothing happens since node[1] is in AwaitingRemoteRevoke
645 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
647 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
648 assert_eq!(added_monitors.len(), 0);
649 added_monitors.clear();
651 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
652 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
653 // node[1] has nothing to do
655 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
656 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
657 check_added_monitors!(nodes[0], 1);
659 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
660 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
661 // No commitment_signed so get_event_msg's assert(len == 1) passes
662 check_added_monitors!(nodes[0], 1);
663 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
664 check_added_monitors!(nodes[1], 1);
665 // AwaitingRemoteRevoke ends here
667 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
668 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
669 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
670 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
671 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
672 assert_eq!(commitment_update.update_fee.is_none(), true);
674 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
675 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
676 check_added_monitors!(nodes[0], 1);
677 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
679 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
680 check_added_monitors!(nodes[1], 1);
681 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
683 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
684 check_added_monitors!(nodes[1], 1);
685 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
686 // No commitment_signed so get_event_msg's assert(len == 1) passes
688 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
689 check_added_monitors!(nodes[0], 1);
690 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
692 expect_pending_htlcs_forwardable!(nodes[0]);
694 let events = nodes[0].node.get_and_clear_pending_events();
695 assert_eq!(events.len(), 1);
697 Event::PaymentReceived { .. } => { },
698 _ => panic!("Unexpected event"),
701 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
703 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
704 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
705 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
709 fn test_update_fee() {
710 let chanmon_cfgs = create_chanmon_cfgs(2);
711 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
712 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
713 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
714 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
715 let channel_id = chan.2;
718 // (1) update_fee/commitment_signed ->
719 // <- (2) revoke_and_ack
720 // .- send (3) commitment_signed
721 // (4) update_fee/commitment_signed ->
722 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
723 // <- (3) commitment_signed delivered
724 // send (6) revoke_and_ack -.
725 // <- (5) deliver revoke_and_ack
726 // (6) deliver revoke_and_ack ->
727 // .- send (7) commitment_signed in response to (4)
728 // <- (7) deliver commitment_signed
731 // Create and deliver (1)...
732 let feerate = get_feerate!(nodes[0], channel_id);
733 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
734 check_added_monitors!(nodes[0], 1);
736 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
737 assert_eq!(events_0.len(), 1);
738 let (update_msg, commitment_signed) = match events_0[0] {
739 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 } } => {
740 (update_fee.as_ref(), commitment_signed)
742 _ => panic!("Unexpected event"),
744 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
746 // Generate (2) and (3):
747 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
748 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
749 check_added_monitors!(nodes[1], 1);
752 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
753 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
754 check_added_monitors!(nodes[0], 1);
756 // Create and deliver (4)...
757 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
758 check_added_monitors!(nodes[0], 1);
759 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
760 assert_eq!(events_0.len(), 1);
761 let (update_msg, commitment_signed) = match events_0[0] {
762 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 } } => {
763 (update_fee.as_ref(), commitment_signed)
765 _ => panic!("Unexpected event"),
768 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
769 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
770 check_added_monitors!(nodes[1], 1);
772 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
773 // No commitment_signed so get_event_msg's assert(len == 1) passes
775 // Handle (3), creating (6):
776 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
777 check_added_monitors!(nodes[0], 1);
778 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
779 // No commitment_signed so get_event_msg's assert(len == 1) passes
782 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
783 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
784 check_added_monitors!(nodes[0], 1);
786 // Deliver (6), creating (7):
787 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
788 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
789 assert!(commitment_update.update_add_htlcs.is_empty());
790 assert!(commitment_update.update_fulfill_htlcs.is_empty());
791 assert!(commitment_update.update_fail_htlcs.is_empty());
792 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
793 assert!(commitment_update.update_fee.is_none());
794 check_added_monitors!(nodes[1], 1);
797 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
798 check_added_monitors!(nodes[0], 1);
799 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
800 // No commitment_signed so get_event_msg's assert(len == 1) passes
802 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
803 check_added_monitors!(nodes[1], 1);
804 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
806 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
807 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
808 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
812 fn pre_funding_lock_shutdown_test() {
813 // Test sending a shutdown prior to funding_locked after funding generation
814 let chanmon_cfgs = create_chanmon_cfgs(2);
815 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
816 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
817 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
818 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::supported(), InitFeatures::supported());
819 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
820 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
821 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
823 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
824 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
825 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
826 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
827 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
829 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
830 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
831 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
832 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
833 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
834 assert!(node_0_none.is_none());
836 assert!(nodes[0].node.list_channels().is_empty());
837 assert!(nodes[1].node.list_channels().is_empty());
841 fn updates_shutdown_wait() {
842 // Test sending a shutdown with outstanding updates pending
843 let chanmon_cfgs = create_chanmon_cfgs(3);
844 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
845 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
846 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
847 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
848 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
849 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
850 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
852 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
854 nodes[0].node.close_channel(&chan_1.2).unwrap();
855 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
856 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
857 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
858 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
860 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
861 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
863 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
864 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
865 else { panic!("New sends should fail!") };
866 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
867 else { panic!("New sends should fail!") };
869 assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
870 check_added_monitors!(nodes[2], 1);
871 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
872 assert!(updates.update_add_htlcs.is_empty());
873 assert!(updates.update_fail_htlcs.is_empty());
874 assert!(updates.update_fail_malformed_htlcs.is_empty());
875 assert!(updates.update_fee.is_none());
876 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
877 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
878 check_added_monitors!(nodes[1], 1);
879 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
880 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
882 assert!(updates_2.update_add_htlcs.is_empty());
883 assert!(updates_2.update_fail_htlcs.is_empty());
884 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
885 assert!(updates_2.update_fee.is_none());
886 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
887 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
888 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
890 let events = nodes[0].node.get_and_clear_pending_events();
891 assert_eq!(events.len(), 1);
893 Event::PaymentSent { ref payment_preimage } => {
894 assert_eq!(our_payment_preimage, *payment_preimage);
896 _ => panic!("Unexpected event"),
899 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
900 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
901 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
902 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
903 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
904 assert!(node_0_none.is_none());
906 assert!(nodes[0].node.list_channels().is_empty());
908 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
909 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
910 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
911 assert!(nodes[1].node.list_channels().is_empty());
912 assert!(nodes[2].node.list_channels().is_empty());
916 fn htlc_fail_async_shutdown() {
917 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
918 let chanmon_cfgs = create_chanmon_cfgs(3);
919 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
920 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
921 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
922 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
923 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
925 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
926 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
927 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
928 check_added_monitors!(nodes[0], 1);
929 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
930 assert_eq!(updates.update_add_htlcs.len(), 1);
931 assert!(updates.update_fulfill_htlcs.is_empty());
932 assert!(updates.update_fail_htlcs.is_empty());
933 assert!(updates.update_fail_malformed_htlcs.is_empty());
934 assert!(updates.update_fee.is_none());
936 nodes[1].node.close_channel(&chan_1.2).unwrap();
937 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
938 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
939 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
941 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
942 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
943 check_added_monitors!(nodes[1], 1);
944 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
945 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
947 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
948 assert!(updates_2.update_add_htlcs.is_empty());
949 assert!(updates_2.update_fulfill_htlcs.is_empty());
950 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
951 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
952 assert!(updates_2.update_fee.is_none());
954 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
955 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
957 let events = nodes[0].node.get_and_clear_pending_events();
958 assert_eq!(events.len(), 1);
960 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
961 assert_eq!(our_payment_hash, *payment_hash);
962 assert!(!rejected_by_dest);
964 _ => panic!("Unexpected event"),
967 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
968 assert_eq!(msg_events.len(), 2);
969 let node_0_closing_signed = match msg_events[0] {
970 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
971 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
974 _ => panic!("Unexpected event"),
976 match msg_events[1] {
977 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
978 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
980 _ => panic!("Unexpected event"),
983 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
984 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
985 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
986 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
987 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
988 assert!(node_0_none.is_none());
990 assert!(nodes[0].node.list_channels().is_empty());
992 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
993 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
994 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
995 assert!(nodes[1].node.list_channels().is_empty());
996 assert!(nodes[2].node.list_channels().is_empty());
999 fn do_test_shutdown_rebroadcast(recv_count: u8) {
1000 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
1001 // messages delivered prior to disconnect
1002 let chanmon_cfgs = create_chanmon_cfgs(3);
1003 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1004 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1005 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1006 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1007 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1009 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1011 nodes[1].node.close_channel(&chan_1.2).unwrap();
1012 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1014 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1015 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1017 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1021 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1022 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1024 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1025 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1026 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1027 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1029 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1030 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1031 assert!(node_1_shutdown == node_1_2nd_shutdown);
1033 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1034 let node_0_2nd_shutdown = if recv_count > 0 {
1035 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1036 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1039 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1040 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1041 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1043 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1045 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1046 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1048 assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
1049 check_added_monitors!(nodes[2], 1);
1050 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1051 assert!(updates.update_add_htlcs.is_empty());
1052 assert!(updates.update_fail_htlcs.is_empty());
1053 assert!(updates.update_fail_malformed_htlcs.is_empty());
1054 assert!(updates.update_fee.is_none());
1055 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1056 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1057 check_added_monitors!(nodes[1], 1);
1058 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1059 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1061 assert!(updates_2.update_add_htlcs.is_empty());
1062 assert!(updates_2.update_fail_htlcs.is_empty());
1063 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1064 assert!(updates_2.update_fee.is_none());
1065 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1066 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1067 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1069 let events = nodes[0].node.get_and_clear_pending_events();
1070 assert_eq!(events.len(), 1);
1072 Event::PaymentSent { ref payment_preimage } => {
1073 assert_eq!(our_payment_preimage, *payment_preimage);
1075 _ => panic!("Unexpected event"),
1078 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1080 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1081 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1082 assert!(node_1_closing_signed.is_some());
1085 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1086 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1088 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1089 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1090 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1091 if recv_count == 0 {
1092 // If all closing_signeds weren't delivered we can just resume where we left off...
1093 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1095 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1096 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1097 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1099 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1100 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1101 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1103 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1104 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1106 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1107 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1108 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1110 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1111 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1112 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1113 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1114 assert!(node_0_none.is_none());
1116 // If one node, however, received + responded with an identical closing_signed we end
1117 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1118 // There isn't really anything better we can do simply, but in the future we might
1119 // explore storing a set of recently-closed channels that got disconnected during
1120 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1121 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1123 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1125 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1126 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1127 assert_eq!(msg_events.len(), 1);
1128 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1130 &ErrorAction::SendErrorMessage { ref msg } => {
1131 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1132 assert_eq!(msg.channel_id, chan_1.2);
1134 _ => panic!("Unexpected event!"),
1136 } else { panic!("Needed SendErrorMessage close"); }
1138 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1139 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1140 // closing_signed so we do it ourselves
1141 check_closed_broadcast!(nodes[0], false);
1142 check_added_monitors!(nodes[0], 1);
1145 assert!(nodes[0].node.list_channels().is_empty());
1147 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1148 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1149 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1150 assert!(nodes[1].node.list_channels().is_empty());
1151 assert!(nodes[2].node.list_channels().is_empty());
1155 fn test_shutdown_rebroadcast() {
1156 do_test_shutdown_rebroadcast(0);
1157 do_test_shutdown_rebroadcast(1);
1158 do_test_shutdown_rebroadcast(2);
1162 fn fake_network_test() {
1163 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1164 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1165 let chanmon_cfgs = create_chanmon_cfgs(4);
1166 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1167 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1168 let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1170 // Create some initial channels
1171 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1172 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1173 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1175 // Rebalance the network a bit by relaying one payment through all the channels...
1176 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1177 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1178 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1179 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1181 // Send some more payments
1182 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1183 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1184 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1186 // Test failure packets
1187 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1188 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1190 // Add a new channel that skips 3
1191 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1193 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1194 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1195 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1196 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1197 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1198 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1199 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1201 // Do some rebalance loop payments, simultaneously
1202 let mut hops = Vec::with_capacity(3);
1203 hops.push(RouteHop {
1204 pubkey: nodes[2].node.get_our_node_id(),
1205 node_features: NodeFeatures::empty(),
1206 short_channel_id: chan_2.0.contents.short_channel_id,
1207 channel_features: ChannelFeatures::empty(),
1209 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1211 hops.push(RouteHop {
1212 pubkey: nodes[3].node.get_our_node_id(),
1213 node_features: NodeFeatures::empty(),
1214 short_channel_id: chan_3.0.contents.short_channel_id,
1215 channel_features: ChannelFeatures::empty(),
1217 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1219 hops.push(RouteHop {
1220 pubkey: nodes[1].node.get_our_node_id(),
1221 node_features: NodeFeatures::empty(),
1222 short_channel_id: chan_4.0.contents.short_channel_id,
1223 channel_features: ChannelFeatures::empty(),
1225 cltv_expiry_delta: TEST_FINAL_CLTV,
1227 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;
1228 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;
1229 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1231 let mut hops = Vec::with_capacity(3);
1232 hops.push(RouteHop {
1233 pubkey: nodes[3].node.get_our_node_id(),
1234 node_features: NodeFeatures::empty(),
1235 short_channel_id: chan_4.0.contents.short_channel_id,
1236 channel_features: ChannelFeatures::empty(),
1238 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1240 hops.push(RouteHop {
1241 pubkey: nodes[2].node.get_our_node_id(),
1242 node_features: NodeFeatures::empty(),
1243 short_channel_id: chan_3.0.contents.short_channel_id,
1244 channel_features: ChannelFeatures::empty(),
1246 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1248 hops.push(RouteHop {
1249 pubkey: nodes[1].node.get_our_node_id(),
1250 node_features: NodeFeatures::empty(),
1251 short_channel_id: chan_2.0.contents.short_channel_id,
1252 channel_features: ChannelFeatures::empty(),
1254 cltv_expiry_delta: TEST_FINAL_CLTV,
1256 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;
1257 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;
1258 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1260 // Claim the rebalances...
1261 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1262 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1264 // Add a duplicate new channel from 2 to 4
1265 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1267 // Send some payments across both channels
1268 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1269 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1270 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1273 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1274 let events = nodes[0].node.get_and_clear_pending_msg_events();
1275 assert_eq!(events.len(), 0);
1276 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);
1278 //TODO: Test that routes work again here as we've been notified that the channel is full
1280 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1281 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1282 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1284 // Close down the channels...
1285 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1286 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1287 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1288 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1289 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1293 fn holding_cell_htlc_counting() {
1294 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1295 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1296 // commitment dance rounds.
1297 let chanmon_cfgs = create_chanmon_cfgs(3);
1298 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1299 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1300 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1301 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1302 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1304 let mut payments = Vec::new();
1305 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1306 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1307 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1308 nodes[1].node.send_payment(route, payment_hash).unwrap();
1309 payments.push((payment_preimage, payment_hash));
1311 check_added_monitors!(nodes[1], 1);
1313 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1314 assert_eq!(events.len(), 1);
1315 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1316 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1318 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1319 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1321 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1322 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1323 if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() {
1324 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
1325 } else { panic!("Unexpected event"); }
1326 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1327 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1329 // This should also be true if we try to forward a payment.
1330 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1331 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1332 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
1333 check_added_monitors!(nodes[0], 1);
1335 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1336 assert_eq!(events.len(), 1);
1337 let payment_event = SendEvent::from_event(events.pop().unwrap());
1338 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1340 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1341 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1342 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1343 // fails), the second will process the resulting failure and fail the HTLC backward.
1344 expect_pending_htlcs_forwardable!(nodes[1]);
1345 expect_pending_htlcs_forwardable!(nodes[1]);
1346 check_added_monitors!(nodes[1], 1);
1348 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1349 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1350 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1352 let events = nodes[0].node.get_and_clear_pending_msg_events();
1353 assert_eq!(events.len(), 1);
1355 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1356 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1358 _ => panic!("Unexpected event"),
1361 let events = nodes[0].node.get_and_clear_pending_events();
1362 assert_eq!(events.len(), 1);
1364 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1365 assert_eq!(payment_hash, payment_hash_2);
1366 assert!(!rejected_by_dest);
1368 _ => panic!("Unexpected event"),
1371 // Now forward all the pending HTLCs and claim them back
1372 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1373 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1374 check_added_monitors!(nodes[2], 1);
1376 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1377 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1378 check_added_monitors!(nodes[1], 1);
1379 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1381 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1382 check_added_monitors!(nodes[1], 1);
1383 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1385 for ref update in as_updates.update_add_htlcs.iter() {
1386 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1388 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1389 check_added_monitors!(nodes[2], 1);
1390 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1391 check_added_monitors!(nodes[2], 1);
1392 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1394 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1395 check_added_monitors!(nodes[1], 1);
1396 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1397 check_added_monitors!(nodes[1], 1);
1398 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1400 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1401 check_added_monitors!(nodes[2], 1);
1403 expect_pending_htlcs_forwardable!(nodes[2]);
1405 let events = nodes[2].node.get_and_clear_pending_events();
1406 assert_eq!(events.len(), payments.len());
1407 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1409 &Event::PaymentReceived { ref payment_hash, .. } => {
1410 assert_eq!(*payment_hash, *hash);
1412 _ => panic!("Unexpected event"),
1416 for (preimage, _) in payments.drain(..) {
1417 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1420 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1424 fn duplicate_htlc_test() {
1425 // Test that we accept duplicate payment_hash HTLCs across the network and that
1426 // claiming/failing them are all separate and don't affect each other
1427 let chanmon_cfgs = create_chanmon_cfgs(6);
1428 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1429 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1430 let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1432 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1433 create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::supported(), InitFeatures::supported());
1434 create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::supported(), InitFeatures::supported());
1435 create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1436 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
1437 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
1439 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1441 *nodes[0].network_payment_count.borrow_mut() -= 1;
1442 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1444 *nodes[0].network_payment_count.borrow_mut() -= 1;
1445 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1447 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1448 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1449 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1453 fn test_duplicate_htlc_different_direction_onchain() {
1454 // Test that ChannelMonitor doesn't generate 2 preimage txn
1455 // when we have 2 HTLCs with same preimage that go across a node
1456 // in opposite directions.
1457 let chanmon_cfgs = create_chanmon_cfgs(2);
1458 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1459 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1460 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1462 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1465 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1467 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1469 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV).unwrap();
1470 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1472 // Provide preimage to node 0 by claiming payment
1473 nodes[0].node.claim_funds(payment_preimage, 800_000);
1474 check_added_monitors!(nodes[0], 1);
1476 // Broadcast node 1 commitment txn
1477 let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1479 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1480 let mut has_both_htlcs = 0; // check htlcs match ones committed
1481 for outp in remote_txn[0].output.iter() {
1482 if outp.value == 800_000 / 1000 {
1483 has_both_htlcs += 1;
1484 } else if outp.value == 900_000 / 1000 {
1485 has_both_htlcs += 1;
1488 assert_eq!(has_both_htlcs, 2);
1490 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1491 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1492 check_added_monitors!(nodes[0], 1);
1494 // Check we only broadcast 1 timeout tx
1495 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1496 let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1497 assert_eq!(claim_txn.len(), 5);
1498 check_spends!(claim_txn[2], chan_1.3);
1499 check_spends!(claim_txn[3], claim_txn[2]);
1500 assert_eq!(htlc_pair.0.input.len(), 1);
1501 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1502 check_spends!(htlc_pair.0, remote_txn[0]);
1503 assert_eq!(htlc_pair.1.input.len(), 1);
1504 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1505 check_spends!(htlc_pair.1, remote_txn[0]);
1507 let events = nodes[0].node.get_and_clear_pending_msg_events();
1508 assert_eq!(events.len(), 2);
1511 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1512 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fulfill_htlcs, ref update_fail_htlcs, ref update_fail_malformed_htlcs, .. } } => {
1513 assert!(update_add_htlcs.is_empty());
1514 assert!(update_fail_htlcs.is_empty());
1515 assert_eq!(update_fulfill_htlcs.len(), 1);
1516 assert!(update_fail_malformed_htlcs.is_empty());
1517 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1519 _ => panic!("Unexpected event"),
1524 fn do_channel_reserve_test(test_recv: bool) {
1526 let chanmon_cfgs = create_chanmon_cfgs(3);
1527 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1528 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1529 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1530 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::supported(), InitFeatures::supported());
1531 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::supported(), InitFeatures::supported());
1533 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1534 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1536 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1537 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1539 macro_rules! get_route_and_payment_hash {
1540 ($recv_value: expr) => {{
1541 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1542 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1543 (route, payment_hash, payment_preimage)
1547 macro_rules! expect_forward {
1549 let mut events = $node.node.get_and_clear_pending_msg_events();
1550 assert_eq!(events.len(), 1);
1551 check_added_monitors!($node, 1);
1552 let payment_event = SendEvent::from_event(events.remove(0));
1557 let feemsat = 239; // somehow we know?
1558 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1560 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1562 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1564 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1565 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1566 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
1568 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
1569 _ => panic!("Unknown error variants"),
1571 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1572 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);
1575 let mut htlc_id = 0;
1576 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1577 // nodes[0]'s wealth
1579 let amt_msat = recv_value_0 + total_fee_msat;
1580 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1583 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1586 let (stat01_, stat11_, stat12_, stat22_) = (
1587 get_channel_value_stat!(nodes[0], chan_1.2),
1588 get_channel_value_stat!(nodes[1], chan_1.2),
1589 get_channel_value_stat!(nodes[1], chan_2.2),
1590 get_channel_value_stat!(nodes[2], chan_2.2),
1593 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1594 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1595 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1596 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1597 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1601 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1602 // attempt to get channel_reserve violation
1603 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1604 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
1606 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1607 _ => panic!("Unknown error variants"),
1609 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1610 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 1);
1613 // adding pending output
1614 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1615 let amt_msat_1 = recv_value_1 + total_fee_msat;
1617 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1618 let payment_event_1 = {
1619 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
1620 check_added_monitors!(nodes[0], 1);
1622 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1623 assert_eq!(events.len(), 1);
1624 SendEvent::from_event(events.remove(0))
1626 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1628 // channel reserve test with htlc pending output > 0
1629 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1631 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1632 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1633 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1634 _ => panic!("Unknown error variants"),
1636 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1637 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 2);
1641 // test channel_reserve test on nodes[1] side
1642 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1644 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1645 let secp_ctx = Secp256k1::new();
1646 let session_priv = SecretKey::from_slice(&{
1647 let mut session_key = [0; 32];
1648 let mut rng = thread_rng();
1649 rng.fill_bytes(&mut session_key);
1651 }).expect("RNG is bad!");
1653 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1654 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1655 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
1656 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1657 let msg = msgs::UpdateAddHTLC {
1658 channel_id: chan_1.2,
1660 amount_msat: htlc_msat,
1661 payment_hash: our_payment_hash,
1662 cltv_expiry: htlc_cltv,
1663 onion_routing_packet: onion_packet,
1667 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1668 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1669 assert_eq!(nodes[1].node.list_channels().len(), 1);
1670 assert_eq!(nodes[1].node.list_channels().len(), 1);
1671 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1672 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
1673 check_added_monitors!(nodes[1], 1);
1678 // split the rest to test holding cell
1679 let recv_value_21 = recv_value_2/2;
1680 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1682 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1683 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);
1686 // now see if they go through on both sides
1687 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1688 // but this will stuck in the holding cell
1689 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
1690 check_added_monitors!(nodes[0], 0);
1691 let events = nodes[0].node.get_and_clear_pending_events();
1692 assert_eq!(events.len(), 0);
1694 // test with outbound holding cell amount > 0
1696 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1697 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1698 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1699 _ => panic!("Unknown error variants"),
1701 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1702 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over their reserve value".to_string(), 3);
1705 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1706 // this will also stuck in the holding cell
1707 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
1708 check_added_monitors!(nodes[0], 0);
1709 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1710 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1712 // flush the pending htlc
1713 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1714 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1715 check_added_monitors!(nodes[1], 1);
1717 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1718 check_added_monitors!(nodes[0], 1);
1719 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1721 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1722 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1723 // No commitment_signed so get_event_msg's assert(len == 1) passes
1724 check_added_monitors!(nodes[0], 1);
1726 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1727 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1728 check_added_monitors!(nodes[1], 1);
1730 expect_pending_htlcs_forwardable!(nodes[1]);
1732 let ref payment_event_11 = expect_forward!(nodes[1]);
1733 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1734 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1736 expect_pending_htlcs_forwardable!(nodes[2]);
1737 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1739 // flush the htlcs in the holding cell
1740 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1741 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1742 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1743 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1744 expect_pending_htlcs_forwardable!(nodes[1]);
1746 let ref payment_event_3 = expect_forward!(nodes[1]);
1747 assert_eq!(payment_event_3.msgs.len(), 2);
1748 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1749 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1751 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1752 expect_pending_htlcs_forwardable!(nodes[2]);
1754 let events = nodes[2].node.get_and_clear_pending_events();
1755 assert_eq!(events.len(), 2);
1757 Event::PaymentReceived { ref payment_hash, amt } => {
1758 assert_eq!(our_payment_hash_21, *payment_hash);
1759 assert_eq!(recv_value_21, amt);
1761 _ => panic!("Unexpected event"),
1764 Event::PaymentReceived { ref payment_hash, amt } => {
1765 assert_eq!(our_payment_hash_22, *payment_hash);
1766 assert_eq!(recv_value_22, amt);
1768 _ => panic!("Unexpected event"),
1771 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1772 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1773 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1775 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);
1776 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1777 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1778 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1780 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1781 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1785 fn channel_reserve_test() {
1786 do_channel_reserve_test(false);
1787 do_channel_reserve_test(true);
1791 fn channel_reserve_in_flight_removes() {
1792 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1793 // can send to its counterparty, but due to update ordering, the other side may not yet have
1794 // considered those HTLCs fully removed.
1795 // This tests that we don't count HTLCs which will not be included in the next remote
1796 // commitment transaction towards the reserve value (as it implies no commitment transaction
1797 // will be generated which violates the remote reserve value).
1798 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1800 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1801 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1802 // you only consider the value of the first HTLC, it may not),
1803 // * start routing a third HTLC from A to B,
1804 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1805 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1806 // * deliver the first fulfill from B
1807 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1809 // * deliver A's response CS and RAA.
1810 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1811 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1812 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1813 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1814 let chanmon_cfgs = create_chanmon_cfgs(2);
1815 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1816 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1817 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1818 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1820 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1821 // Route the first two HTLCs.
1822 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1823 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1825 // Start routing the third HTLC (this is just used to get everyone in the right state).
1826 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1828 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1829 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
1830 check_added_monitors!(nodes[0], 1);
1831 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1832 assert_eq!(events.len(), 1);
1833 SendEvent::from_event(events.remove(0))
1836 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1837 // initial fulfill/CS.
1838 assert!(nodes[1].node.claim_funds(payment_preimage_1, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1839 check_added_monitors!(nodes[1], 1);
1840 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1842 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1843 // remove the second HTLC when we send the HTLC back from B to A.
1844 assert!(nodes[1].node.claim_funds(payment_preimage_2, 20000));
1845 check_added_monitors!(nodes[1], 1);
1846 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1848 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1849 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1850 check_added_monitors!(nodes[0], 1);
1851 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1852 expect_payment_sent!(nodes[0], payment_preimage_1);
1854 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1855 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1856 check_added_monitors!(nodes[1], 1);
1857 // B is already AwaitingRAA, so cant generate a CS here
1858 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1860 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1861 check_added_monitors!(nodes[1], 1);
1862 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1864 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1865 check_added_monitors!(nodes[0], 1);
1866 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1868 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1869 check_added_monitors!(nodes[1], 1);
1870 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1872 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1873 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1874 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1875 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1876 // on-chain as necessary).
1877 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1878 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1879 check_added_monitors!(nodes[0], 1);
1880 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1881 expect_payment_sent!(nodes[0], payment_preimage_2);
1883 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1884 check_added_monitors!(nodes[1], 1);
1885 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1887 expect_pending_htlcs_forwardable!(nodes[1]);
1888 expect_payment_received!(nodes[1], payment_hash_3, 100000);
1890 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1891 // resolve the second HTLC from A's point of view.
1892 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1893 check_added_monitors!(nodes[0], 1);
1894 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1896 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1897 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1898 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1900 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1901 nodes[1].node.send_payment(route, payment_hash_4).unwrap();
1902 check_added_monitors!(nodes[1], 1);
1903 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1904 assert_eq!(events.len(), 1);
1905 SendEvent::from_event(events.remove(0))
1908 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1909 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1910 check_added_monitors!(nodes[0], 1);
1911 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1913 // Now just resolve all the outstanding messages/HTLCs for completeness...
1915 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1916 check_added_monitors!(nodes[1], 1);
1917 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1919 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1920 check_added_monitors!(nodes[1], 1);
1922 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1923 check_added_monitors!(nodes[0], 1);
1924 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1926 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1927 check_added_monitors!(nodes[1], 1);
1928 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1930 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1931 check_added_monitors!(nodes[0], 1);
1933 expect_pending_htlcs_forwardable!(nodes[0]);
1934 expect_payment_received!(nodes[0], payment_hash_4, 10000);
1936 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1937 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1941 fn channel_monitor_network_test() {
1942 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1943 // tests that ChannelMonitor is able to recover from various states.
1944 let chanmon_cfgs = create_chanmon_cfgs(5);
1945 let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1946 let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1947 let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1949 // Create some initial channels
1950 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
1951 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
1952 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
1953 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
1955 // Rebalance the network a bit by relaying one payment through all the channels...
1956 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
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);
1961 // Simple case with no pending HTLCs:
1962 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1963 check_added_monitors!(nodes[1], 1);
1965 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1966 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1967 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1968 check_added_monitors!(nodes[0], 1);
1969 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1971 get_announce_close_broadcast_events(&nodes, 0, 1);
1972 assert_eq!(nodes[0].node.list_channels().len(), 0);
1973 assert_eq!(nodes[1].node.list_channels().len(), 1);
1975 // One pending HTLC is discarded by the force-close:
1976 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1978 // Simple case of one pending HTLC to HTLC-Timeout
1979 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1980 check_added_monitors!(nodes[1], 1);
1982 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1983 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1984 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1985 check_added_monitors!(nodes[2], 1);
1986 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1988 get_announce_close_broadcast_events(&nodes, 1, 2);
1989 assert_eq!(nodes[1].node.list_channels().len(), 0);
1990 assert_eq!(nodes[2].node.list_channels().len(), 1);
1992 macro_rules! claim_funds {
1993 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1995 assert!($node.node.claim_funds($preimage, $amount));
1996 check_added_monitors!($node, 1);
1998 let events = $node.node.get_and_clear_pending_msg_events();
1999 assert_eq!(events.len(), 1);
2001 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
2002 assert!(update_add_htlcs.is_empty());
2003 assert!(update_fail_htlcs.is_empty());
2004 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2006 _ => panic!("Unexpected event"),
2012 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2013 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2014 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2015 check_added_monitors!(nodes[2], 1);
2016 let node2_commitment_txid;
2018 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2019 node2_commitment_txid = node_txn[0].txid();
2021 // Claim the payment on nodes[3], giving it knowledge of the preimage
2022 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2024 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2025 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2026 check_added_monitors!(nodes[3], 1);
2028 check_preimage_claim(&nodes[3], &node_txn);
2030 get_announce_close_broadcast_events(&nodes, 2, 3);
2031 assert_eq!(nodes[2].node.list_channels().len(), 0);
2032 assert_eq!(nodes[3].node.list_channels().len(), 1);
2034 { // Cheat and reset nodes[4]'s height to 1
2035 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2036 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2039 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2040 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2041 // One pending HTLC to time out:
2042 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2043 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2047 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2048 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2049 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2050 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2051 nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2053 check_added_monitors!(nodes[3], 1);
2055 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2057 let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2058 node_txn.retain(|tx| {
2059 if tx.input[0].previous_output.txid == node2_commitment_txid {
2065 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2067 // Claim the payment on nodes[4], giving it knowledge of the preimage
2068 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2070 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2072 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2073 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2074 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2075 nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2078 check_added_monitors!(nodes[4], 1);
2079 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2081 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2082 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2084 check_preimage_claim(&nodes[4], &node_txn);
2086 get_announce_close_broadcast_events(&nodes, 3, 4);
2087 assert_eq!(nodes[3].node.list_channels().len(), 0);
2088 assert_eq!(nodes[4].node.list_channels().len(), 0);
2092 fn test_justice_tx() {
2093 // Test justice txn built on revoked HTLC-Success tx, against both sides
2094 let mut alice_config = UserConfig::default();
2095 alice_config.channel_options.announced_channel = true;
2096 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2097 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2098 let mut bob_config = UserConfig::default();
2099 bob_config.channel_options.announced_channel = true;
2100 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2101 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2102 let user_cfgs = [Some(alice_config), Some(bob_config)];
2103 let chanmon_cfgs = create_chanmon_cfgs(2);
2104 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2105 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2106 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2107 // Create some new channels:
2108 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2110 // A pending HTLC which will be revoked:
2111 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2112 // Get the will-be-revoked local txn from nodes[0]
2113 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2114 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2115 assert_eq!(revoked_local_txn[0].input.len(), 1);
2116 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2117 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2118 assert_eq!(revoked_local_txn[1].input.len(), 1);
2119 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2120 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2121 // Revoke the old state
2122 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2125 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2126 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2128 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2129 assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2130 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2132 check_spends!(node_txn[0], revoked_local_txn[0]);
2133 node_txn.swap_remove(0);
2134 node_txn.truncate(1);
2136 check_added_monitors!(nodes[1], 1);
2137 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2139 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2140 // Verify broadcast of revoked HTLC-timeout
2141 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2142 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2143 check_added_monitors!(nodes[0], 1);
2144 // Broadcast revoked HTLC-timeout on node 1
2145 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2146 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2148 get_announce_close_broadcast_events(&nodes, 0, 1);
2150 assert_eq!(nodes[0].node.list_channels().len(), 0);
2151 assert_eq!(nodes[1].node.list_channels().len(), 0);
2153 // We test justice_tx build by A on B's revoked HTLC-Success tx
2154 // Create some new channels:
2155 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2157 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2161 // A pending HTLC which will be revoked:
2162 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2163 // Get the will-be-revoked local txn from B
2164 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2165 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2166 assert_eq!(revoked_local_txn[0].input.len(), 1);
2167 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2168 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2169 // Revoke the old state
2170 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2172 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2173 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2175 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2176 assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2177 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2179 check_spends!(node_txn[0], revoked_local_txn[0]);
2180 node_txn.swap_remove(0);
2182 check_added_monitors!(nodes[0], 1);
2183 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2185 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2186 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2187 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2188 check_added_monitors!(nodes[1], 1);
2189 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2190 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2192 get_announce_close_broadcast_events(&nodes, 0, 1);
2193 assert_eq!(nodes[0].node.list_channels().len(), 0);
2194 assert_eq!(nodes[1].node.list_channels().len(), 0);
2198 fn revoked_output_claim() {
2199 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2200 // transaction is broadcast by its counterparty
2201 let chanmon_cfgs = create_chanmon_cfgs(2);
2202 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2203 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2204 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2205 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2206 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2207 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2208 assert_eq!(revoked_local_txn.len(), 1);
2209 // Only output is the full channel value back to nodes[0]:
2210 assert_eq!(revoked_local_txn[0].output.len(), 1);
2211 // Send a payment through, updating everyone's latest commitment txn
2212 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2214 // Inform nodes[1] that nodes[0] broadcast a stale tx
2215 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2216 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2217 check_added_monitors!(nodes[1], 1);
2218 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2219 assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2221 check_spends!(node_txn[0], revoked_local_txn[0]);
2222 check_spends!(node_txn[1], chan_1.3);
2224 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2225 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2226 get_announce_close_broadcast_events(&nodes, 0, 1);
2227 check_added_monitors!(nodes[0], 1)
2231 fn claim_htlc_outputs_shared_tx() {
2232 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2233 let chanmon_cfgs = create_chanmon_cfgs(2);
2234 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2235 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2236 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2238 // Create some new channel:
2239 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2241 // Rebalance the network to generate htlc in the two directions
2242 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2243 // 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
2244 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2245 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2247 // Get the will-be-revoked local txn from node[0]
2248 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2249 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2250 assert_eq!(revoked_local_txn[0].input.len(), 1);
2251 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2252 assert_eq!(revoked_local_txn[1].input.len(), 1);
2253 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2254 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2255 check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2257 //Revoke the old state
2258 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2261 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2262 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2263 check_added_monitors!(nodes[0], 1);
2264 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2265 check_added_monitors!(nodes[1], 1);
2266 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2268 let events = nodes[1].node.get_and_clear_pending_events();
2269 assert_eq!(events.len(), 1);
2271 Event::PaymentFailed { payment_hash, .. } => {
2272 assert_eq!(payment_hash, payment_hash_2);
2274 _ => panic!("Unexpected event"),
2277 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2278 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2280 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2281 check_spends!(node_txn[0], revoked_local_txn[0]);
2283 let mut witness_lens = BTreeSet::new();
2284 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2285 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2286 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2287 assert_eq!(witness_lens.len(), 3);
2288 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2289 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2290 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2292 // Next nodes[1] broadcasts its current local tx state:
2293 assert_eq!(node_txn[1].input.len(), 1);
2294 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2296 assert_eq!(node_txn[2].input.len(), 1);
2297 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2298 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2299 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2300 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2301 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2303 get_announce_close_broadcast_events(&nodes, 0, 1);
2304 assert_eq!(nodes[0].node.list_channels().len(), 0);
2305 assert_eq!(nodes[1].node.list_channels().len(), 0);
2309 fn claim_htlc_outputs_single_tx() {
2310 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2311 let chanmon_cfgs = create_chanmon_cfgs(2);
2312 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2313 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2314 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2316 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2318 // Rebalance the network to generate htlc in the two directions
2319 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2320 // 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
2321 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2322 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2323 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2325 // Get the will-be-revoked local txn from node[0]
2326 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2328 //Revoke the old state
2329 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2332 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2333 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2334 check_added_monitors!(nodes[0], 1);
2335 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2336 check_added_monitors!(nodes[1], 1);
2337 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2339 let events = nodes[1].node.get_and_clear_pending_events();
2340 assert_eq!(events.len(), 1);
2342 Event::PaymentFailed { payment_hash, .. } => {
2343 assert_eq!(payment_hash, payment_hash_2);
2345 _ => panic!("Unexpected event"),
2348 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2349 assert_eq!(node_txn.len(), 21);
2350 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2351 // ChannelManager: local commmitment + local HTLC-timeout (2)
2352 // ChannelMonitor: bumped justice tx (4), after one increase, bumps on HTLC aren't generated not being substantial anymore
2353 // ChannelMonito r: local commitment + local HTLC-timeout (14)
2355 assert_eq!(node_txn[0], node_txn[5]);
2356 assert_eq!(node_txn[0], node_txn[7]);
2357 assert_eq!(node_txn[0], node_txn[9]);
2358 assert_eq!(node_txn[0], node_txn[13]);
2359 assert_eq!(node_txn[0], node_txn[15]);
2360 assert_eq!(node_txn[0], node_txn[17]);
2361 assert_eq!(node_txn[0], node_txn[19]);
2363 assert_eq!(node_txn[1], node_txn[6]);
2364 assert_eq!(node_txn[1], node_txn[8]);
2365 assert_eq!(node_txn[1], node_txn[10]);
2366 assert_eq!(node_txn[1], node_txn[14]);
2367 assert_eq!(node_txn[1], node_txn[16]);
2368 assert_eq!(node_txn[1], node_txn[18]);
2369 assert_eq!(node_txn[1], node_txn[20]);
2372 // 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)
2373 assert_eq!(node_txn[0].input.len(), 1);
2374 check_spends!(node_txn[0], chan_1.3);
2375 assert_eq!(node_txn[1].input.len(), 1);
2376 let witness_script = node_txn[1].input[0].witness.last().unwrap();
2377 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2378 check_spends!(node_txn[1], node_txn[0]);
2380 // Justice transactions are indices 2-3-4
2381 assert_eq!(node_txn[2].input.len(), 1);
2382 assert_eq!(node_txn[3].input.len(), 1);
2383 assert_eq!(node_txn[4].input.len(), 1);
2384 check_spends!(node_txn[2], revoked_local_txn[0]);
2385 check_spends!(node_txn[3], revoked_local_txn[0]);
2386 check_spends!(node_txn[4], revoked_local_txn[0]);
2388 let mut witness_lens = BTreeSet::new();
2389 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2390 witness_lens.insert(node_txn[3].input[0].witness.last().unwrap().len());
2391 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2392 assert_eq!(witness_lens.len(), 3);
2393 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2394 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2395 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2397 get_announce_close_broadcast_events(&nodes, 0, 1);
2398 assert_eq!(nodes[0].node.list_channels().len(), 0);
2399 assert_eq!(nodes[1].node.list_channels().len(), 0);
2403 fn test_htlc_on_chain_success() {
2404 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2405 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2406 // broadcasting the right event to other nodes in payment path.
2407 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2408 // A --------------------> B ----------------------> C (preimage)
2409 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2410 // commitment transaction was broadcast.
2411 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2413 // B should be able to claim via preimage if A then broadcasts its local tx.
2414 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2415 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2416 // PaymentSent event).
2418 let chanmon_cfgs = create_chanmon_cfgs(3);
2419 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2420 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2421 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2423 // Create some initial channels
2424 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2425 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2427 // Rebalance the network a bit by relaying one payment through all the channels...
2428 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2429 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2431 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2432 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2433 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2435 // Broadcast legit commitment tx from C on B's chain
2436 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2437 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2438 assert_eq!(commitment_tx.len(), 1);
2439 check_spends!(commitment_tx[0], chan_2.3);
2440 nodes[2].node.claim_funds(our_payment_preimage, 3_000_000);
2441 nodes[2].node.claim_funds(our_payment_preimage_2, 3_000_000);
2442 check_added_monitors!(nodes[2], 2);
2443 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2444 assert!(updates.update_add_htlcs.is_empty());
2445 assert!(updates.update_fail_htlcs.is_empty());
2446 assert!(updates.update_fail_malformed_htlcs.is_empty());
2447 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2449 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2450 check_closed_broadcast!(nodes[2], false);
2451 check_added_monitors!(nodes[2], 1);
2452 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)
2453 assert_eq!(node_txn.len(), 7);
2454 assert_eq!(node_txn[0], node_txn[3]);
2455 assert_eq!(node_txn[1], node_txn[4]);
2456 assert_eq!(node_txn[0], node_txn[5]);
2457 assert_eq!(node_txn[1], node_txn[6]);
2458 assert_eq!(node_txn[2], commitment_tx[0]);
2459 check_spends!(node_txn[0], commitment_tx[0]);
2460 check_spends!(node_txn[1], commitment_tx[0]);
2461 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2462 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2463 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2464 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2465 assert_eq!(node_txn[0].lock_time, 0);
2466 assert_eq!(node_txn[1].lock_time, 0);
2468 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2469 nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2471 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2472 assert_eq!(added_monitors.len(), 1);
2473 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2474 added_monitors.clear();
2476 let events = nodes[1].node.get_and_clear_pending_msg_events();
2478 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2479 assert_eq!(added_monitors.len(), 2);
2480 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2481 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2482 added_monitors.clear();
2484 assert_eq!(events.len(), 2);
2486 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2487 _ => panic!("Unexpected event"),
2490 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, .. } } => {
2491 assert!(update_add_htlcs.is_empty());
2492 assert!(update_fail_htlcs.is_empty());
2493 assert_eq!(update_fulfill_htlcs.len(), 1);
2494 assert!(update_fail_malformed_htlcs.is_empty());
2495 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2497 _ => panic!("Unexpected event"),
2499 macro_rules! check_tx_local_broadcast {
2500 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2501 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2502 assert_eq!(node_txn.len(), if $htlc_offered { 7 } else { 5 });
2503 // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2504 // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout * 2 (block-rescan)
2505 check_spends!(node_txn[0], $commitment_tx);
2506 check_spends!(node_txn[1], $commitment_tx);
2508 assert_eq!(node_txn[0], node_txn[5]);
2509 assert_eq!(node_txn[1], node_txn[6]);
2511 assert_ne!(node_txn[0].lock_time, 0);
2512 assert_ne!(node_txn[1].lock_time, 0);
2514 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2515 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2516 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2517 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2519 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2520 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2521 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2522 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2524 check_spends!(node_txn[2], $chan_tx);
2525 check_spends!(node_txn[3], node_txn[2]);
2526 check_spends!(node_txn[4], node_txn[2]);
2527 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2528 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2529 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2530 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2531 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2532 assert_ne!(node_txn[3].lock_time, 0);
2533 assert_ne!(node_txn[4].lock_time, 0);
2537 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2538 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2539 // timeout-claim of the output that nodes[2] just claimed via success.
2540 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2542 // Broadcast legit commitment tx from A on B's chain
2543 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2544 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2545 check_spends!(commitment_tx[0], chan_1.3);
2546 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2547 check_closed_broadcast!(nodes[1], false);
2548 check_added_monitors!(nodes[1], 1);
2549 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2550 assert_eq!(node_txn.len(), 4);
2551 check_spends!(node_txn[0], commitment_tx[0]);
2552 assert_eq!(node_txn[0].input.len(), 2);
2553 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2554 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2555 assert_eq!(node_txn[0].lock_time, 0);
2556 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2557 check_spends!(node_txn[1], chan_1.3);
2558 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2559 check_spends!(node_txn[2], node_txn[1]);
2560 check_spends!(node_txn[3], node_txn[1]);
2561 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2562 // we already checked the same situation with A.
2564 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2565 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2566 check_closed_broadcast!(nodes[0], false);
2567 check_added_monitors!(nodes[0], 1);
2568 let events = nodes[0].node.get_and_clear_pending_events();
2569 assert_eq!(events.len(), 2);
2570 let mut first_claimed = false;
2571 for event in events {
2573 Event::PaymentSent { payment_preimage } => {
2574 if payment_preimage == our_payment_preimage {
2575 assert!(!first_claimed);
2576 first_claimed = true;
2578 assert_eq!(payment_preimage, our_payment_preimage_2);
2581 _ => panic!("Unexpected event"),
2584 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2588 fn test_htlc_on_chain_timeout() {
2589 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2590 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2591 // broadcasting the right event to other nodes in payment path.
2592 // A ------------------> B ----------------------> C (timeout)
2593 // B's commitment tx C's commitment tx
2595 // B's HTLC timeout tx B's timeout tx
2597 let chanmon_cfgs = create_chanmon_cfgs(3);
2598 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2599 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2600 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2602 // Create some intial channels
2603 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2604 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2606 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2607 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2608 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2610 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2611 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2613 // Broadcast legit commitment tx from C on B's chain
2614 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2615 check_spends!(commitment_tx[0], chan_2.3);
2616 nodes[2].node.fail_htlc_backwards(&payment_hash);
2617 check_added_monitors!(nodes[2], 0);
2618 expect_pending_htlcs_forwardable!(nodes[2]);
2619 check_added_monitors!(nodes[2], 1);
2621 let events = nodes[2].node.get_and_clear_pending_msg_events();
2622 assert_eq!(events.len(), 1);
2624 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, .. } } => {
2625 assert!(update_add_htlcs.is_empty());
2626 assert!(!update_fail_htlcs.is_empty());
2627 assert!(update_fulfill_htlcs.is_empty());
2628 assert!(update_fail_malformed_htlcs.is_empty());
2629 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2631 _ => panic!("Unexpected event"),
2633 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2634 check_closed_broadcast!(nodes[2], false);
2635 check_added_monitors!(nodes[2], 1);
2636 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2637 assert_eq!(node_txn.len(), 1);
2638 check_spends!(node_txn[0], chan_2.3);
2639 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2641 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2642 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2643 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2646 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2647 assert_eq!(node_txn.len(), 7); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : (local commitment tx + HTLC-timeout) * 2 (block-rescan), timeout tx
2648 assert_eq!(node_txn[0], node_txn[3]);
2649 assert_eq!(node_txn[0], node_txn[5]);
2650 assert_eq!(node_txn[1], node_txn[4]);
2651 assert_eq!(node_txn[1], node_txn[6]);
2653 check_spends!(node_txn[2], commitment_tx[0]);
2654 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2656 check_spends!(node_txn[0], chan_2.3);
2657 check_spends!(node_txn[1], node_txn[0]);
2658 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), 71);
2659 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2661 timeout_tx = node_txn[2].clone();
2665 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2666 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2667 check_added_monitors!(nodes[1], 1);
2668 check_closed_broadcast!(nodes[1], false);
2670 expect_pending_htlcs_forwardable!(nodes[1]);
2671 check_added_monitors!(nodes[1], 1);
2672 let events = nodes[1].node.get_and_clear_pending_msg_events();
2673 assert_eq!(events.len(), 1);
2675 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, .. } } => {
2676 assert!(update_add_htlcs.is_empty());
2677 assert!(!update_fail_htlcs.is_empty());
2678 assert!(update_fulfill_htlcs.is_empty());
2679 assert!(update_fail_malformed_htlcs.is_empty());
2680 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2682 _ => panic!("Unexpected event"),
2684 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
2685 assert_eq!(node_txn.len(), 0);
2687 // Broadcast legit commitment tx from B on A's chain
2688 let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2689 check_spends!(commitment_tx[0], chan_1.3);
2691 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2692 check_closed_broadcast!(nodes[0], false);
2693 check_added_monitors!(nodes[0], 1);
2694 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2695 assert_eq!(node_txn.len(), 3);
2696 check_spends!(node_txn[0], commitment_tx[0]);
2697 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2698 check_spends!(node_txn[1], chan_1.3);
2699 check_spends!(node_txn[2], node_txn[1]);
2700 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2701 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2705 fn test_simple_commitment_revoked_fail_backward() {
2706 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2707 // and fail backward accordingly.
2709 let chanmon_cfgs = create_chanmon_cfgs(3);
2710 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2711 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2712 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2714 // Create some initial channels
2715 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2716 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2718 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2719 // Get the will-be-revoked local txn from nodes[2]
2720 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2721 // Revoke the old state
2722 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2724 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2726 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2727 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2728 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2729 check_added_monitors!(nodes[1], 1);
2730 check_closed_broadcast!(nodes[1], false);
2732 expect_pending_htlcs_forwardable!(nodes[1]);
2733 check_added_monitors!(nodes[1], 1);
2734 let events = nodes[1].node.get_and_clear_pending_msg_events();
2735 assert_eq!(events.len(), 1);
2737 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, .. } } => {
2738 assert!(update_add_htlcs.is_empty());
2739 assert_eq!(update_fail_htlcs.len(), 1);
2740 assert!(update_fulfill_htlcs.is_empty());
2741 assert!(update_fail_malformed_htlcs.is_empty());
2742 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2744 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2745 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2747 let events = nodes[0].node.get_and_clear_pending_msg_events();
2748 assert_eq!(events.len(), 1);
2750 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2751 _ => panic!("Unexpected event"),
2753 let events = nodes[0].node.get_and_clear_pending_events();
2754 assert_eq!(events.len(), 1);
2756 Event::PaymentFailed { .. } => {},
2757 _ => panic!("Unexpected event"),
2760 _ => panic!("Unexpected event"),
2764 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2765 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2766 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2767 // commitment transaction anymore.
2768 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2769 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2770 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2771 // technically disallowed and we should probably handle it reasonably.
2772 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2773 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2775 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2776 // commitment_signed (implying it will be in the latest remote commitment transaction).
2777 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2778 // and once they revoke the previous commitment transaction (allowing us to send a new
2779 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2780 let chanmon_cfgs = create_chanmon_cfgs(3);
2781 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2782 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2783 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2785 // Create some initial channels
2786 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
2787 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
2789 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2790 // Get the will-be-revoked local txn from nodes[2]
2791 let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2792 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2793 // Revoke the old state
2794 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2796 let value = if use_dust {
2797 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2798 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2799 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2802 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2803 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2804 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2806 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2807 expect_pending_htlcs_forwardable!(nodes[2]);
2808 check_added_monitors!(nodes[2], 1);
2809 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2810 assert!(updates.update_add_htlcs.is_empty());
2811 assert!(updates.update_fulfill_htlcs.is_empty());
2812 assert!(updates.update_fail_malformed_htlcs.is_empty());
2813 assert_eq!(updates.update_fail_htlcs.len(), 1);
2814 assert!(updates.update_fee.is_none());
2815 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2816 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2817 // Drop the last RAA from 3 -> 2
2819 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2820 expect_pending_htlcs_forwardable!(nodes[2]);
2821 check_added_monitors!(nodes[2], 1);
2822 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2823 assert!(updates.update_add_htlcs.is_empty());
2824 assert!(updates.update_fulfill_htlcs.is_empty());
2825 assert!(updates.update_fail_malformed_htlcs.is_empty());
2826 assert_eq!(updates.update_fail_htlcs.len(), 1);
2827 assert!(updates.update_fee.is_none());
2828 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2829 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2830 check_added_monitors!(nodes[1], 1);
2831 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2832 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2833 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2834 check_added_monitors!(nodes[2], 1);
2836 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2837 expect_pending_htlcs_forwardable!(nodes[2]);
2838 check_added_monitors!(nodes[2], 1);
2839 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2840 assert!(updates.update_add_htlcs.is_empty());
2841 assert!(updates.update_fulfill_htlcs.is_empty());
2842 assert!(updates.update_fail_malformed_htlcs.is_empty());
2843 assert_eq!(updates.update_fail_htlcs.len(), 1);
2844 assert!(updates.update_fee.is_none());
2845 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2846 // At this point first_payment_hash has dropped out of the latest two commitment
2847 // transactions that nodes[1] is tracking...
2848 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2849 check_added_monitors!(nodes[1], 1);
2850 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2851 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2852 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2853 check_added_monitors!(nodes[2], 1);
2855 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2856 // on nodes[2]'s RAA.
2857 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2858 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2859 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
2860 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2861 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2862 check_added_monitors!(nodes[1], 0);
2865 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2866 // One monitor for the new revocation preimage, no second on as we won't generate a new
2867 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2868 check_added_monitors!(nodes[1], 1);
2869 let events = nodes[1].node.get_and_clear_pending_events();
2870 assert_eq!(events.len(), 1);
2872 Event::PendingHTLCsForwardable { .. } => { },
2873 _ => panic!("Unexpected event"),
2875 // Deliberately don't process the pending fail-back so they all fail back at once after
2876 // block connection just like the !deliver_bs_raa case
2879 let mut failed_htlcs = HashSet::new();
2880 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2882 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2883 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2884 check_added_monitors!(nodes[1], 1);
2885 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2887 let events = nodes[1].node.get_and_clear_pending_events();
2888 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2890 Event::PaymentFailed { ref payment_hash, .. } => {
2891 assert_eq!(*payment_hash, fourth_payment_hash);
2893 _ => panic!("Unexpected event"),
2895 if !deliver_bs_raa {
2897 Event::PendingHTLCsForwardable { .. } => { },
2898 _ => panic!("Unexpected event"),
2901 nodes[1].node.process_pending_htlc_forwards();
2902 check_added_monitors!(nodes[1], 1);
2904 let events = nodes[1].node.get_and_clear_pending_msg_events();
2905 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2906 match events[if deliver_bs_raa { 1 } else { 0 }] {
2907 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2908 _ => panic!("Unexpected event"),
2912 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, .. } } => {
2913 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2914 assert_eq!(update_add_htlcs.len(), 1);
2915 assert!(update_fulfill_htlcs.is_empty());
2916 assert!(update_fail_htlcs.is_empty());
2917 assert!(update_fail_malformed_htlcs.is_empty());
2919 _ => panic!("Unexpected event"),
2922 match events[if deliver_bs_raa { 2 } else { 1 }] {
2923 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, .. } } => {
2924 assert!(update_add_htlcs.is_empty());
2925 assert_eq!(update_fail_htlcs.len(), 3);
2926 assert!(update_fulfill_htlcs.is_empty());
2927 assert!(update_fail_malformed_htlcs.is_empty());
2928 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2930 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2931 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2932 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2934 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2936 let events = nodes[0].node.get_and_clear_pending_msg_events();
2937 // If we delivered B's RAA we got an unknown preimage error, not something
2938 // that we should update our routing table for.
2939 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2940 for event in events {
2942 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2943 _ => panic!("Unexpected event"),
2946 let events = nodes[0].node.get_and_clear_pending_events();
2947 assert_eq!(events.len(), 3);
2949 Event::PaymentFailed { ref payment_hash, .. } => {
2950 assert!(failed_htlcs.insert(payment_hash.0));
2952 _ => panic!("Unexpected event"),
2955 Event::PaymentFailed { ref payment_hash, .. } => {
2956 assert!(failed_htlcs.insert(payment_hash.0));
2958 _ => panic!("Unexpected event"),
2961 Event::PaymentFailed { ref payment_hash, .. } => {
2962 assert!(failed_htlcs.insert(payment_hash.0));
2964 _ => panic!("Unexpected event"),
2967 _ => panic!("Unexpected event"),
2970 assert!(failed_htlcs.contains(&first_payment_hash.0));
2971 assert!(failed_htlcs.contains(&second_payment_hash.0));
2972 assert!(failed_htlcs.contains(&third_payment_hash.0));
2976 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2977 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2978 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2979 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2980 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2984 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2985 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2986 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2987 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2988 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2992 fn test_htlc_ignore_latest_remote_commitment() {
2993 // Test that HTLC transactions spending the latest remote commitment transaction are simply
2994 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2995 let chanmon_cfgs = create_chanmon_cfgs(2);
2996 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2997 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2998 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2999 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3001 route_payment(&nodes[0], &[&nodes[1]], 10000000);
3002 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3003 check_closed_broadcast!(nodes[0], false);
3004 check_added_monitors!(nodes[0], 1);
3006 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3007 assert_eq!(node_txn.len(), 2);
3009 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3010 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3011 check_closed_broadcast!(nodes[1], false);
3012 check_added_monitors!(nodes[1], 1);
3014 // Duplicate the block_connected call since this may happen due to other listeners
3015 // registering new transactions
3016 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3020 fn test_force_close_fail_back() {
3021 // Check which HTLCs are failed-backwards on channel force-closure
3022 let chanmon_cfgs = create_chanmon_cfgs(3);
3023 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3024 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3025 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3026 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3027 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
3029 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
3031 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3033 let mut payment_event = {
3034 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
3035 check_added_monitors!(nodes[0], 1);
3037 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3038 assert_eq!(events.len(), 1);
3039 SendEvent::from_event(events.remove(0))
3042 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3043 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3045 expect_pending_htlcs_forwardable!(nodes[1]);
3047 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3048 assert_eq!(events_2.len(), 1);
3049 payment_event = SendEvent::from_event(events_2.remove(0));
3050 assert_eq!(payment_event.msgs.len(), 1);
3052 check_added_monitors!(nodes[1], 1);
3053 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3054 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3055 check_added_monitors!(nodes[2], 1);
3056 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3058 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3059 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3060 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3062 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3063 check_closed_broadcast!(nodes[2], false);
3064 check_added_monitors!(nodes[2], 1);
3066 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3067 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3068 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3069 // back to nodes[1] upon timeout otherwise.
3070 assert_eq!(node_txn.len(), 1);
3074 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3075 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3077 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3078 check_closed_broadcast!(nodes[1], false);
3079 check_added_monitors!(nodes[1], 1);
3081 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3083 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3084 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
3085 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3087 nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3088 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3089 assert_eq!(node_txn.len(), 1);
3090 assert_eq!(node_txn[0].input.len(), 1);
3091 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3092 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3093 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3095 check_spends!(node_txn[0], tx);
3099 fn test_unconf_chan() {
3100 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3101 let chanmon_cfgs = create_chanmon_cfgs(2);
3102 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3103 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3104 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3105 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3107 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3108 assert_eq!(channel_state.by_id.len(), 1);
3109 assert_eq!(channel_state.short_to_id.len(), 1);
3110 mem::drop(channel_state);
3112 let mut headers = Vec::new();
3113 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3114 headers.push(header.clone());
3116 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3117 headers.push(header.clone());
3119 let mut height = 99;
3120 while !headers.is_empty() {
3121 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3124 check_closed_broadcast!(nodes[0], false);
3125 check_added_monitors!(nodes[0], 1);
3126 let channel_state = nodes[0].node.channel_state.lock().unwrap();
3127 assert_eq!(channel_state.by_id.len(), 0);
3128 assert_eq!(channel_state.short_to_id.len(), 0);
3132 fn test_simple_peer_disconnect() {
3133 // Test that we can reconnect when there are no lost messages
3134 let chanmon_cfgs = create_chanmon_cfgs(3);
3135 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3136 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3137 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3138 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3139 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
3141 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3142 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3143 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3145 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3146 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3147 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3148 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3150 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3151 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3152 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3154 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3155 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3156 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3157 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3159 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3160 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3162 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3163 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3165 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3167 let events = nodes[0].node.get_and_clear_pending_events();
3168 assert_eq!(events.len(), 2);
3170 Event::PaymentSent { payment_preimage } => {
3171 assert_eq!(payment_preimage, payment_preimage_3);
3173 _ => panic!("Unexpected event"),
3176 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3177 assert_eq!(payment_hash, payment_hash_5);
3178 assert!(rejected_by_dest);
3180 _ => panic!("Unexpected event"),
3184 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3185 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3188 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3189 // Test that we can reconnect when in-flight HTLC updates get dropped
3190 let chanmon_cfgs = create_chanmon_cfgs(2);
3191 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3192 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3193 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3194 if messages_delivered == 0 {
3195 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3196 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3198 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3201 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();
3202 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3204 let payment_event = {
3205 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
3206 check_added_monitors!(nodes[0], 1);
3208 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3209 assert_eq!(events.len(), 1);
3210 SendEvent::from_event(events.remove(0))
3212 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3214 if messages_delivered < 2 {
3215 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3217 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3218 if messages_delivered >= 3 {
3219 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3220 check_added_monitors!(nodes[1], 1);
3221 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3223 if messages_delivered >= 4 {
3224 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3225 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3226 check_added_monitors!(nodes[0], 1);
3228 if messages_delivered >= 5 {
3229 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3230 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3231 // No commitment_signed so get_event_msg's assert(len == 1) passes
3232 check_added_monitors!(nodes[0], 1);
3234 if messages_delivered >= 6 {
3235 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3236 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3237 check_added_monitors!(nodes[1], 1);
3244 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3245 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3246 if messages_delivered < 3 {
3247 // Even if the funding_locked messages get exchanged, as long as nothing further was
3248 // received on either side, both sides will need to resend them.
3249 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3250 } else if messages_delivered == 3 {
3251 // nodes[0] still wants its RAA + commitment_signed
3252 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3253 } else if messages_delivered == 4 {
3254 // nodes[0] still wants its commitment_signed
3255 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3256 } else if messages_delivered == 5 {
3257 // nodes[1] still wants its final RAA
3258 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3259 } else if messages_delivered == 6 {
3260 // Everything was delivered...
3261 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3264 let events_1 = nodes[1].node.get_and_clear_pending_events();
3265 assert_eq!(events_1.len(), 1);
3267 Event::PendingHTLCsForwardable { .. } => { },
3268 _ => panic!("Unexpected event"),
3271 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3272 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3273 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3275 nodes[1].node.process_pending_htlc_forwards();
3277 let events_2 = nodes[1].node.get_and_clear_pending_events();
3278 assert_eq!(events_2.len(), 1);
3280 Event::PaymentReceived { ref payment_hash, amt } => {
3281 assert_eq!(payment_hash_1, *payment_hash);
3282 assert_eq!(amt, 1000000);
3284 _ => panic!("Unexpected event"),
3287 nodes[1].node.claim_funds(payment_preimage_1, 1_000_000);
3288 check_added_monitors!(nodes[1], 1);
3290 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3291 assert_eq!(events_3.len(), 1);
3292 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3293 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3294 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3295 assert!(updates.update_add_htlcs.is_empty());
3296 assert!(updates.update_fail_htlcs.is_empty());
3297 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3298 assert!(updates.update_fail_malformed_htlcs.is_empty());
3299 assert!(updates.update_fee.is_none());
3300 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3302 _ => panic!("Unexpected event"),
3305 if messages_delivered >= 1 {
3306 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3308 let events_4 = nodes[0].node.get_and_clear_pending_events();
3309 assert_eq!(events_4.len(), 1);
3311 Event::PaymentSent { ref payment_preimage } => {
3312 assert_eq!(payment_preimage_1, *payment_preimage);
3314 _ => panic!("Unexpected event"),
3317 if messages_delivered >= 2 {
3318 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3319 check_added_monitors!(nodes[0], 1);
3320 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3322 if messages_delivered >= 3 {
3323 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3324 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3325 check_added_monitors!(nodes[1], 1);
3327 if messages_delivered >= 4 {
3328 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3329 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3330 // No commitment_signed so get_event_msg's assert(len == 1) passes
3331 check_added_monitors!(nodes[1], 1);
3333 if messages_delivered >= 5 {
3334 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3335 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3336 check_added_monitors!(nodes[0], 1);
3343 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3344 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3345 if messages_delivered < 2 {
3346 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3347 //TODO: Deduplicate PaymentSent events, then enable this if:
3348 //if messages_delivered < 1 {
3349 let events_4 = nodes[0].node.get_and_clear_pending_events();
3350 assert_eq!(events_4.len(), 1);
3352 Event::PaymentSent { ref payment_preimage } => {
3353 assert_eq!(payment_preimage_1, *payment_preimage);
3355 _ => panic!("Unexpected event"),
3358 } else if messages_delivered == 2 {
3359 // nodes[0] still wants its RAA + commitment_signed
3360 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3361 } else if messages_delivered == 3 {
3362 // nodes[0] still wants its commitment_signed
3363 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3364 } else if messages_delivered == 4 {
3365 // nodes[1] still wants its final RAA
3366 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3367 } else if messages_delivered == 5 {
3368 // Everything was delivered...
3369 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3372 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3373 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3374 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3376 // Channel should still work fine...
3377 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3378 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3382 fn test_drop_messages_peer_disconnect_a() {
3383 do_test_drop_messages_peer_disconnect(0);
3384 do_test_drop_messages_peer_disconnect(1);
3385 do_test_drop_messages_peer_disconnect(2);
3386 do_test_drop_messages_peer_disconnect(3);
3390 fn test_drop_messages_peer_disconnect_b() {
3391 do_test_drop_messages_peer_disconnect(4);
3392 do_test_drop_messages_peer_disconnect(5);
3393 do_test_drop_messages_peer_disconnect(6);
3397 fn test_funding_peer_disconnect() {
3398 // Test that we can lock in our funding tx while disconnected
3399 let chanmon_cfgs = create_chanmon_cfgs(2);
3400 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3401 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3402 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3403 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3405 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3406 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3408 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3409 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3410 assert_eq!(events_1.len(), 1);
3412 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3413 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3415 _ => panic!("Unexpected event"),
3418 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3420 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3421 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3423 confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3424 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3425 assert_eq!(events_2.len(), 2);
3426 let funding_locked = match events_2[0] {
3427 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3428 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3431 _ => panic!("Unexpected event"),
3433 let bs_announcement_sigs = match events_2[1] {
3434 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3435 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3438 _ => panic!("Unexpected event"),
3441 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3443 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3444 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3445 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3446 assert_eq!(events_3.len(), 2);
3447 let as_announcement_sigs = match events_3[0] {
3448 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3449 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3452 _ => panic!("Unexpected event"),
3454 let (as_announcement, as_update) = match events_3[1] {
3455 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3456 (msg.clone(), update_msg.clone())
3458 _ => panic!("Unexpected event"),
3461 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3462 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3463 assert_eq!(events_4.len(), 1);
3464 let (_, bs_update) = match events_4[0] {
3465 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3466 (msg.clone(), update_msg.clone())
3468 _ => panic!("Unexpected event"),
3471 nodes[0].router.handle_channel_announcement(&as_announcement).unwrap();
3472 nodes[0].router.handle_channel_update(&bs_update).unwrap();
3473 nodes[0].router.handle_channel_update(&as_update).unwrap();
3475 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3476 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3477 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3481 fn test_drop_messages_peer_disconnect_dual_htlc() {
3482 // Test that we can handle reconnecting when both sides of a channel have pending
3483 // commitment_updates when we disconnect.
3484 let chanmon_cfgs = create_chanmon_cfgs(2);
3485 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3486 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3487 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3488 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3490 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3492 // Now try to send a second payment which will fail to send
3493 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3494 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3496 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3497 check_added_monitors!(nodes[0], 1);
3499 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3500 assert_eq!(events_1.len(), 1);
3502 MessageSendEvent::UpdateHTLCs { .. } => {},
3503 _ => panic!("Unexpected event"),
3506 assert!(nodes[1].node.claim_funds(payment_preimage_1, 1_000_000));
3507 check_added_monitors!(nodes[1], 1);
3509 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3510 assert_eq!(events_2.len(), 1);
3512 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 } } => {
3513 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3514 assert!(update_add_htlcs.is_empty());
3515 assert_eq!(update_fulfill_htlcs.len(), 1);
3516 assert!(update_fail_htlcs.is_empty());
3517 assert!(update_fail_malformed_htlcs.is_empty());
3518 assert!(update_fee.is_none());
3520 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3521 let events_3 = nodes[0].node.get_and_clear_pending_events();
3522 assert_eq!(events_3.len(), 1);
3524 Event::PaymentSent { ref payment_preimage } => {
3525 assert_eq!(*payment_preimage, payment_preimage_1);
3527 _ => panic!("Unexpected event"),
3530 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3531 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3532 // No commitment_signed so get_event_msg's assert(len == 1) passes
3533 check_added_monitors!(nodes[0], 1);
3535 _ => panic!("Unexpected event"),
3538 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3539 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3541 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3542 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3543 assert_eq!(reestablish_1.len(), 1);
3544 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3545 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3546 assert_eq!(reestablish_2.len(), 1);
3548 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3549 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3550 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3551 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3553 assert!(as_resp.0.is_none());
3554 assert!(bs_resp.0.is_none());
3556 assert!(bs_resp.1.is_none());
3557 assert!(bs_resp.2.is_none());
3559 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3561 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3562 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3563 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3564 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3565 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3566 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3567 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3568 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3569 // No commitment_signed so get_event_msg's assert(len == 1) passes
3570 check_added_monitors!(nodes[1], 1);
3572 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3573 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3574 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3575 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3576 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3577 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3578 assert!(bs_second_commitment_signed.update_fee.is_none());
3579 check_added_monitors!(nodes[1], 1);
3581 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3582 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3583 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3584 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3585 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3586 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3587 assert!(as_commitment_signed.update_fee.is_none());
3588 check_added_monitors!(nodes[0], 1);
3590 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3591 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3592 // No commitment_signed so get_event_msg's assert(len == 1) passes
3593 check_added_monitors!(nodes[0], 1);
3595 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3596 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3597 // No commitment_signed so get_event_msg's assert(len == 1) passes
3598 check_added_monitors!(nodes[1], 1);
3600 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3601 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3602 check_added_monitors!(nodes[1], 1);
3604 expect_pending_htlcs_forwardable!(nodes[1]);
3606 let events_5 = nodes[1].node.get_and_clear_pending_events();
3607 assert_eq!(events_5.len(), 1);
3609 Event::PaymentReceived { ref payment_hash, amt: _ } => {
3610 assert_eq!(payment_hash_2, *payment_hash);
3612 _ => panic!("Unexpected event"),
3615 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3616 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3617 check_added_monitors!(nodes[0], 1);
3619 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3623 fn test_invalid_channel_announcement() {
3624 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3625 let secp_ctx = Secp256k1::new();
3626 let chanmon_cfgs = create_chanmon_cfgs(2);
3627 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3628 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3629 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3631 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::supported(), InitFeatures::supported());
3633 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3634 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3635 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3636 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3638 nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3640 let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3641 let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3643 let as_network_key = nodes[0].node.get_our_node_id();
3644 let bs_network_key = nodes[1].node.get_our_node_id();
3646 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3648 let mut chan_announcement;
3650 macro_rules! dummy_unsigned_msg {
3652 msgs::UnsignedChannelAnnouncement {
3653 features: ChannelFeatures::supported(),
3654 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3655 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3656 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3657 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3658 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3659 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3660 excess_data: Vec::new(),
3665 macro_rules! sign_msg {
3666 ($unsigned_msg: expr) => {
3667 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3668 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3669 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3670 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3671 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3672 chan_announcement = msgs::ChannelAnnouncement {
3673 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3674 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3675 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3676 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3677 contents: $unsigned_msg
3682 let unsigned_msg = dummy_unsigned_msg!();
3683 sign_msg!(unsigned_msg);
3684 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3685 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 } );
3687 // Configured with Network::Testnet
3688 let mut unsigned_msg = dummy_unsigned_msg!();
3689 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3690 sign_msg!(unsigned_msg);
3691 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3693 let mut unsigned_msg = dummy_unsigned_msg!();
3694 unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3695 sign_msg!(unsigned_msg);
3696 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3700 fn test_no_txn_manager_serialize_deserialize() {
3701 let chanmon_cfgs = create_chanmon_cfgs(2);
3702 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3703 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3704 let fee_estimator: test_utils::TestFeeEstimator;
3705 let new_chan_monitor: test_utils::TestChannelMonitor;
3706 let keys_manager: test_utils::TestKeysInterface;
3707 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3708 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3710 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::supported(), InitFeatures::supported());
3712 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3714 let nodes_0_serialized = nodes[0].node.encode();
3715 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3716 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3718 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3719 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);
3720 nodes[0].chan_monitor = &new_chan_monitor;
3721 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3722 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3723 assert!(chan_0_monitor_read.is_empty());
3725 let mut nodes_0_read = &nodes_0_serialized[..];
3726 let config = UserConfig::default();
3727 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3728 let (_, nodes_0_deserialized_tmp) = {
3729 let mut channel_monitors = HashMap::new();
3730 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &mut chan_0_monitor);
3731 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3732 default_config: config,
3733 keys_manager: &keys_manager,
3734 fee_estimator: &fee_estimator,
3735 monitor: nodes[0].chan_monitor,
3736 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3737 logger: Arc::new(test_utils::TestLogger::new()),
3738 channel_monitors: &mut channel_monitors,
3741 nodes_0_deserialized = nodes_0_deserialized_tmp;
3742 assert!(nodes_0_read.is_empty());
3744 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3745 nodes[0].node = &nodes_0_deserialized;
3746 nodes[0].block_notifier.register_listener(nodes[0].node);
3747 assert_eq!(nodes[0].node.list_channels().len(), 1);
3748 check_added_monitors!(nodes[0], 1);
3750 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3751 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3752 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3753 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3755 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3756 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3757 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3758 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3760 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3761 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3762 for node in nodes.iter() {
3763 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3764 node.router.handle_channel_update(&as_update).unwrap();
3765 node.router.handle_channel_update(&bs_update).unwrap();
3768 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3772 fn test_simple_manager_serialize_deserialize() {
3773 let chanmon_cfgs = create_chanmon_cfgs(2);
3774 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3775 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3776 let fee_estimator: test_utils::TestFeeEstimator;
3777 let new_chan_monitor: test_utils::TestChannelMonitor;
3778 let keys_manager: test_utils::TestKeysInterface;
3779 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3780 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3781 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3783 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3784 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3786 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3788 let nodes_0_serialized = nodes[0].node.encode();
3789 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3790 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3792 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3793 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);
3794 nodes[0].chan_monitor = &new_chan_monitor;
3795 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3796 let (_, mut chan_0_monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3797 assert!(chan_0_monitor_read.is_empty());
3799 let mut nodes_0_read = &nodes_0_serialized[..];
3800 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3801 let (_, nodes_0_deserialized_tmp) = {
3802 let mut channel_monitors = HashMap::new();
3803 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &mut chan_0_monitor);
3804 <(Sha256dHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3805 default_config: UserConfig::default(),
3806 keys_manager: &keys_manager,
3807 fee_estimator: &fee_estimator,
3808 monitor: nodes[0].chan_monitor,
3809 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3810 logger: Arc::new(test_utils::TestLogger::new()),
3811 channel_monitors: &mut channel_monitors,
3814 nodes_0_deserialized = nodes_0_deserialized_tmp;
3815 assert!(nodes_0_read.is_empty());
3817 assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3818 nodes[0].node = &nodes_0_deserialized;
3819 check_added_monitors!(nodes[0], 1);
3821 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3823 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3824 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
3828 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3829 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3830 let chanmon_cfgs = create_chanmon_cfgs(4);
3831 let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
3832 let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
3833 let fee_estimator: test_utils::TestFeeEstimator;
3834 let new_chan_monitor: test_utils::TestChannelMonitor;
3835 let keys_manager: test_utils::TestKeysInterface;
3836 let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator>;
3837 let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
3838 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
3839 create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::supported(), InitFeatures::supported());
3840 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::supported(), InitFeatures::supported());
3842 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3844 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3845 let nodes_0_serialized = nodes[0].node.encode();
3847 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3848 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3849 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3850 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3852 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3854 let mut node_0_monitors_serialized = Vec::new();
3855 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3856 let mut writer = test_utils::TestVecWriter(Vec::new());
3857 monitor.1.write_for_disk(&mut writer).unwrap();
3858 node_0_monitors_serialized.push(writer.0);
3861 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3862 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);
3863 nodes[0].chan_monitor = &new_chan_monitor;
3864 let mut node_0_monitors = Vec::new();
3865 for serialized in node_0_monitors_serialized.iter() {
3866 let mut read = &serialized[..];
3867 let (_, monitor) = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3868 assert!(read.is_empty());
3869 node_0_monitors.push(monitor);
3872 let mut nodes_0_read = &nodes_0_serialized[..];
3873 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()));
3874 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 {
3875 default_config: UserConfig::default(),
3876 keys_manager: &keys_manager,
3877 fee_estimator: &fee_estimator,
3878 monitor: nodes[0].chan_monitor,
3879 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3880 logger: Arc::new(test_utils::TestLogger::new()),
3881 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
3883 nodes_0_deserialized = nodes_0_deserialized_tmp;
3884 assert!(nodes_0_read.is_empty());
3886 { // Channel close should result in a commitment tx and an HTLC tx
3887 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3888 assert_eq!(txn.len(), 2);
3889 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3890 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3893 for monitor in node_0_monitors.drain(..) {
3894 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
3895 check_added_monitors!(nodes[0], 1);
3897 nodes[0].node = &nodes_0_deserialized;
3899 // nodes[1] and nodes[2] have no lost state with nodes[0]...
3900 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3901 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3902 //... and we can even still claim the payment!
3903 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
3905 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3906 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3907 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3908 nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
3909 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
3910 assert_eq!(msg_events.len(), 1);
3911 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
3913 &ErrorAction::SendErrorMessage { ref msg } => {
3914 assert_eq!(msg.channel_id, channel_id);
3916 _ => panic!("Unexpected event!"),
3921 macro_rules! check_spendable_outputs {
3922 ($node: expr, $der_idx: expr) => {
3924 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3925 let mut txn = Vec::new();
3926 for event in events {
3928 Event::SpendableOutputs { ref outputs } => {
3929 for outp in outputs {
3931 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
3933 previous_output: outpoint.clone(),
3934 script_sig: Script::new(),
3936 witness: Vec::new(),
3939 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3940 value: output.value,
3942 let mut spend_tx = Transaction {
3948 let secp_ctx = Secp256k1::new();
3949 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
3950 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
3951 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3952 let remotesig = secp_ctx.sign(&sighash, key);
3953 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
3954 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3955 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
3958 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
3960 previous_output: outpoint.clone(),
3961 script_sig: Script::new(),
3962 sequence: *to_self_delay as u32,
3963 witness: Vec::new(),
3966 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3967 value: output.value,
3969 let mut spend_tx = Transaction {
3975 let secp_ctx = Secp256k1::new();
3976 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
3977 let local_delaysig = secp_ctx.sign(&sighash, key);
3978 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
3979 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3980 spend_tx.input[0].witness.push(vec!(0));
3981 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
3984 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
3985 let secp_ctx = Secp256k1::new();
3987 previous_output: outpoint.clone(),
3988 script_sig: Script::new(),
3990 witness: Vec::new(),
3993 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3994 value: output.value,
3996 let mut spend_tx = Transaction {
4000 output: vec![outp.clone()],
4003 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4005 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4007 Err(_) => panic!("Your RNG is busted"),
4010 Err(_) => panic!("Your rng is busted"),
4013 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4014 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4015 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4016 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4017 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4018 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4019 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4025 _ => panic!("Unexpected event"),
4034 fn test_claim_sizeable_push_msat() {
4035 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4036 let chanmon_cfgs = create_chanmon_cfgs(2);
4037 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4038 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4039 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4041 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4042 nodes[1].node.force_close_channel(&chan.2);
4043 check_closed_broadcast!(nodes[1], false);
4044 check_added_monitors!(nodes[1], 1);
4045 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4046 assert_eq!(node_txn.len(), 1);
4047 check_spends!(node_txn[0], chan.3);
4048 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
4050 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4051 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4052 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4053 assert_eq!(spend_txn.len(), 1);
4054 check_spends!(spend_txn[0], node_txn[0]);
4058 fn test_claim_on_remote_sizeable_push_msat() {
4059 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4060 // to_remote output is encumbered by a P2WPKH
4061 let chanmon_cfgs = create_chanmon_cfgs(2);
4062 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4063 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4064 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4066 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::supported(), InitFeatures::supported());
4067 nodes[0].node.force_close_channel(&chan.2);
4068 check_closed_broadcast!(nodes[0], false);
4069 check_added_monitors!(nodes[0], 1);
4071 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4072 assert_eq!(node_txn.len(), 1);
4073 check_spends!(node_txn[0], chan.3);
4074 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
4076 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4077 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4078 check_closed_broadcast!(nodes[1], false);
4079 check_added_monitors!(nodes[1], 1);
4080 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4081 assert_eq!(spend_txn.len(), 2);
4082 assert_eq!(spend_txn[0], spend_txn[1]);
4083 check_spends!(spend_txn[0], node_txn[0]);
4087 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4088 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4089 // to_remote output is encumbered by a P2WPKH
4091 let chanmon_cfgs = create_chanmon_cfgs(2);
4092 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4093 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4094 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4096 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::supported(), InitFeatures::supported());
4097 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4098 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4099 assert_eq!(revoked_local_txn[0].input.len(), 1);
4100 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4102 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4103 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4104 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4105 check_closed_broadcast!(nodes[1], false);
4106 check_added_monitors!(nodes[1], 1);
4108 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4109 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4110 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 2);
4112 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4113 assert_eq!(spend_txn.len(), 3);
4114 assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4115 check_spends!(spend_txn[0], revoked_local_txn[0]);
4116 check_spends!(spend_txn[2], node_txn[0]);
4120 fn test_static_spendable_outputs_preimage_tx() {
4121 let chanmon_cfgs = create_chanmon_cfgs(2);
4122 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4123 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4124 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4126 // Create some initial channels
4127 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4129 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4131 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4132 assert_eq!(commitment_tx[0].input.len(), 1);
4133 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4135 // Settle A's commitment tx on B's chain
4136 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4137 assert!(nodes[1].node.claim_funds(payment_preimage, 3_000_000));
4138 check_added_monitors!(nodes[1], 1);
4139 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4140 check_added_monitors!(nodes[1], 1);
4141 let events = nodes[1].node.get_and_clear_pending_msg_events();
4143 MessageSendEvent::UpdateHTLCs { .. } => {},
4144 _ => panic!("Unexpected event"),
4147 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4148 _ => panic!("Unexepected event"),
4151 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4152 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4153 assert_eq!(node_txn.len(), 3);
4154 check_spends!(node_txn[0], commitment_tx[0]);
4155 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4156 check_spends!(node_txn[1], chan_1.3);
4157 check_spends!(node_txn[2], node_txn[1]);
4159 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4160 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4162 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4163 assert_eq!(spend_txn.len(), 1);
4164 check_spends!(spend_txn[0], node_txn[0]);
4168 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4169 let chanmon_cfgs = create_chanmon_cfgs(2);
4170 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4171 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4172 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4174 // Create some initial channels
4175 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4177 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4178 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4179 assert_eq!(revoked_local_txn[0].input.len(), 1);
4180 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4182 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4184 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4185 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4186 check_closed_broadcast!(nodes[1], false);
4187 check_added_monitors!(nodes[1], 1);
4189 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4190 assert_eq!(node_txn.len(), 2);
4191 assert_eq!(node_txn[0].input.len(), 2);
4192 check_spends!(node_txn[0], revoked_local_txn[0]);
4194 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4195 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 2);
4197 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4198 assert_eq!(spend_txn.len(), 1);
4199 check_spends!(spend_txn[0], node_txn[0]);
4203 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4204 let chanmon_cfgs = create_chanmon_cfgs(2);
4205 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4206 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4207 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4209 // Create some initial channels
4210 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4212 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4213 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4214 assert_eq!(revoked_local_txn[0].input.len(), 1);
4215 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4217 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4219 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4220 // A will generate HTLC-Timeout from revoked commitment tx
4221 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4222 check_closed_broadcast!(nodes[0], false);
4223 check_added_monitors!(nodes[0], 1);
4225 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4226 assert_eq!(revoked_htlc_txn.len(), 3);
4227 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
4228 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4229 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4230 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4231 check_spends!(revoked_htlc_txn[1], chan_1.3);
4233 // B will generate justice tx from A's revoked commitment/HTLC tx
4234 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4235 check_closed_broadcast!(nodes[1], false);
4236 check_added_monitors!(nodes[1], 1);
4238 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4239 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
4240 assert_eq!(node_txn[0].input.len(), 2);
4241 check_spends!(node_txn[0], revoked_local_txn[0]);
4242 check_spends!(node_txn[1], chan_1.3);
4243 assert_eq!(node_txn[2].input.len(), 1);
4244 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4245 assert_eq!(node_txn[3].input.len(), 1);
4246 check_spends!(node_txn[3], revoked_local_txn[0]);
4248 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4249 nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4251 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4252 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4253 assert_eq!(spend_txn.len(), 2);
4254 check_spends!(spend_txn[0], node_txn[0]);
4255 check_spends!(spend_txn[1], node_txn[2]);
4259 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4260 let chanmon_cfgs = create_chanmon_cfgs(2);
4261 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4262 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4263 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4265 // Create some initial channels
4266 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4268 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4269 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4270 assert_eq!(revoked_local_txn[0].input.len(), 1);
4271 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4273 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4275 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4276 // B will generate HTLC-Success from revoked commitment tx
4277 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4278 check_closed_broadcast!(nodes[1], false);
4279 check_added_monitors!(nodes[1], 1);
4280 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4282 assert_eq!(revoked_htlc_txn.len(), 3);
4283 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
4284 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4285 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4286 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4288 // A will generate justice tx from B's revoked commitment/HTLC tx
4289 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4290 check_closed_broadcast!(nodes[0], false);
4291 check_added_monitors!(nodes[0], 1);
4293 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4294 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4295 assert_eq!(node_txn[2].input.len(), 1);
4296 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4298 let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4299 nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4301 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4302 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4303 assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4304 assert_eq!(spend_txn[0], spend_txn[1]);
4305 assert_eq!(spend_txn[0], spend_txn[2]);
4306 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4307 check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4308 check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
4312 fn test_onchain_to_onchain_claim() {
4313 // Test that in case of channel closure, we detect the state of output thanks to
4314 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4315 // First, have C claim an HTLC against its own latest commitment transaction.
4316 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4318 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4321 let chanmon_cfgs = create_chanmon_cfgs(3);
4322 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4323 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4324 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4326 // Create some initial channels
4327 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4328 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4330 // Rebalance the network a bit by relaying one payment through all the channels ...
4331 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4332 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4334 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4335 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4336 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4337 check_spends!(commitment_tx[0], chan_2.3);
4338 nodes[2].node.claim_funds(payment_preimage, 3_000_000);
4339 check_added_monitors!(nodes[2], 1);
4340 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4341 assert!(updates.update_add_htlcs.is_empty());
4342 assert!(updates.update_fail_htlcs.is_empty());
4343 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4344 assert!(updates.update_fail_malformed_htlcs.is_empty());
4346 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4347 check_closed_broadcast!(nodes[2], false);
4348 check_added_monitors!(nodes[2], 1);
4350 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4351 assert_eq!(c_txn.len(), 4);
4352 assert_eq!(c_txn[0], c_txn[2]);
4353 assert_eq!(c_txn[0], c_txn[3]);
4354 assert_eq!(commitment_tx[0], c_txn[1]);
4355 check_spends!(c_txn[1], chan_2.3);
4356 check_spends!(c_txn[2], c_txn[1]);
4357 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4358 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4359 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4360 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4362 // 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
4363 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4365 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4366 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4367 assert_eq!(b_txn.len(), 3);
4368 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4369 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4370 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4371 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4372 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4373 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4374 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4375 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4376 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4379 check_added_monitors!(nodes[1], 1);
4380 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4381 check_added_monitors!(nodes[1], 1);
4382 match msg_events[0] {
4383 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4384 _ => panic!("Unexpected event"),
4386 match msg_events[1] {
4387 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, .. } } => {
4388 assert!(update_add_htlcs.is_empty());
4389 assert!(update_fail_htlcs.is_empty());
4390 assert_eq!(update_fulfill_htlcs.len(), 1);
4391 assert!(update_fail_malformed_htlcs.is_empty());
4392 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4394 _ => panic!("Unexpected event"),
4396 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4397 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4398 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4399 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4400 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4401 assert_eq!(b_txn.len(), 3);
4402 check_spends!(b_txn[1], chan_1.3);
4403 check_spends!(b_txn[2], b_txn[1]);
4404 check_spends!(b_txn[0], commitment_tx[0]);
4405 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4406 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4407 assert_eq!(b_txn[0].lock_time, 0); // Success tx
4409 check_closed_broadcast!(nodes[1], false);
4410 check_added_monitors!(nodes[1], 1);
4414 fn test_duplicate_payment_hash_one_failure_one_success() {
4415 // Topology : A --> B --> C
4416 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4417 let chanmon_cfgs = create_chanmon_cfgs(3);
4418 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4419 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4420 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4422 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4423 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4425 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4426 *nodes[0].network_payment_count.borrow_mut() -= 1;
4427 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4429 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4430 assert_eq!(commitment_txn[0].input.len(), 1);
4431 check_spends!(commitment_txn[0], chan_2.3);
4433 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4434 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4435 check_closed_broadcast!(nodes[1], false);
4436 check_added_monitors!(nodes[1], 1);
4438 let htlc_timeout_tx;
4439 { // Extract one of the two HTLC-Timeout transaction
4440 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4441 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4442 assert_eq!(node_txn.len(), 5);
4443 check_spends!(node_txn[0], commitment_txn[0]);
4444 assert_eq!(node_txn[0].input.len(), 1);
4445 check_spends!(node_txn[1], commitment_txn[0]);
4446 assert_eq!(node_txn[1].input.len(), 1);
4447 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4448 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4449 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4450 check_spends!(node_txn[2], chan_2.3);
4451 check_spends!(node_txn[3], node_txn[2]);
4452 check_spends!(node_txn[4], node_txn[2]);
4453 htlc_timeout_tx = node_txn[1].clone();
4456 nodes[2].node.claim_funds(our_payment_preimage, 900_000);
4457 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4458 check_added_monitors!(nodes[2], 3);
4459 let events = nodes[2].node.get_and_clear_pending_msg_events();
4461 MessageSendEvent::UpdateHTLCs { .. } => {},
4462 _ => panic!("Unexpected event"),
4465 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4466 _ => panic!("Unexepected event"),
4468 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4469 assert_eq!(htlc_success_txn.len(), 7);
4470 check_spends!(htlc_success_txn[2], chan_2.3);
4471 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4472 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4473 assert_eq!(htlc_success_txn[0], htlc_success_txn[5]);
4474 assert_eq!(htlc_success_txn[0].input.len(), 1);
4475 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4476 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4477 assert_eq!(htlc_success_txn[1].input.len(), 1);
4478 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4479 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4480 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4481 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4483 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4484 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4485 expect_pending_htlcs_forwardable!(nodes[1]);
4486 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4487 assert!(htlc_updates.update_add_htlcs.is_empty());
4488 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4489 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4490 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4491 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4492 check_added_monitors!(nodes[1], 1);
4494 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4495 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4497 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4498 let events = nodes[0].node.get_and_clear_pending_msg_events();
4499 assert_eq!(events.len(), 1);
4501 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
4503 _ => { panic!("Unexpected event"); }
4506 let events = nodes[0].node.get_and_clear_pending_events();
4508 Event::PaymentFailed { ref payment_hash, .. } => {
4509 assert_eq!(*payment_hash, duplicate_payment_hash);
4511 _ => panic!("Unexpected event"),
4514 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4515 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4516 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4517 assert!(updates.update_add_htlcs.is_empty());
4518 assert!(updates.update_fail_htlcs.is_empty());
4519 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4520 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4521 assert!(updates.update_fail_malformed_htlcs.is_empty());
4522 check_added_monitors!(nodes[1], 1);
4524 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4525 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4527 let events = nodes[0].node.get_and_clear_pending_events();
4529 Event::PaymentSent { ref payment_preimage } => {
4530 assert_eq!(*payment_preimage, our_payment_preimage);
4532 _ => panic!("Unexpected event"),
4537 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4538 let chanmon_cfgs = create_chanmon_cfgs(2);
4539 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4540 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4541 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4543 // Create some initial channels
4544 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4546 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4547 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4548 assert_eq!(local_txn[0].input.len(), 1);
4549 check_spends!(local_txn[0], chan_1.3);
4551 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4552 nodes[1].node.claim_funds(payment_preimage, 9_000_000);
4553 check_added_monitors!(nodes[1], 1);
4554 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4555 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4556 check_added_monitors!(nodes[1], 1);
4557 let events = nodes[1].node.get_and_clear_pending_msg_events();
4559 MessageSendEvent::UpdateHTLCs { .. } => {},
4560 _ => panic!("Unexpected event"),
4563 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4564 _ => panic!("Unexepected event"),
4567 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4568 assert_eq!(node_txn[0].input.len(), 1);
4569 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4570 check_spends!(node_txn[0], local_txn[0]);
4571 vec![node_txn[0].clone(), node_txn[2].clone()]
4574 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4575 nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
4577 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4578 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4579 assert_eq!(spend_txn.len(), 2);
4580 check_spends!(spend_txn[0], node_txn[0]);
4581 check_spends!(spend_txn[1], node_txn[1]);
4584 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4585 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4586 // unrevoked commitment transaction.
4587 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4588 // a remote RAA before they could be failed backwards (and combinations thereof).
4589 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4590 // use the same payment hashes.
4591 // Thus, we use a six-node network:
4596 // And test where C fails back to A/B when D announces its latest commitment transaction
4597 let chanmon_cfgs = create_chanmon_cfgs(6);
4598 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4599 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
4600 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4602 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::supported(), InitFeatures::supported());
4603 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4604 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
4605 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
4606 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
4608 // Rebalance and check output sanity...
4609 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4610 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4611 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
4613 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4615 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
4617 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
4618 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();
4620 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
4622 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
4624 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4626 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4627 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4629 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4631 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4634 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4636 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();
4637 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
4640 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
4642 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4643 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4645 // Double-check that six of the new HTLC were added
4646 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4647 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4648 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
4649 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
4651 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4652 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4653 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
4654 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
4655 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
4656 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
4657 check_added_monitors!(nodes[4], 0);
4658 expect_pending_htlcs_forwardable!(nodes[4]);
4659 check_added_monitors!(nodes[4], 1);
4661 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4662 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4663 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4664 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4665 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4666 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4668 // Fail 3rd below-dust and 7th above-dust HTLCs
4669 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
4670 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
4671 check_added_monitors!(nodes[5], 0);
4672 expect_pending_htlcs_forwardable!(nodes[5]);
4673 check_added_monitors!(nodes[5], 1);
4675 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4676 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4677 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4678 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4680 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4682 expect_pending_htlcs_forwardable!(nodes[3]);
4683 check_added_monitors!(nodes[3], 1);
4684 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4685 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4686 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4687 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4688 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4689 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4690 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4691 if deliver_last_raa {
4692 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4694 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4697 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4698 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4699 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4700 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4702 // We now broadcast the latest commitment transaction, which *should* result in failures for
4703 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4704 // the non-broadcast above-dust HTLCs.
4706 // Alternatively, we may broadcast the previous commitment transaction, which should only
4707 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4708 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4710 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4711 if announce_latest {
4712 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4714 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4716 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4717 check_closed_broadcast!(nodes[2], false);
4718 expect_pending_htlcs_forwardable!(nodes[2]);
4719 check_added_monitors!(nodes[2], 3);
4721 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4722 assert_eq!(cs_msgs.len(), 2);
4723 let mut a_done = false;
4724 for msg in cs_msgs {
4726 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4727 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4728 // should be failed-backwards here.
4729 let target = if *node_id == nodes[0].node.get_our_node_id() {
4730 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4731 for htlc in &updates.update_fail_htlcs {
4732 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 });
4734 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4739 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4740 for htlc in &updates.update_fail_htlcs {
4741 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4743 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4744 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4747 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4748 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
4749 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
4750 if announce_latest {
4751 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
4752 if *node_id == nodes[0].node.get_our_node_id() {
4753 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
4756 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4758 _ => panic!("Unexpected event"),
4762 let as_events = nodes[0].node.get_and_clear_pending_events();
4763 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4764 let mut as_failds = HashSet::new();
4765 for event in as_events.iter() {
4766 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4767 assert!(as_failds.insert(*payment_hash));
4768 if *payment_hash != payment_hash_2 {
4769 assert_eq!(*rejected_by_dest, deliver_last_raa);
4771 assert!(!rejected_by_dest);
4773 } else { panic!("Unexpected event"); }
4775 assert!(as_failds.contains(&payment_hash_1));
4776 assert!(as_failds.contains(&payment_hash_2));
4777 if announce_latest {
4778 assert!(as_failds.contains(&payment_hash_3));
4779 assert!(as_failds.contains(&payment_hash_5));
4781 assert!(as_failds.contains(&payment_hash_6));
4783 let bs_events = nodes[1].node.get_and_clear_pending_events();
4784 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4785 let mut bs_failds = HashSet::new();
4786 for event in bs_events.iter() {
4787 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4788 assert!(bs_failds.insert(*payment_hash));
4789 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4790 assert_eq!(*rejected_by_dest, deliver_last_raa);
4792 assert!(!rejected_by_dest);
4794 } else { panic!("Unexpected event"); }
4796 assert!(bs_failds.contains(&payment_hash_1));
4797 assert!(bs_failds.contains(&payment_hash_2));
4798 if announce_latest {
4799 assert!(bs_failds.contains(&payment_hash_4));
4801 assert!(bs_failds.contains(&payment_hash_5));
4803 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4804 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4805 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4806 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4807 // PaymentFailureNetworkUpdates.
4808 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4809 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4810 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4811 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4812 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4814 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4815 _ => panic!("Unexpected event"),
4821 fn test_fail_backwards_latest_remote_announce_a() {
4822 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4826 fn test_fail_backwards_latest_remote_announce_b() {
4827 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4831 fn test_fail_backwards_previous_remote_announce() {
4832 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4833 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4834 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4838 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4839 let chanmon_cfgs = create_chanmon_cfgs(2);
4840 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4841 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4842 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4844 // Create some initial channels
4845 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4847 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4848 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4849 assert_eq!(local_txn[0].input.len(), 1);
4850 check_spends!(local_txn[0], chan_1.3);
4852 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4853 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4854 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4855 check_closed_broadcast!(nodes[0], false);
4856 check_added_monitors!(nodes[0], 1);
4858 let htlc_timeout = {
4859 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4860 assert_eq!(node_txn[0].input.len(), 1);
4861 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4862 check_spends!(node_txn[0], local_txn[0]);
4866 let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4867 nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
4869 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4870 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4871 assert_eq!(spend_txn.len(), 3);
4872 assert_eq!(spend_txn[0], spend_txn[1]);
4873 check_spends!(spend_txn[0], local_txn[0]);
4874 check_spends!(spend_txn[2], htlc_timeout);
4878 fn test_static_output_closing_tx() {
4879 let chanmon_cfgs = create_chanmon_cfgs(2);
4880 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4881 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4882 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4884 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4886 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4887 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4889 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4890 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4891 let spend_txn = check_spendable_outputs!(nodes[0], 2);
4892 assert_eq!(spend_txn.len(), 1);
4893 check_spends!(spend_txn[0], closing_tx);
4895 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4896 let spend_txn = check_spendable_outputs!(nodes[1], 2);
4897 assert_eq!(spend_txn.len(), 1);
4898 check_spends!(spend_txn[0], closing_tx);
4901 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4902 let chanmon_cfgs = create_chanmon_cfgs(2);
4903 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4904 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4905 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4906 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4908 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4910 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4911 // present in B's local commitment transaction, but none of A's commitment transactions.
4912 assert!(nodes[1].node.claim_funds(our_payment_preimage, if use_dust { 50_000 } else { 3_000_000 }));
4913 check_added_monitors!(nodes[1], 1);
4915 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4916 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
4917 let events = nodes[0].node.get_and_clear_pending_events();
4918 assert_eq!(events.len(), 1);
4920 Event::PaymentSent { payment_preimage } => {
4921 assert_eq!(payment_preimage, our_payment_preimage);
4923 _ => panic!("Unexpected event"),
4926 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4927 check_added_monitors!(nodes[0], 1);
4928 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4929 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4930 check_added_monitors!(nodes[1], 1);
4932 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4933 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4934 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4935 header.prev_blockhash = header.bitcoin_hash();
4937 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4938 check_closed_broadcast!(nodes[1], false);
4939 check_added_monitors!(nodes[1], 1);
4942 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4943 let chanmon_cfgs = create_chanmon_cfgs(2);
4944 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4945 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4946 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4947 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4949 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();
4950 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4951 nodes[0].node.send_payment(route, payment_hash).unwrap();
4952 check_added_monitors!(nodes[0], 1);
4954 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4956 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4957 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4958 // to "time out" the HTLC.
4960 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4962 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4963 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
4964 header.prev_blockhash = header.bitcoin_hash();
4966 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4967 check_closed_broadcast!(nodes[0], false);
4968 check_added_monitors!(nodes[0], 1);
4971 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4972 let chanmon_cfgs = create_chanmon_cfgs(3);
4973 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4974 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4975 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4976 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4978 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4979 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4980 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4981 // actually revoked.
4982 let htlc_value = if use_dust { 50000 } else { 3000000 };
4983 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4984 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4985 expect_pending_htlcs_forwardable!(nodes[1]);
4986 check_added_monitors!(nodes[1], 1);
4988 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4989 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
4990 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4991 check_added_monitors!(nodes[0], 1);
4992 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4993 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4994 check_added_monitors!(nodes[1], 1);
4995 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
4996 check_added_monitors!(nodes[1], 1);
4997 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4999 if check_revoke_no_close {
5000 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5001 check_added_monitors!(nodes[0], 1);
5004 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5005 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5006 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5007 header.prev_blockhash = header.bitcoin_hash();
5009 if !check_revoke_no_close {
5010 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5011 check_closed_broadcast!(nodes[0], false);
5012 check_added_monitors!(nodes[0], 1);
5014 let events = nodes[0].node.get_and_clear_pending_events();
5015 assert_eq!(events.len(), 1);
5017 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
5018 assert_eq!(payment_hash, our_payment_hash);
5019 assert!(rejected_by_dest);
5021 _ => panic!("Unexpected event"),
5026 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5027 // There are only a few cases to test here:
5028 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5029 // broadcastable commitment transactions result in channel closure,
5030 // * its included in an unrevoked-but-previous remote commitment transaction,
5031 // * its included in the latest remote or local commitment transactions.
5032 // We test each of the three possible commitment transactions individually and use both dust and
5034 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5035 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5036 // tested for at least one of the cases in other tests.
5038 fn htlc_claim_single_commitment_only_a() {
5039 do_htlc_claim_local_commitment_only(true);
5040 do_htlc_claim_local_commitment_only(false);
5042 do_htlc_claim_current_remote_commitment_only(true);
5043 do_htlc_claim_current_remote_commitment_only(false);
5047 fn htlc_claim_single_commitment_only_b() {
5048 do_htlc_claim_previous_remote_commitment_only(true, false);
5049 do_htlc_claim_previous_remote_commitment_only(false, false);
5050 do_htlc_claim_previous_remote_commitment_only(true, true);
5051 do_htlc_claim_previous_remote_commitment_only(false, true);
5054 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>)
5055 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5058 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);
5062 // 0: node1 fails backward
5063 // 1: final node fails backward
5064 // 2: payment completed but the user rejects the payment
5065 // 3: final node fails backward (but tamper onion payloads from node0)
5066 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5067 // 200: trigger error in the final node and tamper returning fail_htlc
5068 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>)
5069 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5070 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5074 // reset block height
5075 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5076 for ix in 0..nodes.len() {
5077 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5080 macro_rules! expect_event {
5081 ($node: expr, $event_type: path) => {{
5082 let events = $node.node.get_and_clear_pending_events();
5083 assert_eq!(events.len(), 1);
5085 $event_type { .. } => {},
5086 _ => panic!("Unexpected event"),
5091 macro_rules! expect_htlc_forward {
5093 expect_event!($node, Event::PendingHTLCsForwardable);
5094 $node.node.process_pending_htlc_forwards();
5098 // 0 ~~> 2 send payment
5099 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
5100 check_added_monitors!(nodes[0], 1);
5101 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5102 // temper update_add (0 => 1)
5103 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5104 if test_case == 0 || test_case == 3 || test_case == 100 {
5105 callback_msg(&mut update_add_0);
5108 // 0 => 1 update_add & CS
5109 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5110 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5112 let update_1_0 = match test_case {
5113 0|100 => { // intermediate node failure; fail backward to 0
5114 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5115 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));
5118 1|2|3|200 => { // final node failure; forwarding to 2
5119 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5121 if test_case != 200 {
5124 expect_htlc_forward!(&nodes[1]);
5126 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5127 check_added_monitors!(&nodes[1], 1);
5128 assert_eq!(update_1.update_add_htlcs.len(), 1);
5129 // tamper update_add (1 => 2)
5130 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5131 if test_case != 3 && test_case != 200 {
5132 callback_msg(&mut update_add_1);
5136 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5137 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5139 if test_case == 2 || test_case == 200 {
5140 expect_htlc_forward!(&nodes[2]);
5141 expect_event!(&nodes[2], Event::PaymentReceived);
5143 expect_pending_htlcs_forwardable!(nodes[2]);
5146 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5147 if test_case == 2 || test_case == 200 {
5148 check_added_monitors!(&nodes[2], 1);
5150 assert!(update_2_1.update_fail_htlcs.len() == 1);
5152 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5153 if test_case == 200 {
5154 callback_fail(&mut fail_msg);
5158 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5159 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5161 // backward fail on 1
5162 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5163 assert!(update_1_0.update_fail_htlcs.len() == 1);
5166 _ => unreachable!(),
5169 // 1 => 0 commitment_signed_dance
5170 if update_1_0.update_fail_htlcs.len() > 0 {
5171 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5172 if test_case == 100 {
5173 callback_fail(&mut fail_msg);
5175 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5177 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5180 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5182 let events = nodes[0].node.get_and_clear_pending_events();
5183 assert_eq!(events.len(), 1);
5184 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
5185 assert_eq!(*rejected_by_dest, !expected_retryable);
5186 assert_eq!(*error_code, expected_error_code);
5188 panic!("Uexpected event");
5191 let events = nodes[0].node.get_and_clear_pending_msg_events();
5192 if expected_channel_update.is_some() {
5193 assert_eq!(events.len(), 1);
5195 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5197 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5198 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5199 panic!("channel_update not found!");
5202 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5203 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5204 assert!(*short_channel_id == *expected_short_channel_id);
5205 assert!(*is_permanent == *expected_is_permanent);
5207 panic!("Unexpected message event");
5210 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5211 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5212 assert!(*node_id == *expected_node_id);
5213 assert!(*is_permanent == *expected_is_permanent);
5215 panic!("Unexpected message event");
5220 _ => panic!("Unexpected message event"),
5223 assert_eq!(events.len(), 0);
5227 impl msgs::ChannelUpdate {
5228 fn dummy() -> msgs::ChannelUpdate {
5229 use secp256k1::ffi::Signature as FFISignature;
5230 use secp256k1::Signature;
5231 msgs::ChannelUpdate {
5232 signature: Signature::from(FFISignature::new()),
5233 contents: msgs::UnsignedChannelUpdate {
5234 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
5235 short_channel_id: 0,
5238 cltv_expiry_delta: 0,
5239 htlc_minimum_msat: 0,
5241 fee_proportional_millionths: 0,
5242 excess_data: vec![],
5248 struct BogusOnionHopData {
5251 impl BogusOnionHopData {
5252 fn new(orig: msgs::OnionHopData) -> Self {
5253 Self { data: orig.encode() }
5256 impl Writeable for BogusOnionHopData {
5257 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5258 writer.write_all(&self.data[..])
5263 fn test_onion_failure() {
5264 use ln::msgs::ChannelUpdate;
5265 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5268 const BADONION: u16 = 0x8000;
5269 const PERM: u16 = 0x4000;
5270 const NODE: u16 = 0x2000;
5271 const UPDATE: u16 = 0x1000;
5273 let chanmon_cfgs = create_chanmon_cfgs(3);
5274 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5275 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5276 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5277 for node in nodes.iter() {
5278 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5280 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())];
5281 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5282 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
5284 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5286 // intermediate node failure
5287 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5288 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5289 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5290 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5291 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5292 let mut new_payloads = Vec::new();
5293 for payload in onion_payloads.drain(..) {
5294 new_payloads.push(BogusOnionHopData::new(payload));
5296 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5297 // describing a length-1 TLV payload, which is obviously bogus.
5298 new_payloads[0].data[0] = 1;
5299 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5300 }, ||{}, 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
5302 // final node failure
5303 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5304 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5305 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5306 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5307 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5308 let mut new_payloads = Vec::new();
5309 for payload in onion_payloads.drain(..) {
5310 new_payloads.push(BogusOnionHopData::new(payload));
5312 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5313 // length-1 TLV payload, which is obviously bogus.
5314 new_payloads[1].data[0] = 1;
5315 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5316 }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5318 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5319 // receiving simulated fail messages
5320 // intermediate node failure
5321 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5323 msg.amount_msat -= 1;
5325 // and tamper returning error message
5326 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5327 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5328 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5329 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
5331 // final node failure
5332 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5333 // and tamper returning error message
5334 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5335 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5336 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5338 nodes[2].node.fail_htlc_backwards(&payment_hash);
5339 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
5341 // intermediate node failure
5342 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5343 msg.amount_msat -= 1;
5345 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5346 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5347 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5348 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
5350 // final node failure
5351 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5352 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5353 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5354 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5356 nodes[2].node.fail_htlc_backwards(&payment_hash);
5357 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
5359 // intermediate node failure
5360 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5361 msg.amount_msat -= 1;
5363 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5364 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5365 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5367 nodes[2].node.fail_htlc_backwards(&payment_hash);
5368 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
5370 // final node failure
5371 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5372 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5373 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5374 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5376 nodes[2].node.fail_htlc_backwards(&payment_hash);
5377 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
5379 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5380 Some(BADONION|PERM|4), None);
5382 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5383 Some(BADONION|PERM|5), None);
5385 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5386 Some(BADONION|PERM|6), None);
5388 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5389 msg.amount_msat -= 1;
5391 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5392 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5393 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5394 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5396 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5397 msg.amount_msat -= 1;
5399 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5400 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5401 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5402 // short_channel_id from the processing node
5403 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5405 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5406 msg.amount_msat -= 1;
5408 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5409 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5410 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5411 // short_channel_id from the processing node
5412 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5414 let mut bogus_route = route.clone();
5415 bogus_route.hops[1].short_channel_id -= 1;
5416 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5417 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
5419 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5420 let mut bogus_route = route.clone();
5421 let route_len = bogus_route.hops.len();
5422 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
5423 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5425 //TODO: with new config API, we will be able to generate both valid and
5426 //invalid channel_update cases.
5427 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5428 msg.amount_msat -= 1;
5429 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5431 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5432 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5433 msg.cltv_expiry -= 1;
5434 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5436 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5437 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5438 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5440 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5441 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5443 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5444 nodes[2].node.fail_htlc_backwards(&payment_hash);
5445 }, false, Some(PERM|15), None);
5447 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5448 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5449 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5451 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5452 }, || {}, true, Some(17), None);
5454 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5455 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5456 for f in pending_forwards.iter_mut() {
5458 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5459 forward_info.outgoing_cltv_value += 1,
5464 }, true, Some(18), None);
5466 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5467 // violate amt_to_forward > msg.amount_msat
5468 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5469 for f in pending_forwards.iter_mut() {
5471 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5472 forward_info.amt_to_forward -= 1,
5477 }, true, Some(19), None);
5479 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5480 // disconnect event to the channel between nodes[1] ~ nodes[2]
5481 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5482 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5483 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5484 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5486 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5487 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5488 let mut route = route.clone();
5490 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
5491 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5492 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
5493 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5494 msg.cltv_expiry = htlc_cltv;
5495 msg.onion_routing_packet = onion_packet;
5496 }, ||{}, true, Some(21), None);
5501 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5502 let chanmon_cfgs = create_chanmon_cfgs(2);
5503 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5504 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5505 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5506 //Force duplicate channel ids
5507 for node in nodes.iter() {
5508 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5511 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5512 let channel_value_satoshis=10000;
5513 let push_msat=10001;
5514 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5515 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5516 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &node0_to_1_send_open_channel);
5518 //Create a second channel with a channel_id collision
5519 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5523 fn bolt2_open_channel_sending_node_checks_part2() {
5524 let chanmon_cfgs = create_chanmon_cfgs(2);
5525 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5526 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5527 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5529 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5530 let channel_value_satoshis=2^24;
5531 let push_msat=10001;
5532 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5534 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5535 let channel_value_satoshis=10000;
5536 // Test when push_msat is equal to 1000 * funding_satoshis.
5537 let push_msat=1000*channel_value_satoshis+1;
5538 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5540 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5541 let channel_value_satoshis=10000;
5542 let push_msat=10001;
5543 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
5544 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5545 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5547 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5548 // 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
5549 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5551 // 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.
5552 assert!(BREAKDOWN_TIMEOUT>0);
5553 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5555 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5556 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5557 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5559 // 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.
5560 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5561 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5562 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5563 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
5564 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5567 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5568 // 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.
5569 //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.
5572 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5573 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5574 let chanmon_cfgs = create_chanmon_cfgs(2);
5575 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5576 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5577 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5578 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5579 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5580 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5582 route.hops[0].fee_msat = 100;
5584 let err = nodes[0].node.send_payment(route, our_payment_hash);
5586 if let Err(APIError::ChannelUnavailable{err}) = err {
5587 assert_eq!(err, "Cannot send less than their minimum HTLC value");
5591 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5592 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5596 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5597 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5598 let chanmon_cfgs = create_chanmon_cfgs(2);
5599 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5600 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5601 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5602 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5603 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5604 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5606 route.hops[0].fee_msat = 0;
5608 let err = nodes[0].node.send_payment(route, our_payment_hash);
5610 if let Err(APIError::ChannelUnavailable{err}) = err {
5611 assert_eq!(err, "Cannot send 0-msat HTLC");
5615 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5616 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5620 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5621 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5622 let chanmon_cfgs = create_chanmon_cfgs(2);
5623 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5624 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5625 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5626 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5627 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5628 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5630 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5631 check_added_monitors!(nodes[0], 1);
5632 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5633 updates.update_add_htlcs[0].amount_msat = 0;
5635 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5636 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5637 check_closed_broadcast!(nodes[1], true).unwrap();
5638 check_added_monitors!(nodes[1], 1);
5642 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5643 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5644 //It is enforced when constructing a route.
5645 let chanmon_cfgs = create_chanmon_cfgs(2);
5646 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5647 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5648 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5649 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::supported(), InitFeatures::supported());
5650 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5651 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5653 let err = nodes[0].node.send_payment(route, our_payment_hash);
5655 if let Err(APIError::RouteError{err}) = err {
5656 assert_eq!(err, "Channel CLTV overflowed?!");
5663 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5664 //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.
5665 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5666 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5667 let chanmon_cfgs = create_chanmon_cfgs(2);
5668 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5669 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5670 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5671 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::supported(), InitFeatures::supported());
5672 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5674 for i in 0..max_accepted_htlcs {
5675 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5676 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5677 let payment_event = {
5678 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5679 check_added_monitors!(nodes[0], 1);
5681 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5682 assert_eq!(events.len(), 1);
5683 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5684 assert_eq!(htlcs[0].htlc_id, i);
5688 SendEvent::from_event(events.remove(0))
5690 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5691 check_added_monitors!(nodes[1], 0);
5692 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5694 expect_pending_htlcs_forwardable!(nodes[1]);
5695 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5697 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5698 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5699 let err = nodes[0].node.send_payment(route, our_payment_hash);
5701 if let Err(APIError::ChannelUnavailable{err}) = err {
5702 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
5706 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5707 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
5711 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5712 //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.
5713 let chanmon_cfgs = create_chanmon_cfgs(2);
5714 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5715 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5716 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5717 let channel_value = 100000;
5718 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::supported(), InitFeatures::supported());
5719 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5721 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5723 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5724 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5725 let err = nodes[0].node.send_payment(route, our_payment_hash);
5727 if let Err(APIError::ChannelUnavailable{err}) = err {
5728 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept");
5732 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5733 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);
5735 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5738 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5740 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5741 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5742 let chanmon_cfgs = create_chanmon_cfgs(2);
5743 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5744 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5745 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5746 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5747 let htlc_minimum_msat: u64;
5749 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5750 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5751 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5753 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5754 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5755 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5756 check_added_monitors!(nodes[0], 1);
5757 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5758 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5759 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5760 assert!(nodes[1].node.list_channels().is_empty());
5761 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5762 assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
5763 check_added_monitors!(nodes[1], 1);
5767 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5768 //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
5769 let chanmon_cfgs = create_chanmon_cfgs(2);
5770 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5771 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5772 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5773 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5775 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5777 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5778 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5779 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5780 check_added_monitors!(nodes[0], 1);
5781 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5783 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5784 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5786 assert!(nodes[1].node.list_channels().is_empty());
5787 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5788 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
5789 check_added_monitors!(nodes[1], 1);
5793 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5794 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5795 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5796 let chanmon_cfgs = create_chanmon_cfgs(2);
5797 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5798 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5799 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5800 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5801 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5802 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5804 let session_priv = SecretKey::from_slice(&{
5805 let mut session_key = [0; 32];
5806 let mut rng = thread_rng();
5807 rng.fill_bytes(&mut session_key);
5809 }).expect("RNG is bad!");
5811 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5812 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
5813 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5814 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
5816 let mut msg = msgs::UpdateAddHTLC {
5820 payment_hash: our_payment_hash,
5821 cltv_expiry: htlc_cltv,
5822 onion_routing_packet: onion_packet.clone(),
5825 for i in 0..super::channel::OUR_MAX_HTLCS {
5826 msg.htlc_id = i as u64;
5827 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5829 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5830 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5832 assert!(nodes[1].node.list_channels().is_empty());
5833 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5834 assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
5835 check_added_monitors!(nodes[1], 1);
5839 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5840 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5841 let chanmon_cfgs = create_chanmon_cfgs(2);
5842 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5843 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5844 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5845 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
5846 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5847 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5848 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5849 check_added_monitors!(nodes[0], 1);
5850 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5851 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5852 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5854 assert!(nodes[1].node.list_channels().is_empty());
5855 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5856 assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
5857 check_added_monitors!(nodes[1], 1);
5861 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5862 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
5863 let chanmon_cfgs = create_chanmon_cfgs(2);
5864 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5865 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5866 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5867 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5868 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5869 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5870 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5871 check_added_monitors!(nodes[0], 1);
5872 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5873 updates.update_add_htlcs[0].cltv_expiry = 500000000;
5874 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5876 assert!(nodes[1].node.list_channels().is_empty());
5877 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5878 assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
5879 check_added_monitors!(nodes[1], 1);
5883 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5884 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5885 // We test this by first testing that that repeated HTLCs pass commitment signature checks
5886 // after disconnect and that non-sequential htlc_ids result in a channel failure.
5887 let chanmon_cfgs = create_chanmon_cfgs(2);
5888 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5889 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5890 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5891 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5892 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5893 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5894 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5895 check_added_monitors!(nodes[0], 1);
5896 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5897 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5899 //Disconnect and Reconnect
5900 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5901 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5902 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5903 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5904 assert_eq!(reestablish_1.len(), 1);
5905 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5906 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5907 assert_eq!(reestablish_2.len(), 1);
5908 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
5909 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5910 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
5911 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5914 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5915 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5916 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
5917 check_added_monitors!(nodes[1], 1);
5918 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5920 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5922 assert!(nodes[1].node.list_channels().is_empty());
5923 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5924 assert_eq!(err_msg.data, "Remote skipped HTLC ID");
5925 check_added_monitors!(nodes[1], 1);
5929 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5930 //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.
5932 let chanmon_cfgs = create_chanmon_cfgs(2);
5933 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5934 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5935 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5936 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5938 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5939 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5940 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5941 check_added_monitors!(nodes[0], 1);
5942 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5943 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5945 let update_msg = msgs::UpdateFulfillHTLC{
5948 payment_preimage: our_payment_preimage,
5951 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5953 assert!(nodes[0].node.list_channels().is_empty());
5954 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5955 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5956 check_added_monitors!(nodes[0], 1);
5960 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5961 //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.
5963 let chanmon_cfgs = create_chanmon_cfgs(2);
5964 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5965 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5966 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5967 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5969 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5970 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5971 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5972 check_added_monitors!(nodes[0], 1);
5973 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5974 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5976 let update_msg = msgs::UpdateFailHTLC{
5979 reason: msgs::OnionErrorPacket { data: Vec::new()},
5982 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5984 assert!(nodes[0].node.list_channels().is_empty());
5985 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5986 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5987 check_added_monitors!(nodes[0], 1);
5991 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5992 //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.
5994 let chanmon_cfgs = create_chanmon_cfgs(2);
5995 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5996 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5997 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5998 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6000 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6001 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6002 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6003 check_added_monitors!(nodes[0], 1);
6004 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6005 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6007 let update_msg = msgs::UpdateFailMalformedHTLC{
6010 sha256_of_onion: [1; 32],
6011 failure_code: 0x8000,
6014 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6016 assert!(nodes[0].node.list_channels().is_empty());
6017 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6018 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6019 check_added_monitors!(nodes[0], 1);
6023 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6024 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6026 let chanmon_cfgs = create_chanmon_cfgs(2);
6027 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6028 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6029 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6030 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6032 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6034 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
6035 check_added_monitors!(nodes[1], 1);
6037 let events = nodes[1].node.get_and_clear_pending_msg_events();
6038 assert_eq!(events.len(), 1);
6039 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6041 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, .. } } => {
6042 assert!(update_add_htlcs.is_empty());
6043 assert_eq!(update_fulfill_htlcs.len(), 1);
6044 assert!(update_fail_htlcs.is_empty());
6045 assert!(update_fail_malformed_htlcs.is_empty());
6046 assert!(update_fee.is_none());
6047 update_fulfill_htlcs[0].clone()
6049 _ => panic!("Unexpected event"),
6053 update_fulfill_msg.htlc_id = 1;
6055 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6057 assert!(nodes[0].node.list_channels().is_empty());
6058 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6059 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6060 check_added_monitors!(nodes[0], 1);
6064 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6065 //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.
6067 let chanmon_cfgs = create_chanmon_cfgs(2);
6068 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6069 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6070 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6071 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6073 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6075 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
6076 check_added_monitors!(nodes[1], 1);
6078 let events = nodes[1].node.get_and_clear_pending_msg_events();
6079 assert_eq!(events.len(), 1);
6080 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6082 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, .. } } => {
6083 assert!(update_add_htlcs.is_empty());
6084 assert_eq!(update_fulfill_htlcs.len(), 1);
6085 assert!(update_fail_htlcs.is_empty());
6086 assert!(update_fail_malformed_htlcs.is_empty());
6087 assert!(update_fee.is_none());
6088 update_fulfill_htlcs[0].clone()
6090 _ => panic!("Unexpected event"),
6094 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6096 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6098 assert!(nodes[0].node.list_channels().is_empty());
6099 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6100 assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6101 check_added_monitors!(nodes[0], 1);
6105 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6106 //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.
6108 let chanmon_cfgs = create_chanmon_cfgs(2);
6109 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6110 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6111 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6112 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6113 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6114 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6115 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6116 check_added_monitors!(nodes[0], 1);
6118 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6119 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6121 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6122 check_added_monitors!(nodes[1], 0);
6123 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6125 let events = nodes[1].node.get_and_clear_pending_msg_events();
6127 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6129 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, .. } } => {
6130 assert!(update_add_htlcs.is_empty());
6131 assert!(update_fulfill_htlcs.is_empty());
6132 assert!(update_fail_htlcs.is_empty());
6133 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6134 assert!(update_fee.is_none());
6135 update_fail_malformed_htlcs[0].clone()
6137 _ => panic!("Unexpected event"),
6140 update_msg.failure_code &= !0x8000;
6141 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6143 assert!(nodes[0].node.list_channels().is_empty());
6144 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6145 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6146 check_added_monitors!(nodes[0], 1);
6150 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6151 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6152 // * 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.
6154 let chanmon_cfgs = create_chanmon_cfgs(3);
6155 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6156 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6157 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6158 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6159 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6161 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
6162 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6165 let mut payment_event = {
6166 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6167 check_added_monitors!(nodes[0], 1);
6168 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6169 assert_eq!(events.len(), 1);
6170 SendEvent::from_event(events.remove(0))
6172 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6173 check_added_monitors!(nodes[1], 0);
6174 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6175 expect_pending_htlcs_forwardable!(nodes[1]);
6176 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6177 assert_eq!(events_2.len(), 1);
6178 check_added_monitors!(nodes[1], 1);
6179 payment_event = SendEvent::from_event(events_2.remove(0));
6180 assert_eq!(payment_event.msgs.len(), 1);
6183 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6184 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6185 check_added_monitors!(nodes[2], 0);
6186 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6188 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6189 assert_eq!(events_3.len(), 1);
6190 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6192 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 } } => {
6193 assert!(update_add_htlcs.is_empty());
6194 assert!(update_fulfill_htlcs.is_empty());
6195 assert!(update_fail_htlcs.is_empty());
6196 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6197 assert!(update_fee.is_none());
6198 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6200 _ => panic!("Unexpected event"),
6204 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6206 check_added_monitors!(nodes[1], 0);
6207 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6208 expect_pending_htlcs_forwardable!(nodes[1]);
6209 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6210 assert_eq!(events_4.len(), 1);
6212 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6214 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, .. } } => {
6215 assert!(update_add_htlcs.is_empty());
6216 assert!(update_fulfill_htlcs.is_empty());
6217 assert_eq!(update_fail_htlcs.len(), 1);
6218 assert!(update_fail_malformed_htlcs.is_empty());
6219 assert!(update_fee.is_none());
6221 _ => panic!("Unexpected event"),
6224 check_added_monitors!(nodes[1], 1);
6227 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6228 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6229 // 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
6230 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6232 let chanmon_cfgs = create_chanmon_cfgs(2);
6233 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6234 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6235 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6236 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6238 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6240 // We route 2 dust-HTLCs between A and B
6241 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6242 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6243 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6245 // Cache one local commitment tx as previous
6246 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6248 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6249 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6250 check_added_monitors!(nodes[1], 0);
6251 expect_pending_htlcs_forwardable!(nodes[1]);
6252 check_added_monitors!(nodes[1], 1);
6254 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6255 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6256 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6257 check_added_monitors!(nodes[0], 1);
6259 // Cache one local commitment tx as lastest
6260 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6262 let events = nodes[0].node.get_and_clear_pending_msg_events();
6264 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6265 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6267 _ => panic!("Unexpected event"),
6270 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6271 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6273 _ => panic!("Unexpected event"),
6276 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6277 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6278 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6280 if announce_latest {
6281 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6283 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6286 check_closed_broadcast!(nodes[0], false);
6287 check_added_monitors!(nodes[0], 1);
6289 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6290 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
6291 let events = nodes[0].node.get_and_clear_pending_events();
6292 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6293 assert_eq!(events.len(), 2);
6294 let mut first_failed = false;
6295 for event in events {
6297 Event::PaymentFailed { payment_hash, .. } => {
6298 if payment_hash == payment_hash_1 {
6299 assert!(!first_failed);
6300 first_failed = true;
6302 assert_eq!(payment_hash, payment_hash_2);
6305 _ => panic!("Unexpected event"),
6311 fn test_failure_delay_dust_htlc_local_commitment() {
6312 do_test_failure_delay_dust_htlc_local_commitment(true);
6313 do_test_failure_delay_dust_htlc_local_commitment(false);
6317 fn test_no_failure_dust_htlc_local_commitment() {
6318 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6319 // prone to error, we test here that a dummy transaction don't fail them.
6321 let chanmon_cfgs = create_chanmon_cfgs(2);
6322 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6323 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6324 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6325 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6328 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6330 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6331 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6333 // We route 2 dust-HTLCs between A and B
6334 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6335 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6337 // Build a dummy invalid transaction trying to spend a commitment tx
6339 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6340 script_sig: Script::new(),
6342 witness: Vec::new(),
6346 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6350 let dummy_tx = Transaction {
6357 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6358 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6359 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6360 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6361 // We broadcast a few more block to check everything is all right
6362 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.bitcoin_hash());
6363 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6364 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6366 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6367 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6370 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6371 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6372 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6373 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6374 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6375 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6376 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6378 let chanmon_cfgs = create_chanmon_cfgs(3);
6379 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6380 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6381 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6382 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6384 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6386 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6387 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6389 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6390 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6392 // We revoked bs_commitment_tx
6394 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6395 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6398 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6399 let mut timeout_tx = Vec::new();
6401 // We fail dust-HTLC 1 by broadcast of local commitment tx
6402 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6403 check_closed_broadcast!(nodes[0], false);
6404 check_added_monitors!(nodes[0], 1);
6405 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6406 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6407 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6408 let events = nodes[0].node.get_and_clear_pending_events();
6409 assert_eq!(events.len(), 1);
6411 Event::PaymentFailed { payment_hash, .. } => {
6412 assert_eq!(payment_hash, dust_hash);
6414 _ => panic!("Unexpected event"),
6416 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6417 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6418 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6419 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6420 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6421 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6422 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6423 let events = nodes[0].node.get_and_clear_pending_events();
6424 assert_eq!(events.len(), 1);
6426 Event::PaymentFailed { payment_hash, .. } => {
6427 assert_eq!(payment_hash, non_dust_hash);
6429 _ => panic!("Unexpected event"),
6432 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6433 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6434 check_closed_broadcast!(nodes[0], false);
6435 check_added_monitors!(nodes[0], 1);
6436 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6437 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6438 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6439 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6441 let events = nodes[0].node.get_and_clear_pending_events();
6442 assert_eq!(events.len(), 1);
6444 Event::PaymentFailed { payment_hash, .. } => {
6445 assert_eq!(payment_hash, dust_hash);
6447 _ => panic!("Unexpected event"),
6449 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6450 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6451 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6452 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6453 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6454 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6455 let events = nodes[0].node.get_and_clear_pending_events();
6456 assert_eq!(events.len(), 1);
6458 Event::PaymentFailed { payment_hash, .. } => {
6459 assert_eq!(payment_hash, non_dust_hash);
6461 _ => panic!("Unexpected event"),
6464 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6466 let events = nodes[0].node.get_and_clear_pending_events();
6467 assert_eq!(events.len(), 2);
6470 Event::PaymentFailed { payment_hash, .. } => {
6471 if payment_hash == dust_hash { first = true; }
6472 else { first = false; }
6474 _ => panic!("Unexpected event"),
6477 Event::PaymentFailed { payment_hash, .. } => {
6478 if first { assert_eq!(payment_hash, non_dust_hash); }
6479 else { assert_eq!(payment_hash, dust_hash); }
6481 _ => panic!("Unexpected event"),
6488 fn test_sweep_outbound_htlc_failure_update() {
6489 do_test_sweep_outbound_htlc_failure_update(false, true);
6490 do_test_sweep_outbound_htlc_failure_update(false, false);
6491 do_test_sweep_outbound_htlc_failure_update(true, false);
6495 fn test_upfront_shutdown_script() {
6496 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6497 // enforce it at shutdown message
6499 let mut config = UserConfig::default();
6500 config.channel_options.announced_channel = true;
6501 config.peer_channel_config_limits.force_announced_channel_preference = false;
6502 config.channel_options.commit_upfront_shutdown_pubkey = false;
6503 let user_cfgs = [None, Some(config), None];
6504 let chanmon_cfgs = create_chanmon_cfgs(3);
6505 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6506 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6507 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6509 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6510 let flags = InitFeatures::supported();
6511 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6512 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6513 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6514 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6515 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
6516 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6517 assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6518 check_added_monitors!(nodes[2], 1);
6520 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6521 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6522 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6523 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6524 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6525 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6526 let events = nodes[2].node.get_and_clear_pending_msg_events();
6527 assert_eq!(events.len(), 1);
6529 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6530 _ => panic!("Unexpected event"),
6533 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6534 let mut flags_no = InitFeatures::supported();
6535 flags_no.unset_upfront_shutdown_script();
6536 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6537 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6538 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6539 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6540 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6541 let events = nodes[1].node.get_and_clear_pending_msg_events();
6542 assert_eq!(events.len(), 1);
6544 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6545 _ => panic!("Unexpected event"),
6548 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6549 // channel smoothly, opt-out is from channel initiator here
6550 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6551 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6552 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6553 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6554 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6555 let events = nodes[0].node.get_and_clear_pending_msg_events();
6556 assert_eq!(events.len(), 1);
6558 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6559 _ => panic!("Unexpected event"),
6562 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6563 //// channel smoothly
6564 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6565 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6566 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6567 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6568 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6569 let events = nodes[0].node.get_and_clear_pending_msg_events();
6570 assert_eq!(events.len(), 2);
6572 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6573 _ => panic!("Unexpected event"),
6576 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6577 _ => panic!("Unexpected event"),
6582 fn test_user_configurable_csv_delay() {
6583 // We test our channel constructors yield errors when we pass them absurd csv delay
6585 let mut low_our_to_self_config = UserConfig::default();
6586 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6587 let mut high_their_to_self_config = UserConfig::default();
6588 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6589 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6590 let chanmon_cfgs = create_chanmon_cfgs(2);
6591 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6592 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6593 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6595 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6596 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())));
6597 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) {
6599 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6600 _ => panic!("Unexpected event"),
6602 } else { assert!(false) }
6604 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6605 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6606 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6607 open_channel.to_self_delay = 200;
6608 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) {
6610 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6611 _ => panic!("Unexpected event"),
6613 } else { assert!(false); }
6615 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6616 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6617 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()));
6618 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6619 accept_channel.to_self_delay = 200;
6620 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::supported(), &accept_channel);
6621 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6623 &ErrorAction::SendErrorMessage { ref msg } => {
6624 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6626 _ => { assert!(false); }
6628 } else { assert!(false); }
6630 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6631 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6632 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6633 open_channel.to_self_delay = 200;
6634 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) {
6636 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6637 _ => panic!("Unexpected event"),
6639 } else { assert!(false); }
6643 fn test_data_loss_protect() {
6644 // We want to be sure that :
6645 // * we don't broadcast our Local Commitment Tx in case of fallen behind
6646 // * we close channel in case of detecting other being fallen behind
6647 // * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6653 let chanmon_cfgs = create_chanmon_cfgs(2);
6654 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6655 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6656 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6658 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6660 // Cache node A state before any channel update
6661 let previous_node_state = nodes[0].node.encode();
6662 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6663 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6665 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6666 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6668 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6669 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6671 // Restore node A from previous state
6672 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6673 let mut chan_monitor = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6674 let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6675 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
6676 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
6677 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger));
6678 monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), &tx_broadcaster, logger.clone(), &fee_estimator);
6680 let mut channel_monitors = HashMap::new();
6681 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
6682 <(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 {
6683 keys_manager: &keys_manager,
6684 fee_estimator: &fee_estimator,
6686 logger: Arc::clone(&logger),
6687 tx_broadcaster: &tx_broadcaster,
6688 default_config: UserConfig::default(),
6689 channel_monitors: &mut channel_monitors,
6692 nodes[0].node = &node_state_0;
6693 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
6694 nodes[0].chan_monitor = &monitor;
6695 nodes[0].chain_monitor = chain_monitor;
6697 nodes[0].block_notifier = BlockNotifier::new(nodes[0].chain_monitor.clone());
6698 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
6699 nodes[0].block_notifier.register_listener(nodes[0].node);
6701 check_added_monitors!(nodes[0], 1);
6703 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6704 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6706 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6708 // Check we update monitor following learning of per_commitment_point from B
6709 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6710 check_added_monitors!(nodes[0], 2);
6713 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6714 assert_eq!(node_txn.len(), 0);
6717 let mut reestablish_1 = Vec::with_capacity(1);
6718 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6719 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6720 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6721 reestablish_1.push(msg.clone());
6722 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6723 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
6725 &ErrorAction::SendErrorMessage { ref msg } => {
6726 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");
6728 _ => panic!("Unexpected event!"),
6731 panic!("Unexpected event")
6735 // Check we close channel detecting A is fallen-behind
6736 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6737 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
6738 check_added_monitors!(nodes[1], 1);
6741 // Check A is able to claim to_remote output
6742 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6743 assert_eq!(node_txn.len(), 1);
6744 check_spends!(node_txn[0], chan.3);
6745 assert_eq!(node_txn[0].output.len(), 2);
6746 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6747 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 1);
6748 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6749 assert_eq!(spend_txn.len(), 1);
6750 check_spends!(spend_txn[0], node_txn[0]);
6754 fn test_check_htlc_underpaying() {
6755 // Send payment through A -> B but A is maliciously
6756 // sending a probe payment (i.e less than expected value0
6757 // to B, B should refuse payment.
6759 let chanmon_cfgs = create_chanmon_cfgs(2);
6760 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6761 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6762 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6764 // Create some initial channels
6765 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6767 let (payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
6769 // Node 3 is expecting payment of 100_000 but receive 10_000,
6770 // fail htlc like we didn't know the preimage.
6771 nodes[1].node.claim_funds(payment_preimage, 100_000);
6772 nodes[1].node.process_pending_htlc_forwards();
6774 let events = nodes[1].node.get_and_clear_pending_msg_events();
6775 assert_eq!(events.len(), 1);
6776 let (update_fail_htlc, commitment_signed) = match events[0] {
6777 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 } } => {
6778 assert!(update_add_htlcs.is_empty());
6779 assert!(update_fulfill_htlcs.is_empty());
6780 assert_eq!(update_fail_htlcs.len(), 1);
6781 assert!(update_fail_malformed_htlcs.is_empty());
6782 assert!(update_fee.is_none());
6783 (update_fail_htlcs[0].clone(), commitment_signed)
6785 _ => panic!("Unexpected event"),
6787 check_added_monitors!(nodes[1], 1);
6789 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6790 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6792 let events = nodes[0].node.get_and_clear_pending_events();
6793 assert_eq!(events.len(), 1);
6794 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
6795 assert_eq!(*rejected_by_dest, true);
6796 assert_eq!(error_code.unwrap(), 0x4000|15);
6798 panic!("Unexpected event");
6800 nodes[1].node.get_and_clear_pending_events();
6804 fn test_announce_disable_channels() {
6805 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
6806 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6808 let chanmon_cfgs = create_chanmon_cfgs(2);
6809 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6810 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6811 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6813 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6814 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6815 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6818 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6819 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6821 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
6822 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
6823 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6824 assert_eq!(msg_events.len(), 3);
6825 for e in msg_events {
6827 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6828 let short_id = msg.contents.short_channel_id;
6829 // Check generated channel_update match list in PendingChannelUpdate
6830 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
6831 panic!("Generated ChannelUpdate for wrong chan!");
6834 _ => panic!("Unexpected event"),
6838 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6839 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6840 assert_eq!(reestablish_1.len(), 3);
6841 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6842 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6843 assert_eq!(reestablish_2.len(), 3);
6845 // Reestablish chan_1
6846 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6847 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6848 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6849 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6850 // Reestablish chan_2
6851 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
6852 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6853 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
6854 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6855 // Reestablish chan_3
6856 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
6857 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6858 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
6859 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6861 nodes[0].node.timer_chan_freshness_every_min();
6862 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6866 fn test_bump_penalty_txn_on_revoked_commitment() {
6867 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
6868 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
6870 let chanmon_cfgs = create_chanmon_cfgs(2);
6871 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6872 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6873 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6875 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6876 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6877 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30).unwrap();
6878 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
6880 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
6881 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
6882 assert_eq!(revoked_txn[0].output.len(), 4);
6883 assert_eq!(revoked_txn[0].input.len(), 1);
6884 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
6885 let revoked_txid = revoked_txn[0].txid();
6887 let mut penalty_sum = 0;
6888 for outp in revoked_txn[0].output.iter() {
6889 if outp.script_pubkey.is_v0_p2wsh() {
6890 penalty_sum += outp.value;
6894 // Connect blocks to change height_timer range to see if we use right soonest_timelock
6895 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
6897 // Actually revoke tx by claiming a HTLC
6898 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6899 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6900 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
6901 check_added_monitors!(nodes[1], 1);
6903 // One or more justice tx should have been broadcast, check it
6907 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6908 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
6909 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6910 assert_eq!(node_txn[0].output.len(), 1);
6911 check_spends!(node_txn[0], revoked_txn[0]);
6912 let fee_1 = penalty_sum - node_txn[0].output[0].value;
6913 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
6914 penalty_1 = node_txn[0].txid();
6918 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
6919 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.bitcoin_hash());
6920 let mut penalty_2 = penalty_1;
6921 let mut feerate_2 = 0;
6923 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6924 assert_eq!(node_txn.len(), 1);
6925 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6926 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6927 assert_eq!(node_txn[0].output.len(), 1);
6928 check_spends!(node_txn[0], revoked_txn[0]);
6929 penalty_2 = node_txn[0].txid();
6930 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6931 assert_ne!(penalty_2, penalty_1);
6932 let fee_2 = penalty_sum - node_txn[0].output[0].value;
6933 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
6934 // Verify 25% bump heuristic
6935 assert!(feerate_2 * 100 >= feerate_1 * 125);
6939 assert_ne!(feerate_2, 0);
6941 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
6942 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
6944 let mut feerate_3 = 0;
6946 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6947 assert_eq!(node_txn.len(), 1);
6948 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6949 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6950 assert_eq!(node_txn[0].output.len(), 1);
6951 check_spends!(node_txn[0], revoked_txn[0]);
6952 penalty_3 = node_txn[0].txid();
6953 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6954 assert_ne!(penalty_3, penalty_2);
6955 let fee_3 = penalty_sum - node_txn[0].output[0].value;
6956 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
6957 // Verify 25% bump heuristic
6958 assert!(feerate_3 * 100 >= feerate_2 * 125);
6962 assert_ne!(feerate_3, 0);
6964 nodes[1].node.get_and_clear_pending_events();
6965 nodes[1].node.get_and_clear_pending_msg_events();
6969 fn test_bump_penalty_txn_on_revoked_htlcs() {
6970 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
6971 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
6973 let chanmon_cfgs = create_chanmon_cfgs(2);
6974 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6975 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6976 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6978 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6979 // Lock HTLC in both directions
6980 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
6981 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
6983 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
6984 assert_eq!(revoked_local_txn[0].input.len(), 1);
6985 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
6987 // Revoke local commitment tx
6988 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6990 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6991 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
6992 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6993 check_closed_broadcast!(nodes[1], false);
6994 check_added_monitors!(nodes[1], 1);
6996 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6997 assert_eq!(revoked_htlc_txn.len(), 6);
6998 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6999 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7000 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7001 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7002 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7003 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7004 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7005 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7006 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7007 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7008 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7009 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7012 // Broadcast set of revoked txn on A
7013 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7014 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7015 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);
7020 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7021 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7022 // Verify claim tx are spending revoked HTLC txn
7023 assert_eq!(node_txn[4].input.len(), 2);
7024 assert_eq!(node_txn[4].output.len(), 1);
7025 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7026 first = node_txn[4].txid();
7027 // Store both feerates for later comparison
7028 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7029 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7030 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7034 // Connect three more block to see if bumped penalty are issued for HTLC txn
7035 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7036 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7038 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7039 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7041 check_spends!(node_txn[0], revoked_local_txn[0]);
7042 check_spends!(node_txn[1], revoked_local_txn[0]);
7047 // Few more blocks to confirm penalty txn
7048 let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7049 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7050 let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7052 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7053 assert_eq!(node_txn.len(), 1);
7055 assert_eq!(node_txn[0].input.len(), 2);
7056 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7057 // Verify bumped tx is different and 25% bump heuristic
7058 assert_ne!(first, node_txn[0].txid());
7059 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7060 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7061 assert!(feerate_2 * 100 > feerate_1 * 125);
7062 let txn = vec![node_txn[0].clone()];
7066 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7067 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7068 nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7069 connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7071 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7072 // We verify than no new transaction has been broadcast because previously
7073 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7074 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7075 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7076 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7077 // up bumped justice generation.
7078 assert_eq!(node_txn.len(), 0);
7081 check_closed_broadcast!(nodes[0], false);
7082 check_added_monitors!(nodes[0], 1);
7086 fn test_bump_penalty_txn_on_remote_commitment() {
7087 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7088 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7091 // Provide preimage for one
7092 // Check aggregation
7094 let chanmon_cfgs = create_chanmon_cfgs(2);
7095 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7096 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7097 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7099 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7100 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7101 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7103 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7104 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7105 assert_eq!(remote_txn[0].output.len(), 4);
7106 assert_eq!(remote_txn[0].input.len(), 1);
7107 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7109 // Claim a HTLC without revocation (provide B monitor with preimage)
7110 nodes[1].node.claim_funds(payment_preimage, 3_000_000);
7111 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7112 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7113 check_added_monitors!(nodes[1], 2);
7115 // One or more claim tx should have been broadcast, check it
7118 let feerate_timeout;
7119 let feerate_preimage;
7121 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7122 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7123 assert_eq!(node_txn[0].input.len(), 1);
7124 assert_eq!(node_txn[1].input.len(), 1);
7125 check_spends!(node_txn[0], remote_txn[0]);
7126 check_spends!(node_txn[1], remote_txn[0]);
7127 check_spends!(node_txn[2], chan.3);
7128 check_spends!(node_txn[3], node_txn[2]);
7129 check_spends!(node_txn[4], node_txn[2]);
7130 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7131 timeout = node_txn[0].txid();
7132 let index = node_txn[0].input[0].previous_output.vout;
7133 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7134 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7136 preimage = node_txn[1].txid();
7137 let index = node_txn[1].input[0].previous_output.vout;
7138 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7139 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7141 timeout = node_txn[1].txid();
7142 let index = node_txn[1].input[0].previous_output.vout;
7143 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7144 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7146 preimage = node_txn[0].txid();
7147 let index = node_txn[0].input[0].previous_output.vout;
7148 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7149 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7153 assert_ne!(feerate_timeout, 0);
7154 assert_ne!(feerate_preimage, 0);
7156 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7157 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.bitcoin_hash());
7159 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7160 assert_eq!(node_txn.len(), 2);
7161 assert_eq!(node_txn[0].input.len(), 1);
7162 assert_eq!(node_txn[1].input.len(), 1);
7163 check_spends!(node_txn[0], remote_txn[0]);
7164 check_spends!(node_txn[1], remote_txn[0]);
7165 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7166 let index = node_txn[0].input[0].previous_output.vout;
7167 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7168 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7169 assert!(new_feerate * 100 > feerate_timeout * 125);
7170 assert_ne!(timeout, node_txn[0].txid());
7172 let index = node_txn[1].input[0].previous_output.vout;
7173 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7174 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7175 assert!(new_feerate * 100 > feerate_preimage * 125);
7176 assert_ne!(preimage, node_txn[1].txid());
7178 let index = node_txn[1].input[0].previous_output.vout;
7179 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7180 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7181 assert!(new_feerate * 100 > feerate_timeout * 125);
7182 assert_ne!(timeout, node_txn[1].txid());
7184 let index = node_txn[0].input[0].previous_output.vout;
7185 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7186 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7187 assert!(new_feerate * 100 > feerate_preimage * 125);
7188 assert_ne!(preimage, node_txn[0].txid());
7193 nodes[1].node.get_and_clear_pending_events();
7194 nodes[1].node.get_and_clear_pending_msg_events();
7198 fn test_set_outpoints_partial_claiming() {
7199 // - remote party claim tx, new bump tx
7200 // - disconnect remote claiming tx, new bump
7201 // - disconnect tx, see no tx anymore
7202 let chanmon_cfgs = create_chanmon_cfgs(2);
7203 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7204 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7205 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7207 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7208 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7209 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7211 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7212 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7213 assert_eq!(remote_txn.len(), 3);
7214 assert_eq!(remote_txn[0].output.len(), 4);
7215 assert_eq!(remote_txn[0].input.len(), 1);
7216 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7217 check_spends!(remote_txn[1], remote_txn[0]);
7218 check_spends!(remote_txn[2], remote_txn[0]);
7220 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7221 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7222 // Provide node A with both preimage
7223 nodes[0].node.claim_funds(payment_preimage_1, 3_000_000);
7224 nodes[0].node.claim_funds(payment_preimage_2, 3_000_000);
7225 check_added_monitors!(nodes[0], 2);
7226 nodes[0].node.get_and_clear_pending_events();
7227 nodes[0].node.get_and_clear_pending_msg_events();
7229 // Connect blocks on node A commitment transaction
7230 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7231 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7232 check_closed_broadcast!(nodes[0], false);
7233 check_added_monitors!(nodes[0], 1);
7234 // Verify node A broadcast tx claiming both HTLCs
7236 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7237 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7238 assert_eq!(node_txn.len(), 4);
7239 check_spends!(node_txn[0], remote_txn[0]);
7240 check_spends!(node_txn[1], chan.3);
7241 check_spends!(node_txn[2], node_txn[1]);
7242 check_spends!(node_txn[3], node_txn[1]);
7243 assert_eq!(node_txn[0].input.len(), 2);
7247 // Connect blocks on node B
7248 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7249 check_closed_broadcast!(nodes[1], false);
7250 check_added_monitors!(nodes[1], 1);
7251 // Verify node B broadcast 2 HTLC-timeout txn
7252 let partial_claim_tx = {
7253 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7254 assert_eq!(node_txn.len(), 3);
7255 check_spends!(node_txn[1], node_txn[0]);
7256 check_spends!(node_txn[2], node_txn[0]);
7257 assert_eq!(node_txn[1].input.len(), 1);
7258 assert_eq!(node_txn[2].input.len(), 1);
7262 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7263 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7264 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7266 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7267 assert_eq!(node_txn.len(), 1);
7268 check_spends!(node_txn[0], remote_txn[0]);
7269 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7272 nodes[0].node.get_and_clear_pending_msg_events();
7274 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7275 nodes[0].block_notifier.block_disconnected(&header, 102);
7277 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7278 assert_eq!(node_txn.len(), 1);
7279 check_spends!(node_txn[0], remote_txn[0]);
7280 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7284 //// Disconnect one more block and then reconnect multiple no transaction should be generated
7285 nodes[0].block_notifier.block_disconnected(&header, 101);
7286 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7288 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7289 assert_eq!(node_txn.len(), 0);
7295 fn test_counterparty_raa_skip_no_crash() {
7296 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7297 // commitment transaction, we would have happily carried on and provided them the next
7298 // commitment transaction based on one RAA forward. This would probably eventually have led to
7299 // channel closure, but it would not have resulted in funds loss. Still, our
7300 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7301 // check simply that the channel is closed in response to such an RAA, but don't check whether
7302 // we decide to punish our counterparty for revoking their funds (as we don't currently
7304 let chanmon_cfgs = create_chanmon_cfgs(2);
7305 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7306 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7307 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7308 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).2;
7310 let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7311 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7312 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7313 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7314 let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7316 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7317 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7318 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7319 check_added_monitors!(nodes[1], 1);
7323 fn test_bump_txn_sanitize_tracking_maps() {
7324 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7325 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7327 let chanmon_cfgs = create_chanmon_cfgs(2);
7328 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7329 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7330 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7332 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7333 // Lock HTLC in both directions
7334 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7335 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7337 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7338 assert_eq!(revoked_local_txn[0].input.len(), 1);
7339 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7341 // Revoke local commitment tx
7342 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7344 // Broadcast set of revoked txn on A
7345 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7346 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7347 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7348 check_closed_broadcast!(nodes[0], false);
7349 check_added_monitors!(nodes[0], 1);
7351 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7352 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7353 check_spends!(node_txn[0], revoked_local_txn[0]);
7354 check_spends!(node_txn[1], revoked_local_txn[0]);
7355 check_spends!(node_txn[2], revoked_local_txn[0]);
7356 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7360 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7361 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7362 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.bitcoin_hash());
7364 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7365 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7366 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7367 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7373 fn test_override_channel_config() {
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, None]);
7377 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7379 // Node0 initiates a channel to node1 using the override config.
7380 let mut override_config = UserConfig::default();
7381 override_config.own_channel_config.our_to_self_delay = 200;
7383 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7385 // Assert the channel created by node0 is using the override config.
7386 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7387 assert_eq!(res.channel_flags, 0);
7388 assert_eq!(res.to_self_delay, 200);
7392 fn test_override_0msat_htlc_minimum() {
7393 let mut zero_config = UserConfig::default();
7394 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7395 let chanmon_cfgs = create_chanmon_cfgs(2);
7396 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7397 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7398 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7400 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7401 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7402 assert_eq!(res.htlc_minimum_msat, 1);
7404 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &res);
7405 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7406 assert_eq!(res.htlc_minimum_msat, 1);