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 spend_txn = check_spendable_outputs!(nodes[1], 1);
4110 assert_eq!(spend_txn.len(), 3);
4111 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
4112 check_spends!(spend_txn[0], revoked_local_txn[0]);
4113 check_spends!(spend_txn[1], node_txn[0]);
4117 fn test_static_spendable_outputs_preimage_tx() {
4118 let chanmon_cfgs = create_chanmon_cfgs(2);
4119 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4120 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4121 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4123 // Create some initial channels
4124 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4126 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4128 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4129 assert_eq!(commitment_tx[0].input.len(), 1);
4130 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4132 // Settle A's commitment tx on B's chain
4133 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4134 assert!(nodes[1].node.claim_funds(payment_preimage, 3_000_000));
4135 check_added_monitors!(nodes[1], 1);
4136 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4137 check_added_monitors!(nodes[1], 1);
4138 let events = nodes[1].node.get_and_clear_pending_msg_events();
4140 MessageSendEvent::UpdateHTLCs { .. } => {},
4141 _ => panic!("Unexpected event"),
4144 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4145 _ => panic!("Unexepected event"),
4148 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4149 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4150 assert_eq!(node_txn.len(), 3);
4151 check_spends!(node_txn[0], commitment_tx[0]);
4152 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4153 eprintln!("{:?}", node_txn[1]);
4154 check_spends!(node_txn[1], chan_1.3);
4155 check_spends!(node_txn[2], node_txn[1]);
4157 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
4158 assert_eq!(spend_txn.len(), 1);
4159 check_spends!(spend_txn[0], node_txn[0]);
4163 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4164 let chanmon_cfgs = create_chanmon_cfgs(2);
4165 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4166 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4167 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4169 // Create some initial channels
4170 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4172 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4173 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4174 assert_eq!(revoked_local_txn[0].input.len(), 1);
4175 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4177 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4179 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4180 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4181 check_closed_broadcast!(nodes[1], false);
4182 check_added_monitors!(nodes[1], 1);
4184 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4185 assert_eq!(node_txn.len(), 2);
4186 assert_eq!(node_txn[0].input.len(), 2);
4187 check_spends!(node_txn[0], revoked_local_txn[0]);
4189 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4190 assert_eq!(spend_txn.len(), 1);
4191 check_spends!(spend_txn[0], node_txn[0]);
4195 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4196 let chanmon_cfgs = create_chanmon_cfgs(2);
4197 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4198 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4199 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4201 // Create some initial channels
4202 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4204 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4205 let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4206 assert_eq!(revoked_local_txn[0].input.len(), 1);
4207 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4209 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4211 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4212 // A will generate HTLC-Timeout from revoked commitment tx
4213 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4214 check_closed_broadcast!(nodes[0], false);
4215 check_added_monitors!(nodes[0], 1);
4217 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4218 assert_eq!(revoked_htlc_txn.len(), 3);
4219 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
4220 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4221 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4222 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4223 check_spends!(revoked_htlc_txn[1], chan_1.3);
4225 // B will generate justice tx from A's revoked commitment/HTLC tx
4226 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4227 check_closed_broadcast!(nodes[1], false);
4228 check_added_monitors!(nodes[1], 1);
4230 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4231 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
4232 assert_eq!(node_txn[0].input.len(), 2);
4233 check_spends!(node_txn[0], revoked_local_txn[0]);
4234 check_spends!(node_txn[1], chan_1.3);
4235 assert_eq!(node_txn[2].input.len(), 1);
4236 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4237 assert_eq!(node_txn[3].input.len(), 1);
4238 check_spends!(node_txn[3], revoked_local_txn[0]);
4240 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4241 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4242 assert_eq!(spend_txn.len(), 2);
4243 check_spends!(spend_txn[0], node_txn[0]);
4244 check_spends!(spend_txn[1], node_txn[2]);
4248 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4249 let chanmon_cfgs = create_chanmon_cfgs(2);
4250 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4251 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4252 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4254 // Create some initial channels
4255 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4257 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4258 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4259 assert_eq!(revoked_local_txn[0].input.len(), 1);
4260 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4262 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4264 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4265 // B will generate HTLC-Success from revoked commitment tx
4266 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4267 check_closed_broadcast!(nodes[1], false);
4268 check_added_monitors!(nodes[1], 1);
4269 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4271 assert_eq!(revoked_htlc_txn.len(), 3);
4272 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
4273 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4274 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4275 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4277 // A will generate justice tx from B's revoked commitment/HTLC tx
4278 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4279 check_closed_broadcast!(nodes[0], false);
4280 check_added_monitors!(nodes[0], 1);
4282 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4283 assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4284 assert_eq!(node_txn[2].input.len(), 1);
4285 check_spends!(node_txn[2], revoked_htlc_txn[0]);
4287 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4288 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4289 assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4290 assert_eq!(spend_txn[0], spend_txn[2]);
4291 check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4292 check_spends!(spend_txn[1], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4293 check_spends!(spend_txn[3], node_txn[2]); // spending justice tx output on htlc success tx
4297 fn test_onchain_to_onchain_claim() {
4298 // Test that in case of channel closure, we detect the state of output thanks to
4299 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4300 // First, have C claim an HTLC against its own latest commitment transaction.
4301 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4303 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4306 let chanmon_cfgs = create_chanmon_cfgs(3);
4307 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4308 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4309 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4311 // Create some initial channels
4312 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4313 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4315 // Rebalance the network a bit by relaying one payment through all the channels ...
4316 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4317 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4319 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4320 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4321 let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4322 check_spends!(commitment_tx[0], chan_2.3);
4323 nodes[2].node.claim_funds(payment_preimage, 3_000_000);
4324 check_added_monitors!(nodes[2], 1);
4325 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4326 assert!(updates.update_add_htlcs.is_empty());
4327 assert!(updates.update_fail_htlcs.is_empty());
4328 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4329 assert!(updates.update_fail_malformed_htlcs.is_empty());
4331 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4332 check_closed_broadcast!(nodes[2], false);
4333 check_added_monitors!(nodes[2], 1);
4335 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4336 assert_eq!(c_txn.len(), 4);
4337 assert_eq!(c_txn[0], c_txn[2]);
4338 assert_eq!(c_txn[0], c_txn[3]);
4339 assert_eq!(commitment_tx[0], c_txn[1]);
4340 check_spends!(c_txn[1], chan_2.3);
4341 check_spends!(c_txn[2], c_txn[1]);
4342 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4343 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4344 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4345 assert_eq!(c_txn[0].lock_time, 0); // Success tx
4347 // 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
4348 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4350 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4351 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4352 assert_eq!(b_txn.len(), 3);
4353 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4354 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4355 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4356 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4357 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4358 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4359 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4360 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4361 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4364 check_added_monitors!(nodes[1], 1);
4365 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4366 check_added_monitors!(nodes[1], 1);
4367 match msg_events[0] {
4368 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4369 _ => panic!("Unexpected event"),
4371 match msg_events[1] {
4372 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, .. } } => {
4373 assert!(update_add_htlcs.is_empty());
4374 assert!(update_fail_htlcs.is_empty());
4375 assert_eq!(update_fulfill_htlcs.len(), 1);
4376 assert!(update_fail_malformed_htlcs.is_empty());
4377 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4379 _ => panic!("Unexpected event"),
4381 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4382 let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4383 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4384 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4385 // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4386 assert_eq!(b_txn.len(), 3);
4387 check_spends!(b_txn[1], chan_1.3);
4388 check_spends!(b_txn[2], b_txn[1]);
4389 check_spends!(b_txn[0], commitment_tx[0]);
4390 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4391 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4392 assert_eq!(b_txn[0].lock_time, 0); // Success tx
4394 check_closed_broadcast!(nodes[1], false);
4395 check_added_monitors!(nodes[1], 1);
4399 fn test_duplicate_payment_hash_one_failure_one_success() {
4400 // Topology : A --> B --> C
4401 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4402 let chanmon_cfgs = create_chanmon_cfgs(3);
4403 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4404 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4405 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4407 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4408 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4410 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4411 *nodes[0].network_payment_count.borrow_mut() -= 1;
4412 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4414 let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4415 assert_eq!(commitment_txn[0].input.len(), 1);
4416 check_spends!(commitment_txn[0], chan_2.3);
4418 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4419 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4420 check_closed_broadcast!(nodes[1], false);
4421 check_added_monitors!(nodes[1], 1);
4423 let htlc_timeout_tx;
4424 { // Extract one of the two HTLC-Timeout transaction
4425 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4426 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4427 assert_eq!(node_txn.len(), 5);
4428 check_spends!(node_txn[0], commitment_txn[0]);
4429 assert_eq!(node_txn[0].input.len(), 1);
4430 check_spends!(node_txn[1], commitment_txn[0]);
4431 assert_eq!(node_txn[1].input.len(), 1);
4432 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4433 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4434 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4435 check_spends!(node_txn[2], chan_2.3);
4436 check_spends!(node_txn[3], node_txn[2]);
4437 check_spends!(node_txn[4], node_txn[2]);
4438 htlc_timeout_tx = node_txn[1].clone();
4441 nodes[2].node.claim_funds(our_payment_preimage, 900_000);
4442 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4443 check_added_monitors!(nodes[2], 3);
4444 let events = nodes[2].node.get_and_clear_pending_msg_events();
4446 MessageSendEvent::UpdateHTLCs { .. } => {},
4447 _ => panic!("Unexpected event"),
4450 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4451 _ => panic!("Unexepected event"),
4453 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4454 assert_eq!(htlc_success_txn.len(), 7);
4455 check_spends!(htlc_success_txn[2], chan_2.3);
4456 check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4457 check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4458 assert_eq!(htlc_success_txn[0], htlc_success_txn[5]);
4459 assert_eq!(htlc_success_txn[0].input.len(), 1);
4460 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4461 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4462 assert_eq!(htlc_success_txn[1].input.len(), 1);
4463 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4464 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4465 check_spends!(htlc_success_txn[0], commitment_txn[0]);
4466 check_spends!(htlc_success_txn[1], commitment_txn[0]);
4468 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4469 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4470 expect_pending_htlcs_forwardable!(nodes[1]);
4471 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4472 assert!(htlc_updates.update_add_htlcs.is_empty());
4473 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4474 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4475 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4476 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4477 check_added_monitors!(nodes[1], 1);
4479 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4480 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4482 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4483 let events = nodes[0].node.get_and_clear_pending_msg_events();
4484 assert_eq!(events.len(), 1);
4486 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
4488 _ => { panic!("Unexpected event"); }
4491 let events = nodes[0].node.get_and_clear_pending_events();
4493 Event::PaymentFailed { ref payment_hash, .. } => {
4494 assert_eq!(*payment_hash, duplicate_payment_hash);
4496 _ => panic!("Unexpected event"),
4499 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4500 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4501 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4502 assert!(updates.update_add_htlcs.is_empty());
4503 assert!(updates.update_fail_htlcs.is_empty());
4504 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4505 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4506 assert!(updates.update_fail_malformed_htlcs.is_empty());
4507 check_added_monitors!(nodes[1], 1);
4509 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4510 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4512 let events = nodes[0].node.get_and_clear_pending_events();
4514 Event::PaymentSent { ref payment_preimage } => {
4515 assert_eq!(*payment_preimage, our_payment_preimage);
4517 _ => panic!("Unexpected event"),
4522 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4523 let chanmon_cfgs = create_chanmon_cfgs(2);
4524 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4525 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4526 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4528 // Create some initial channels
4529 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4531 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4532 let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4533 assert_eq!(local_txn[0].input.len(), 1);
4534 check_spends!(local_txn[0], chan_1.3);
4536 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4537 nodes[1].node.claim_funds(payment_preimage, 9_000_000);
4538 check_added_monitors!(nodes[1], 1);
4539 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4540 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4541 check_added_monitors!(nodes[1], 1);
4542 let events = nodes[1].node.get_and_clear_pending_msg_events();
4544 MessageSendEvent::UpdateHTLCs { .. } => {},
4545 _ => panic!("Unexpected event"),
4548 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4549 _ => panic!("Unexepected event"),
4551 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4552 assert_eq!(node_txn[0].input.len(), 1);
4553 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4554 check_spends!(node_txn[0], local_txn[0]);
4556 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4557 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4558 assert_eq!(spend_txn.len(), 2);
4559 check_spends!(spend_txn[0], node_txn[0]);
4560 check_spends!(spend_txn[1], node_txn[2]);
4563 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4564 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4565 // unrevoked commitment transaction.
4566 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4567 // a remote RAA before they could be failed backwards (and combinations thereof).
4568 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4569 // use the same payment hashes.
4570 // Thus, we use a six-node network:
4575 // And test where C fails back to A/B when D announces its latest commitment transaction
4576 let chanmon_cfgs = create_chanmon_cfgs(6);
4577 let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4578 let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
4579 let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
4581 create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::supported(), InitFeatures::supported());
4582 create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::supported(), InitFeatures::supported());
4583 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::supported(), InitFeatures::supported());
4584 create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::supported(), InitFeatures::supported());
4585 create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::supported(), InitFeatures::supported());
4587 // Rebalance and check output sanity...
4588 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4589 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4590 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
4592 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4594 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
4596 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
4597 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();
4599 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
4601 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
4603 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4605 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4606 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4608 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4610 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4613 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4615 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();
4616 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
4619 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
4621 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4622 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4624 // Double-check that six of the new HTLC were added
4625 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4626 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4627 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
4628 assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
4630 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4631 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4632 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
4633 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
4634 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
4635 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
4636 check_added_monitors!(nodes[4], 0);
4637 expect_pending_htlcs_forwardable!(nodes[4]);
4638 check_added_monitors!(nodes[4], 1);
4640 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4641 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
4642 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
4643 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
4644 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
4645 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4647 // Fail 3rd below-dust and 7th above-dust HTLCs
4648 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
4649 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
4650 check_added_monitors!(nodes[5], 0);
4651 expect_pending_htlcs_forwardable!(nodes[5]);
4652 check_added_monitors!(nodes[5], 1);
4654 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4655 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
4656 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
4657 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4659 let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4661 expect_pending_htlcs_forwardable!(nodes[3]);
4662 check_added_monitors!(nodes[3], 1);
4663 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4664 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
4665 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
4666 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
4667 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
4668 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
4669 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
4670 if deliver_last_raa {
4671 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4673 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4676 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4677 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4678 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4679 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4681 // We now broadcast the latest commitment transaction, which *should* result in failures for
4682 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4683 // the non-broadcast above-dust HTLCs.
4685 // Alternatively, we may broadcast the previous commitment transaction, which should only
4686 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4687 let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
4689 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4690 if announce_latest {
4691 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4693 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4695 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4696 check_closed_broadcast!(nodes[2], false);
4697 expect_pending_htlcs_forwardable!(nodes[2]);
4698 check_added_monitors!(nodes[2], 3);
4700 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4701 assert_eq!(cs_msgs.len(), 2);
4702 let mut a_done = false;
4703 for msg in cs_msgs {
4705 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4706 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4707 // should be failed-backwards here.
4708 let target = if *node_id == nodes[0].node.get_our_node_id() {
4709 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4710 for htlc in &updates.update_fail_htlcs {
4711 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 });
4713 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4718 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4719 for htlc in &updates.update_fail_htlcs {
4720 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4722 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4723 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4726 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
4727 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
4728 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
4729 if announce_latest {
4730 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
4731 if *node_id == nodes[0].node.get_our_node_id() {
4732 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
4735 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4737 _ => panic!("Unexpected event"),
4741 let as_events = nodes[0].node.get_and_clear_pending_events();
4742 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4743 let mut as_failds = HashSet::new();
4744 for event in as_events.iter() {
4745 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4746 assert!(as_failds.insert(*payment_hash));
4747 if *payment_hash != payment_hash_2 {
4748 assert_eq!(*rejected_by_dest, deliver_last_raa);
4750 assert!(!rejected_by_dest);
4752 } else { panic!("Unexpected event"); }
4754 assert!(as_failds.contains(&payment_hash_1));
4755 assert!(as_failds.contains(&payment_hash_2));
4756 if announce_latest {
4757 assert!(as_failds.contains(&payment_hash_3));
4758 assert!(as_failds.contains(&payment_hash_5));
4760 assert!(as_failds.contains(&payment_hash_6));
4762 let bs_events = nodes[1].node.get_and_clear_pending_events();
4763 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4764 let mut bs_failds = HashSet::new();
4765 for event in bs_events.iter() {
4766 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4767 assert!(bs_failds.insert(*payment_hash));
4768 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4769 assert_eq!(*rejected_by_dest, deliver_last_raa);
4771 assert!(!rejected_by_dest);
4773 } else { panic!("Unexpected event"); }
4775 assert!(bs_failds.contains(&payment_hash_1));
4776 assert!(bs_failds.contains(&payment_hash_2));
4777 if announce_latest {
4778 assert!(bs_failds.contains(&payment_hash_4));
4780 assert!(bs_failds.contains(&payment_hash_5));
4782 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4783 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4784 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4785 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4786 // PaymentFailureNetworkUpdates.
4787 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4788 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4789 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4790 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4791 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4793 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4794 _ => panic!("Unexpected event"),
4800 fn test_fail_backwards_latest_remote_announce_a() {
4801 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4805 fn test_fail_backwards_latest_remote_announce_b() {
4806 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4810 fn test_fail_backwards_previous_remote_announce() {
4811 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4812 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4813 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4817 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4818 let chanmon_cfgs = create_chanmon_cfgs(2);
4819 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4820 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4821 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4823 // Create some initial channels
4824 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4826 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4827 let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4828 assert_eq!(local_txn[0].input.len(), 1);
4829 check_spends!(local_txn[0], chan_1.3);
4831 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4832 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4833 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4834 check_closed_broadcast!(nodes[0], false);
4835 check_added_monitors!(nodes[0], 1);
4837 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4838 assert_eq!(node_txn[0].input.len(), 1);
4839 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4840 check_spends!(node_txn[0], local_txn[0]);
4842 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4843 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4844 assert_eq!(spend_txn.len(), 8);
4845 assert_eq!(spend_txn[0], spend_txn[2]);
4846 assert_eq!(spend_txn[0], spend_txn[4]);
4847 assert_eq!(spend_txn[0], spend_txn[6]);
4848 assert_eq!(spend_txn[1], spend_txn[3]);
4849 assert_eq!(spend_txn[1], spend_txn[5]);
4850 assert_eq!(spend_txn[1], spend_txn[7]);
4851 check_spends!(spend_txn[0], local_txn[0]);
4852 check_spends!(spend_txn[1], node_txn[0]);
4856 fn test_static_output_closing_tx() {
4857 let chanmon_cfgs = create_chanmon_cfgs(2);
4858 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4859 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4860 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4862 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4864 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4865 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4867 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4868 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4869 let spend_txn = check_spendable_outputs!(nodes[0], 2);
4870 assert_eq!(spend_txn.len(), 1);
4871 check_spends!(spend_txn[0], closing_tx);
4873 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4874 let spend_txn = check_spendable_outputs!(nodes[1], 2);
4875 assert_eq!(spend_txn.len(), 1);
4876 check_spends!(spend_txn[0], closing_tx);
4879 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4880 let chanmon_cfgs = create_chanmon_cfgs(2);
4881 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4882 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4883 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 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4888 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4889 // present in B's local commitment transaction, but none of A's commitment transactions.
4890 assert!(nodes[1].node.claim_funds(our_payment_preimage, if use_dust { 50_000 } else { 3_000_000 }));
4891 check_added_monitors!(nodes[1], 1);
4893 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4894 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
4895 let events = nodes[0].node.get_and_clear_pending_events();
4896 assert_eq!(events.len(), 1);
4898 Event::PaymentSent { payment_preimage } => {
4899 assert_eq!(payment_preimage, our_payment_preimage);
4901 _ => panic!("Unexpected event"),
4904 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4905 check_added_monitors!(nodes[0], 1);
4906 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4907 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4908 check_added_monitors!(nodes[1], 1);
4910 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4911 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4912 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4913 header.prev_blockhash = header.bitcoin_hash();
4915 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4916 check_closed_broadcast!(nodes[1], false);
4917 check_added_monitors!(nodes[1], 1);
4920 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4921 let chanmon_cfgs = create_chanmon_cfgs(2);
4922 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4923 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4924 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4925 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4927 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();
4928 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4929 nodes[0].node.send_payment(route, payment_hash).unwrap();
4930 check_added_monitors!(nodes[0], 1);
4932 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4934 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4935 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4936 // to "time out" the HTLC.
4938 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4940 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4941 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
4942 header.prev_blockhash = header.bitcoin_hash();
4944 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4945 check_closed_broadcast!(nodes[0], false);
4946 check_added_monitors!(nodes[0], 1);
4949 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4950 let chanmon_cfgs = create_chanmon_cfgs(3);
4951 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4952 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4953 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4954 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
4956 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4957 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4958 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4959 // actually revoked.
4960 let htlc_value = if use_dust { 50000 } else { 3000000 };
4961 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4962 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4963 expect_pending_htlcs_forwardable!(nodes[1]);
4964 check_added_monitors!(nodes[1], 1);
4966 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4967 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
4968 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
4969 check_added_monitors!(nodes[0], 1);
4970 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4971 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
4972 check_added_monitors!(nodes[1], 1);
4973 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
4974 check_added_monitors!(nodes[1], 1);
4975 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4977 if check_revoke_no_close {
4978 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
4979 check_added_monitors!(nodes[0], 1);
4982 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4983 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4984 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4985 header.prev_blockhash = header.bitcoin_hash();
4987 if !check_revoke_no_close {
4988 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4989 check_closed_broadcast!(nodes[0], false);
4990 check_added_monitors!(nodes[0], 1);
4992 let events = nodes[0].node.get_and_clear_pending_events();
4993 assert_eq!(events.len(), 1);
4995 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4996 assert_eq!(payment_hash, our_payment_hash);
4997 assert!(rejected_by_dest);
4999 _ => panic!("Unexpected event"),
5004 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5005 // There are only a few cases to test here:
5006 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
5007 // broadcastable commitment transactions result in channel closure,
5008 // * its included in an unrevoked-but-previous remote commitment transaction,
5009 // * its included in the latest remote or local commitment transactions.
5010 // We test each of the three possible commitment transactions individually and use both dust and
5012 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5013 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5014 // tested for at least one of the cases in other tests.
5016 fn htlc_claim_single_commitment_only_a() {
5017 do_htlc_claim_local_commitment_only(true);
5018 do_htlc_claim_local_commitment_only(false);
5020 do_htlc_claim_current_remote_commitment_only(true);
5021 do_htlc_claim_current_remote_commitment_only(false);
5025 fn htlc_claim_single_commitment_only_b() {
5026 do_htlc_claim_previous_remote_commitment_only(true, false);
5027 do_htlc_claim_previous_remote_commitment_only(false, false);
5028 do_htlc_claim_previous_remote_commitment_only(true, true);
5029 do_htlc_claim_previous_remote_commitment_only(false, true);
5032 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>)
5033 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5036 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);
5040 // 0: node1 fails backward
5041 // 1: final node fails backward
5042 // 2: payment completed but the user rejects the payment
5043 // 3: final node fails backward (but tamper onion payloads from node0)
5044 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5045 // 200: trigger error in the final node and tamper returning fail_htlc
5046 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>)
5047 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5048 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5052 // reset block height
5053 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5054 for ix in 0..nodes.len() {
5055 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5058 macro_rules! expect_event {
5059 ($node: expr, $event_type: path) => {{
5060 let events = $node.node.get_and_clear_pending_events();
5061 assert_eq!(events.len(), 1);
5063 $event_type { .. } => {},
5064 _ => panic!("Unexpected event"),
5069 macro_rules! expect_htlc_forward {
5071 expect_event!($node, Event::PendingHTLCsForwardable);
5072 $node.node.process_pending_htlc_forwards();
5076 // 0 ~~> 2 send payment
5077 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
5078 check_added_monitors!(nodes[0], 1);
5079 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5080 // temper update_add (0 => 1)
5081 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5082 if test_case == 0 || test_case == 3 || test_case == 100 {
5083 callback_msg(&mut update_add_0);
5086 // 0 => 1 update_add & CS
5087 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5088 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5090 let update_1_0 = match test_case {
5091 0|100 => { // intermediate node failure; fail backward to 0
5092 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5093 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));
5096 1|2|3|200 => { // final node failure; forwarding to 2
5097 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5099 if test_case != 200 {
5102 expect_htlc_forward!(&nodes[1]);
5104 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5105 check_added_monitors!(&nodes[1], 1);
5106 assert_eq!(update_1.update_add_htlcs.len(), 1);
5107 // tamper update_add (1 => 2)
5108 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5109 if test_case != 3 && test_case != 200 {
5110 callback_msg(&mut update_add_1);
5114 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5115 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5117 if test_case == 2 || test_case == 200 {
5118 expect_htlc_forward!(&nodes[2]);
5119 expect_event!(&nodes[2], Event::PaymentReceived);
5121 expect_pending_htlcs_forwardable!(nodes[2]);
5124 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5125 if test_case == 2 || test_case == 200 {
5126 check_added_monitors!(&nodes[2], 1);
5128 assert!(update_2_1.update_fail_htlcs.len() == 1);
5130 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5131 if test_case == 200 {
5132 callback_fail(&mut fail_msg);
5136 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5137 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5139 // backward fail on 1
5140 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5141 assert!(update_1_0.update_fail_htlcs.len() == 1);
5144 _ => unreachable!(),
5147 // 1 => 0 commitment_signed_dance
5148 if update_1_0.update_fail_htlcs.len() > 0 {
5149 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5150 if test_case == 100 {
5151 callback_fail(&mut fail_msg);
5153 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5155 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5158 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5160 let events = nodes[0].node.get_and_clear_pending_events();
5161 assert_eq!(events.len(), 1);
5162 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
5163 assert_eq!(*rejected_by_dest, !expected_retryable);
5164 assert_eq!(*error_code, expected_error_code);
5166 panic!("Uexpected event");
5169 let events = nodes[0].node.get_and_clear_pending_msg_events();
5170 if expected_channel_update.is_some() {
5171 assert_eq!(events.len(), 1);
5173 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5175 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5176 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5177 panic!("channel_update not found!");
5180 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5181 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5182 assert!(*short_channel_id == *expected_short_channel_id);
5183 assert!(*is_permanent == *expected_is_permanent);
5185 panic!("Unexpected message event");
5188 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5189 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5190 assert!(*node_id == *expected_node_id);
5191 assert!(*is_permanent == *expected_is_permanent);
5193 panic!("Unexpected message event");
5198 _ => panic!("Unexpected message event"),
5201 assert_eq!(events.len(), 0);
5205 impl msgs::ChannelUpdate {
5206 fn dummy() -> msgs::ChannelUpdate {
5207 use secp256k1::ffi::Signature as FFISignature;
5208 use secp256k1::Signature;
5209 msgs::ChannelUpdate {
5210 signature: Signature::from(FFISignature::new()),
5211 contents: msgs::UnsignedChannelUpdate {
5212 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
5213 short_channel_id: 0,
5216 cltv_expiry_delta: 0,
5217 htlc_minimum_msat: 0,
5219 fee_proportional_millionths: 0,
5220 excess_data: vec![],
5226 struct BogusOnionHopData {
5229 impl BogusOnionHopData {
5230 fn new(orig: msgs::OnionHopData) -> Self {
5231 Self { data: orig.encode() }
5234 impl Writeable for BogusOnionHopData {
5235 fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5236 writer.write_all(&self.data[..])
5241 fn test_onion_failure() {
5242 use ln::msgs::ChannelUpdate;
5243 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5246 const BADONION: u16 = 0x8000;
5247 const PERM: u16 = 0x4000;
5248 const NODE: u16 = 0x2000;
5249 const UPDATE: u16 = 0x1000;
5251 let chanmon_cfgs = create_chanmon_cfgs(3);
5252 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5253 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5254 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5255 for node in nodes.iter() {
5256 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5258 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())];
5259 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5260 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
5262 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5264 // intermediate node failure
5265 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5266 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5267 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5268 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5269 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5270 let mut new_payloads = Vec::new();
5271 for payload in onion_payloads.drain(..) {
5272 new_payloads.push(BogusOnionHopData::new(payload));
5274 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5275 // describing a length-1 TLV payload, which is obviously bogus.
5276 new_payloads[0].data[0] = 1;
5277 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5278 }, ||{}, 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
5280 // final node failure
5281 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5282 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5283 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5284 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5285 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5286 let mut new_payloads = Vec::new();
5287 for payload in onion_payloads.drain(..) {
5288 new_payloads.push(BogusOnionHopData::new(payload));
5290 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5291 // length-1 TLV payload, which is obviously bogus.
5292 new_payloads[1].data[0] = 1;
5293 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5294 }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5296 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5297 // receiving simulated fail messages
5298 // intermediate node failure
5299 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5301 msg.amount_msat -= 1;
5303 // and tamper returning error message
5304 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5305 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5306 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5307 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
5309 // final node failure
5310 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5311 // and tamper returning error message
5312 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5313 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5314 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5316 nodes[2].node.fail_htlc_backwards(&payment_hash);
5317 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
5319 // intermediate node failure
5320 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5321 msg.amount_msat -= 1;
5323 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5324 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5325 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5326 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
5328 // final node failure
5329 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5330 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5331 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5332 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5334 nodes[2].node.fail_htlc_backwards(&payment_hash);
5335 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
5337 // intermediate node failure
5338 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5339 msg.amount_msat -= 1;
5341 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5342 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5343 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5345 nodes[2].node.fail_htlc_backwards(&payment_hash);
5346 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
5348 // final node failure
5349 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5350 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5351 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5352 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5354 nodes[2].node.fail_htlc_backwards(&payment_hash);
5355 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
5357 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5358 Some(BADONION|PERM|4), None);
5360 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5361 Some(BADONION|PERM|5), None);
5363 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5364 Some(BADONION|PERM|6), None);
5366 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5367 msg.amount_msat -= 1;
5369 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5370 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5371 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5372 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5374 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5375 msg.amount_msat -= 1;
5377 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5378 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5379 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5380 // short_channel_id from the processing node
5381 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5383 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5384 msg.amount_msat -= 1;
5386 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5387 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5388 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5389 // short_channel_id from the processing node
5390 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5392 let mut bogus_route = route.clone();
5393 bogus_route.hops[1].short_channel_id -= 1;
5394 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5395 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
5397 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5398 let mut bogus_route = route.clone();
5399 let route_len = bogus_route.hops.len();
5400 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
5401 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5403 //TODO: with new config API, we will be able to generate both valid and
5404 //invalid channel_update cases.
5405 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5406 msg.amount_msat -= 1;
5407 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5409 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5410 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5411 msg.cltv_expiry -= 1;
5412 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5414 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5415 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5416 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5418 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5419 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5421 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5422 nodes[2].node.fail_htlc_backwards(&payment_hash);
5423 }, false, Some(PERM|15), None);
5425 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5426 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5427 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5429 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5430 }, || {}, true, Some(17), None);
5432 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5433 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5434 for f in pending_forwards.iter_mut() {
5436 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5437 forward_info.outgoing_cltv_value += 1,
5442 }, true, Some(18), None);
5444 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5445 // violate amt_to_forward > msg.amount_msat
5446 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5447 for f in pending_forwards.iter_mut() {
5449 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5450 forward_info.amt_to_forward -= 1,
5455 }, true, Some(19), None);
5457 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5458 // disconnect event to the channel between nodes[1] ~ nodes[2]
5459 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5460 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5461 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5462 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5464 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5465 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5466 let mut route = route.clone();
5468 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
5469 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5470 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
5471 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5472 msg.cltv_expiry = htlc_cltv;
5473 msg.onion_routing_packet = onion_packet;
5474 }, ||{}, true, Some(21), None);
5479 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5480 let chanmon_cfgs = create_chanmon_cfgs(2);
5481 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5482 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5483 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5484 //Force duplicate channel ids
5485 for node in nodes.iter() {
5486 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5489 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5490 let channel_value_satoshis=10000;
5491 let push_msat=10001;
5492 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5493 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5494 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &node0_to_1_send_open_channel);
5496 //Create a second channel with a channel_id collision
5497 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5501 fn bolt2_open_channel_sending_node_checks_part2() {
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);
5507 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5508 let channel_value_satoshis=2^24;
5509 let push_msat=10001;
5510 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5512 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5513 let channel_value_satoshis=10000;
5514 // Test when push_msat is equal to 1000 * funding_satoshis.
5515 let push_msat=1000*channel_value_satoshis+1;
5516 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5518 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5519 let channel_value_satoshis=10000;
5520 let push_msat=10001;
5521 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
5522 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5523 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5525 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5526 // 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
5527 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5529 // 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.
5530 assert!(BREAKDOWN_TIMEOUT>0);
5531 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5533 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5534 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5535 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5537 // 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.
5538 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5539 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5540 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5541 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
5542 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5545 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5546 // 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.
5547 //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.
5550 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5551 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5552 let chanmon_cfgs = create_chanmon_cfgs(2);
5553 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5554 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5555 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5556 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5557 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5558 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5560 route.hops[0].fee_msat = 100;
5562 let err = nodes[0].node.send_payment(route, our_payment_hash);
5564 if let Err(APIError::ChannelUnavailable{err}) = err {
5565 assert_eq!(err, "Cannot send less than their minimum HTLC value");
5569 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5570 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5574 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5575 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5576 let chanmon_cfgs = create_chanmon_cfgs(2);
5577 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5578 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5579 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5580 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5581 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5582 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5584 route.hops[0].fee_msat = 0;
5586 let err = nodes[0].node.send_payment(route, our_payment_hash);
5588 if let Err(APIError::ChannelUnavailable{err}) = err {
5589 assert_eq!(err, "Cannot send 0-msat HTLC");
5593 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5594 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
5598 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
5599 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5600 let chanmon_cfgs = create_chanmon_cfgs(2);
5601 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5602 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5603 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5604 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5605 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5606 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5608 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5609 check_added_monitors!(nodes[0], 1);
5610 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5611 updates.update_add_htlcs[0].amount_msat = 0;
5613 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5614 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
5615 check_closed_broadcast!(nodes[1], true).unwrap();
5616 check_added_monitors!(nodes[1], 1);
5620 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5621 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5622 //It is enforced when constructing a route.
5623 let chanmon_cfgs = create_chanmon_cfgs(2);
5624 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5625 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5626 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5627 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::supported(), InitFeatures::supported());
5628 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5629 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5631 let err = nodes[0].node.send_payment(route, our_payment_hash);
5633 if let Err(APIError::RouteError{err}) = err {
5634 assert_eq!(err, "Channel CLTV overflowed?!");
5641 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5642 //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.
5643 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5644 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
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, 1000000, 0, InitFeatures::supported(), InitFeatures::supported());
5650 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5652 for i in 0..max_accepted_htlcs {
5653 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5654 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5655 let payment_event = {
5656 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5657 check_added_monitors!(nodes[0], 1);
5659 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5660 assert_eq!(events.len(), 1);
5661 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5662 assert_eq!(htlcs[0].htlc_id, i);
5666 SendEvent::from_event(events.remove(0))
5668 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
5669 check_added_monitors!(nodes[1], 0);
5670 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5672 expect_pending_htlcs_forwardable!(nodes[1]);
5673 expect_payment_received!(nodes[1], our_payment_hash, 100000);
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 err = nodes[0].node.send_payment(route, our_payment_hash);
5679 if let Err(APIError::ChannelUnavailable{err}) = err {
5680 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
5684 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5685 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
5689 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5690 //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.
5691 let chanmon_cfgs = create_chanmon_cfgs(2);
5692 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5693 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5694 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5695 let channel_value = 100000;
5696 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::supported(), InitFeatures::supported());
5697 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5699 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5701 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5702 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5703 let err = nodes[0].node.send_payment(route, our_payment_hash);
5705 if let Err(APIError::ChannelUnavailable{err}) = err {
5706 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept");
5710 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5711 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);
5713 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5716 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5718 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5719 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5720 let chanmon_cfgs = create_chanmon_cfgs(2);
5721 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5722 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5723 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5724 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5725 let htlc_minimum_msat: u64;
5727 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5728 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5729 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5731 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5732 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5733 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5734 check_added_monitors!(nodes[0], 1);
5735 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5736 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5737 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5738 assert!(nodes[1].node.list_channels().is_empty());
5739 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5740 assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
5741 check_added_monitors!(nodes[1], 1);
5745 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5746 //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
5747 let chanmon_cfgs = create_chanmon_cfgs(2);
5748 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5749 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5750 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5751 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5753 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5755 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5756 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5757 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5758 check_added_monitors!(nodes[0], 1);
5759 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5761 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5762 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5764 assert!(nodes[1].node.list_channels().is_empty());
5765 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5766 assert_eq!(err_msg.data, "Remote HTLC add would put them over their reserve value");
5767 check_added_monitors!(nodes[1], 1);
5771 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5772 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5773 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5774 let chanmon_cfgs = create_chanmon_cfgs(2);
5775 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5776 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5777 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5778 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5779 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5780 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5782 let session_priv = SecretKey::from_slice(&{
5783 let mut session_key = [0; 32];
5784 let mut rng = thread_rng();
5785 rng.fill_bytes(&mut session_key);
5787 }).expect("RNG is bad!");
5789 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5790 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
5791 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5792 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
5794 let mut msg = msgs::UpdateAddHTLC {
5798 payment_hash: our_payment_hash,
5799 cltv_expiry: htlc_cltv,
5800 onion_routing_packet: onion_packet.clone(),
5803 for i in 0..super::channel::OUR_MAX_HTLCS {
5804 msg.htlc_id = i as u64;
5805 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5807 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5808 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5810 assert!(nodes[1].node.list_channels().is_empty());
5811 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5812 assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
5813 check_added_monitors!(nodes[1], 1);
5817 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5818 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5819 let chanmon_cfgs = create_chanmon_cfgs(2);
5820 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5821 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5822 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5823 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
5824 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5825 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5826 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5827 check_added_monitors!(nodes[0], 1);
5828 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5829 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5830 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
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 HTLC add would put them over our max HTLC value");
5835 check_added_monitors!(nodes[1], 1);
5839 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5840 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: 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 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::supported(), InitFeatures::supported());
5846 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, 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].cltv_expiry = 500000000;
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 provided CLTV expiry in seconds instead of block height");
5857 check_added_monitors!(nodes[1], 1);
5861 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5862 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5863 // We test this by first testing that that repeated HTLCs pass commitment signature checks
5864 // after disconnect and that non-sequential htlc_ids result in a channel failure.
5865 let chanmon_cfgs = create_chanmon_cfgs(2);
5866 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5867 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5868 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5869 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5870 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5871 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5872 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5873 check_added_monitors!(nodes[0], 1);
5874 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5875 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5877 //Disconnect and Reconnect
5878 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5879 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5880 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5881 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5882 assert_eq!(reestablish_1.len(), 1);
5883 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
5884 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5885 assert_eq!(reestablish_2.len(), 1);
5886 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
5887 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5888 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
5889 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5892 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5893 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5894 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
5895 check_added_monitors!(nodes[1], 1);
5896 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5898 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5900 assert!(nodes[1].node.list_channels().is_empty());
5901 let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
5902 assert_eq!(err_msg.data, "Remote skipped HTLC ID");
5903 check_added_monitors!(nodes[1], 1);
5907 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5908 //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.
5910 let chanmon_cfgs = create_chanmon_cfgs(2);
5911 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5912 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5913 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5914 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5916 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5917 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5918 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5919 check_added_monitors!(nodes[0], 1);
5920 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5921 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5923 let update_msg = msgs::UpdateFulfillHTLC{
5926 payment_preimage: our_payment_preimage,
5929 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5931 assert!(nodes[0].node.list_channels().is_empty());
5932 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5933 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5934 check_added_monitors!(nodes[0], 1);
5938 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5939 //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.
5941 let chanmon_cfgs = create_chanmon_cfgs(2);
5942 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5943 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5944 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5945 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5947 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5948 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5949 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5950 check_added_monitors!(nodes[0], 1);
5951 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5952 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5954 let update_msg = msgs::UpdateFailHTLC{
5957 reason: msgs::OnionErrorPacket { data: Vec::new()},
5960 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5962 assert!(nodes[0].node.list_channels().is_empty());
5963 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5964 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5965 check_added_monitors!(nodes[0], 1);
5969 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5970 //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.
5972 let chanmon_cfgs = create_chanmon_cfgs(2);
5973 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5974 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5975 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5976 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
5978 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5979 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5980 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5981 check_added_monitors!(nodes[0], 1);
5982 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5983 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5985 let update_msg = msgs::UpdateFailMalformedHTLC{
5988 sha256_of_onion: [1; 32],
5989 failure_code: 0x8000,
5992 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5994 assert!(nodes[0].node.list_channels().is_empty());
5995 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
5996 assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
5997 check_added_monitors!(nodes[0], 1);
6001 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6002 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6004 let chanmon_cfgs = create_chanmon_cfgs(2);
6005 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6006 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6007 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6008 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6010 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6012 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
6013 check_added_monitors!(nodes[1], 1);
6015 let events = nodes[1].node.get_and_clear_pending_msg_events();
6016 assert_eq!(events.len(), 1);
6017 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6019 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, .. } } => {
6020 assert!(update_add_htlcs.is_empty());
6021 assert_eq!(update_fulfill_htlcs.len(), 1);
6022 assert!(update_fail_htlcs.is_empty());
6023 assert!(update_fail_malformed_htlcs.is_empty());
6024 assert!(update_fee.is_none());
6025 update_fulfill_htlcs[0].clone()
6027 _ => panic!("Unexpected event"),
6031 update_fulfill_msg.htlc_id = 1;
6033 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6035 assert!(nodes[0].node.list_channels().is_empty());
6036 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6037 assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6038 check_added_monitors!(nodes[0], 1);
6042 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6043 //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.
6045 let chanmon_cfgs = create_chanmon_cfgs(2);
6046 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6047 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6048 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6049 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6051 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6053 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
6054 check_added_monitors!(nodes[1], 1);
6056 let events = nodes[1].node.get_and_clear_pending_msg_events();
6057 assert_eq!(events.len(), 1);
6058 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6060 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, .. } } => {
6061 assert!(update_add_htlcs.is_empty());
6062 assert_eq!(update_fulfill_htlcs.len(), 1);
6063 assert!(update_fail_htlcs.is_empty());
6064 assert!(update_fail_malformed_htlcs.is_empty());
6065 assert!(update_fee.is_none());
6066 update_fulfill_htlcs[0].clone()
6068 _ => panic!("Unexpected event"),
6072 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6074 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6076 assert!(nodes[0].node.list_channels().is_empty());
6077 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6078 assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6079 check_added_monitors!(nodes[0], 1);
6083 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6084 //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.
6086 let chanmon_cfgs = create_chanmon_cfgs(2);
6087 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6088 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6089 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6090 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6091 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
6092 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6093 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6094 check_added_monitors!(nodes[0], 1);
6096 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6097 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6099 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6100 check_added_monitors!(nodes[1], 0);
6101 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6103 let events = nodes[1].node.get_and_clear_pending_msg_events();
6105 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6107 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, .. } } => {
6108 assert!(update_add_htlcs.is_empty());
6109 assert!(update_fulfill_htlcs.is_empty());
6110 assert!(update_fail_htlcs.is_empty());
6111 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6112 assert!(update_fee.is_none());
6113 update_fail_malformed_htlcs[0].clone()
6115 _ => panic!("Unexpected event"),
6118 update_msg.failure_code &= !0x8000;
6119 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6121 assert!(nodes[0].node.list_channels().is_empty());
6122 let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6123 assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6124 check_added_monitors!(nodes[0], 1);
6128 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6129 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6130 // * 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.
6132 let chanmon_cfgs = create_chanmon_cfgs(3);
6133 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6134 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6135 let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6136 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6137 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6139 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
6140 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6143 let mut payment_event = {
6144 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
6145 check_added_monitors!(nodes[0], 1);
6146 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6147 assert_eq!(events.len(), 1);
6148 SendEvent::from_event(events.remove(0))
6150 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6151 check_added_monitors!(nodes[1], 0);
6152 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6153 expect_pending_htlcs_forwardable!(nodes[1]);
6154 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6155 assert_eq!(events_2.len(), 1);
6156 check_added_monitors!(nodes[1], 1);
6157 payment_event = SendEvent::from_event(events_2.remove(0));
6158 assert_eq!(payment_event.msgs.len(), 1);
6161 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6162 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6163 check_added_monitors!(nodes[2], 0);
6164 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6166 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6167 assert_eq!(events_3.len(), 1);
6168 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6170 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 } } => {
6171 assert!(update_add_htlcs.is_empty());
6172 assert!(update_fulfill_htlcs.is_empty());
6173 assert!(update_fail_htlcs.is_empty());
6174 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6175 assert!(update_fee.is_none());
6176 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6178 _ => panic!("Unexpected event"),
6182 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6184 check_added_monitors!(nodes[1], 0);
6185 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6186 expect_pending_htlcs_forwardable!(nodes[1]);
6187 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6188 assert_eq!(events_4.len(), 1);
6190 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
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, .. } } => {
6193 assert!(update_add_htlcs.is_empty());
6194 assert!(update_fulfill_htlcs.is_empty());
6195 assert_eq!(update_fail_htlcs.len(), 1);
6196 assert!(update_fail_malformed_htlcs.is_empty());
6197 assert!(update_fee.is_none());
6199 _ => panic!("Unexpected event"),
6202 check_added_monitors!(nodes[1], 1);
6205 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6206 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6207 // 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
6208 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6210 let chanmon_cfgs = create_chanmon_cfgs(2);
6211 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6212 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6213 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6214 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6216 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6218 // We route 2 dust-HTLCs between A and B
6219 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6220 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6221 route_payment(&nodes[0], &[&nodes[1]], 1000000);
6223 // Cache one local commitment tx as previous
6224 let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6226 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6227 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
6228 check_added_monitors!(nodes[1], 0);
6229 expect_pending_htlcs_forwardable!(nodes[1]);
6230 check_added_monitors!(nodes[1], 1);
6232 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6233 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6234 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6235 check_added_monitors!(nodes[0], 1);
6237 // Cache one local commitment tx as lastest
6238 let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6240 let events = nodes[0].node.get_and_clear_pending_msg_events();
6242 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6243 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6245 _ => panic!("Unexpected event"),
6248 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6249 assert_eq!(node_id, nodes[1].node.get_our_node_id());
6251 _ => panic!("Unexpected event"),
6254 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6255 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6256 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6258 if announce_latest {
6259 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6261 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6264 check_closed_broadcast!(nodes[0], false);
6265 check_added_monitors!(nodes[0], 1);
6267 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6268 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
6269 let events = nodes[0].node.get_and_clear_pending_events();
6270 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6271 assert_eq!(events.len(), 2);
6272 let mut first_failed = false;
6273 for event in events {
6275 Event::PaymentFailed { payment_hash, .. } => {
6276 if payment_hash == payment_hash_1 {
6277 assert!(!first_failed);
6278 first_failed = true;
6280 assert_eq!(payment_hash, payment_hash_2);
6283 _ => panic!("Unexpected event"),
6289 fn test_failure_delay_dust_htlc_local_commitment() {
6290 do_test_failure_delay_dust_htlc_local_commitment(true);
6291 do_test_failure_delay_dust_htlc_local_commitment(false);
6295 fn test_no_failure_dust_htlc_local_commitment() {
6296 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6297 // prone to error, we test here that a dummy transaction don't fail them.
6299 let chanmon_cfgs = create_chanmon_cfgs(2);
6300 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6301 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6302 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6303 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6306 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6308 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6309 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6311 // We route 2 dust-HTLCs between A and B
6312 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6313 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6315 // Build a dummy invalid transaction trying to spend a commitment tx
6317 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6318 script_sig: Script::new(),
6320 witness: Vec::new(),
6324 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6328 let dummy_tx = Transaction {
6335 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6336 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6337 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6338 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6339 // We broadcast a few more block to check everything is all right
6340 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.bitcoin_hash());
6341 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6342 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6344 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6345 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6348 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6349 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6350 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6351 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6352 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6353 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6354 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6356 let chanmon_cfgs = create_chanmon_cfgs(3);
6357 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6358 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6359 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6360 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6362 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6364 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6365 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6367 let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6368 let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6370 // We revoked bs_commitment_tx
6372 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6373 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6376 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6377 let mut timeout_tx = Vec::new();
6379 // We fail dust-HTLC 1 by broadcast of local commitment tx
6380 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6381 check_closed_broadcast!(nodes[0], false);
6382 check_added_monitors!(nodes[0], 1);
6383 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6384 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6385 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6386 let events = nodes[0].node.get_and_clear_pending_events();
6387 assert_eq!(events.len(), 1);
6389 Event::PaymentFailed { payment_hash, .. } => {
6390 assert_eq!(payment_hash, dust_hash);
6392 _ => panic!("Unexpected event"),
6394 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6395 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6396 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6397 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6398 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6399 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6400 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6401 let events = nodes[0].node.get_and_clear_pending_events();
6402 assert_eq!(events.len(), 1);
6404 Event::PaymentFailed { payment_hash, .. } => {
6405 assert_eq!(payment_hash, non_dust_hash);
6407 _ => panic!("Unexpected event"),
6410 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6411 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6412 check_closed_broadcast!(nodes[0], false);
6413 check_added_monitors!(nodes[0], 1);
6414 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6415 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6416 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6417 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6419 let events = nodes[0].node.get_and_clear_pending_events();
6420 assert_eq!(events.len(), 1);
6422 Event::PaymentFailed { payment_hash, .. } => {
6423 assert_eq!(payment_hash, dust_hash);
6425 _ => panic!("Unexpected event"),
6427 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6428 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6429 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6430 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6431 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6432 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6433 let events = nodes[0].node.get_and_clear_pending_events();
6434 assert_eq!(events.len(), 1);
6436 Event::PaymentFailed { payment_hash, .. } => {
6437 assert_eq!(payment_hash, non_dust_hash);
6439 _ => panic!("Unexpected event"),
6442 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6444 let events = nodes[0].node.get_and_clear_pending_events();
6445 assert_eq!(events.len(), 2);
6448 Event::PaymentFailed { payment_hash, .. } => {
6449 if payment_hash == dust_hash { first = true; }
6450 else { first = false; }
6452 _ => panic!("Unexpected event"),
6455 Event::PaymentFailed { payment_hash, .. } => {
6456 if first { assert_eq!(payment_hash, non_dust_hash); }
6457 else { assert_eq!(payment_hash, dust_hash); }
6459 _ => panic!("Unexpected event"),
6466 fn test_sweep_outbound_htlc_failure_update() {
6467 do_test_sweep_outbound_htlc_failure_update(false, true);
6468 do_test_sweep_outbound_htlc_failure_update(false, false);
6469 do_test_sweep_outbound_htlc_failure_update(true, false);
6473 fn test_upfront_shutdown_script() {
6474 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6475 // enforce it at shutdown message
6477 let mut config = UserConfig::default();
6478 config.channel_options.announced_channel = true;
6479 config.peer_channel_config_limits.force_announced_channel_preference = false;
6480 config.channel_options.commit_upfront_shutdown_pubkey = false;
6481 let user_cfgs = [None, Some(config), None];
6482 let chanmon_cfgs = create_chanmon_cfgs(3);
6483 let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6484 let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6485 let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6487 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6488 let flags = InitFeatures::supported();
6489 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6490 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6491 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6492 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6493 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
6494 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6495 assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6496 check_added_monitors!(nodes[2], 1);
6498 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6499 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6500 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6501 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6502 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6503 nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6504 let events = nodes[2].node.get_and_clear_pending_msg_events();
6505 assert_eq!(events.len(), 1);
6507 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6508 _ => panic!("Unexpected event"),
6511 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6512 let mut flags_no = InitFeatures::supported();
6513 flags_no.unset_upfront_shutdown_script();
6514 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6515 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6516 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6517 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6518 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6519 let events = nodes[1].node.get_and_clear_pending_msg_events();
6520 assert_eq!(events.len(), 1);
6522 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6523 _ => panic!("Unexpected event"),
6526 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6527 // channel smoothly, opt-out is from channel initiator here
6528 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6529 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6530 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6531 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6532 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6533 let events = nodes[0].node.get_and_clear_pending_msg_events();
6534 assert_eq!(events.len(), 1);
6536 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6537 _ => panic!("Unexpected event"),
6540 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6541 //// channel smoothly
6542 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6543 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6544 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6545 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6546 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6547 let events = nodes[0].node.get_and_clear_pending_msg_events();
6548 assert_eq!(events.len(), 2);
6550 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6551 _ => panic!("Unexpected event"),
6554 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6555 _ => panic!("Unexpected event"),
6560 fn test_user_configurable_csv_delay() {
6561 // We test our channel constructors yield errors when we pass them absurd csv delay
6563 let mut low_our_to_self_config = UserConfig::default();
6564 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6565 let mut high_their_to_self_config = UserConfig::default();
6566 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6567 let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6568 let chanmon_cfgs = create_chanmon_cfgs(2);
6569 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6570 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6571 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6573 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6574 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())));
6575 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) {
6577 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6578 _ => panic!("Unexpected event"),
6580 } else { assert!(false) }
6582 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6583 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6584 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6585 open_channel.to_self_delay = 200;
6586 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) {
6588 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6589 _ => panic!("Unexpected event"),
6591 } else { assert!(false); }
6593 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6594 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6595 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()));
6596 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6597 accept_channel.to_self_delay = 200;
6598 nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::supported(), &accept_channel);
6599 if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
6601 &ErrorAction::SendErrorMessage { ref msg } => {
6602 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6604 _ => { assert!(false); }
6606 } else { assert!(false); }
6608 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6609 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
6610 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6611 open_channel.to_self_delay = 200;
6612 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) {
6614 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6615 _ => panic!("Unexpected event"),
6617 } else { assert!(false); }
6621 fn test_data_loss_protect() {
6622 // We want to be sure that :
6623 // * we don't broadcast our Local Commitment Tx in case of fallen behind
6624 // * we close channel in case of detecting other being fallen behind
6625 // * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6631 let chanmon_cfgs = create_chanmon_cfgs(2);
6632 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6633 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6634 let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6636 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::supported(), InitFeatures::supported());
6638 // Cache node A state before any channel update
6639 let previous_node_state = nodes[0].node.encode();
6640 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6641 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6643 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6644 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6646 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6647 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6649 // Restore node A from previous state
6650 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6651 let mut chan_monitor = <(Sha256dHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6652 let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6653 tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
6654 fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
6655 keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger));
6656 monitor = test_utils::TestChannelMonitor::new(chain_monitor.clone(), &tx_broadcaster, logger.clone(), &fee_estimator);
6658 let mut channel_monitors = HashMap::new();
6659 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
6660 <(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 {
6661 keys_manager: &keys_manager,
6662 fee_estimator: &fee_estimator,
6664 logger: Arc::clone(&logger),
6665 tx_broadcaster: &tx_broadcaster,
6666 default_config: UserConfig::default(),
6667 channel_monitors: &mut channel_monitors,
6670 nodes[0].node = &node_state_0;
6671 assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
6672 nodes[0].chan_monitor = &monitor;
6673 nodes[0].chain_monitor = chain_monitor;
6675 nodes[0].block_notifier = BlockNotifier::new(nodes[0].chain_monitor.clone());
6676 nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
6677 nodes[0].block_notifier.register_listener(nodes[0].node);
6679 check_added_monitors!(nodes[0], 1);
6681 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6682 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6684 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6686 // Check we update monitor following learning of per_commitment_point from B
6687 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
6688 check_added_monitors!(nodes[0], 2);
6691 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6692 assert_eq!(node_txn.len(), 0);
6695 let mut reestablish_1 = Vec::with_capacity(1);
6696 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6697 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6698 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6699 reestablish_1.push(msg.clone());
6700 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6701 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
6703 &ErrorAction::SendErrorMessage { ref msg } => {
6704 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");
6706 _ => panic!("Unexpected event!"),
6709 panic!("Unexpected event")
6713 // Check we close channel detecting A is fallen-behind
6714 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6715 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
6716 check_added_monitors!(nodes[1], 1);
6719 // Check A is able to claim to_remote output
6720 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6721 assert_eq!(node_txn.len(), 1);
6722 check_spends!(node_txn[0], chan.3);
6723 assert_eq!(node_txn[0].output.len(), 2);
6724 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6725 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 1);
6726 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6727 assert_eq!(spend_txn.len(), 1);
6728 check_spends!(spend_txn[0], node_txn[0]);
6732 fn test_check_htlc_underpaying() {
6733 // Send payment through A -> B but A is maliciously
6734 // sending a probe payment (i.e less than expected value0
6735 // to B, B should refuse payment.
6737 let chanmon_cfgs = create_chanmon_cfgs(2);
6738 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6739 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6740 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6742 // Create some initial channels
6743 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported());
6745 let (payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
6747 // Node 3 is expecting payment of 100_000 but receive 10_000,
6748 // fail htlc like we didn't know the preimage.
6749 nodes[1].node.claim_funds(payment_preimage, 100_000);
6750 nodes[1].node.process_pending_htlc_forwards();
6752 let events = nodes[1].node.get_and_clear_pending_msg_events();
6753 assert_eq!(events.len(), 1);
6754 let (update_fail_htlc, commitment_signed) = match events[0] {
6755 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 } } => {
6756 assert!(update_add_htlcs.is_empty());
6757 assert!(update_fulfill_htlcs.is_empty());
6758 assert_eq!(update_fail_htlcs.len(), 1);
6759 assert!(update_fail_malformed_htlcs.is_empty());
6760 assert!(update_fee.is_none());
6761 (update_fail_htlcs[0].clone(), commitment_signed)
6763 _ => panic!("Unexpected event"),
6765 check_added_monitors!(nodes[1], 1);
6767 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
6768 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6770 let events = nodes[0].node.get_and_clear_pending_events();
6771 assert_eq!(events.len(), 1);
6772 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
6773 assert_eq!(*rejected_by_dest, true);
6774 assert_eq!(error_code.unwrap(), 0x4000|15);
6776 panic!("Unexpected event");
6778 nodes[1].node.get_and_clear_pending_events();
6782 fn test_announce_disable_channels() {
6783 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
6784 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6786 let chanmon_cfgs = create_chanmon_cfgs(2);
6787 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6788 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6789 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6791 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6792 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6793 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).0.contents.short_channel_id;
6796 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6797 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6799 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
6800 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
6801 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6802 assert_eq!(msg_events.len(), 3);
6803 for e in msg_events {
6805 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6806 let short_id = msg.contents.short_channel_id;
6807 // Check generated channel_update match list in PendingChannelUpdate
6808 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
6809 panic!("Generated ChannelUpdate for wrong chan!");
6812 _ => panic!("Unexpected event"),
6816 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6817 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6818 assert_eq!(reestablish_1.len(), 3);
6819 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6820 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6821 assert_eq!(reestablish_2.len(), 3);
6823 // Reestablish chan_1
6824 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6825 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6826 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6827 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6828 // Reestablish chan_2
6829 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
6830 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6831 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
6832 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6833 // Reestablish chan_3
6834 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
6835 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6836 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
6837 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6839 nodes[0].node.timer_chan_freshness_every_min();
6840 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6844 fn test_bump_penalty_txn_on_revoked_commitment() {
6845 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
6846 // we're able to claim outputs on revoked commitment transaction before timelocks expiration
6848 let chanmon_cfgs = create_chanmon_cfgs(2);
6849 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6850 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6851 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6853 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6854 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
6855 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30).unwrap();
6856 send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
6858 let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
6859 // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
6860 assert_eq!(revoked_txn[0].output.len(), 4);
6861 assert_eq!(revoked_txn[0].input.len(), 1);
6862 assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
6863 let revoked_txid = revoked_txn[0].txid();
6865 let mut penalty_sum = 0;
6866 for outp in revoked_txn[0].output.iter() {
6867 if outp.script_pubkey.is_v0_p2wsh() {
6868 penalty_sum += outp.value;
6872 // Connect blocks to change height_timer range to see if we use right soonest_timelock
6873 let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
6875 // Actually revoke tx by claiming a HTLC
6876 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6877 let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6878 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
6879 check_added_monitors!(nodes[1], 1);
6881 // One or more justice tx should have been broadcast, check it
6885 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6886 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
6887 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6888 assert_eq!(node_txn[0].output.len(), 1);
6889 check_spends!(node_txn[0], revoked_txn[0]);
6890 let fee_1 = penalty_sum - node_txn[0].output[0].value;
6891 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
6892 penalty_1 = node_txn[0].txid();
6896 // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
6897 let header = connect_blocks(&nodes[1].block_notifier, 3, 115, true, header.bitcoin_hash());
6898 let mut penalty_2 = penalty_1;
6899 let mut feerate_2 = 0;
6901 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6902 assert_eq!(node_txn.len(), 1);
6903 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6904 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6905 assert_eq!(node_txn[0].output.len(), 1);
6906 check_spends!(node_txn[0], revoked_txn[0]);
6907 penalty_2 = node_txn[0].txid();
6908 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6909 assert_ne!(penalty_2, penalty_1);
6910 let fee_2 = penalty_sum - node_txn[0].output[0].value;
6911 feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
6912 // Verify 25% bump heuristic
6913 assert!(feerate_2 * 100 >= feerate_1 * 125);
6917 assert_ne!(feerate_2, 0);
6919 // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
6920 connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
6922 let mut feerate_3 = 0;
6924 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6925 assert_eq!(node_txn.len(), 1);
6926 if node_txn[0].input[0].previous_output.txid == revoked_txid {
6927 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
6928 assert_eq!(node_txn[0].output.len(), 1);
6929 check_spends!(node_txn[0], revoked_txn[0]);
6930 penalty_3 = node_txn[0].txid();
6931 // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
6932 assert_ne!(penalty_3, penalty_2);
6933 let fee_3 = penalty_sum - node_txn[0].output[0].value;
6934 feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
6935 // Verify 25% bump heuristic
6936 assert!(feerate_3 * 100 >= feerate_2 * 125);
6940 assert_ne!(feerate_3, 0);
6942 nodes[1].node.get_and_clear_pending_events();
6943 nodes[1].node.get_and_clear_pending_msg_events();
6947 fn test_bump_penalty_txn_on_revoked_htlcs() {
6948 // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
6949 // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
6951 let chanmon_cfgs = create_chanmon_cfgs(2);
6952 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6953 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6954 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6956 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
6957 // Lock HTLC in both directions
6958 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
6959 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
6961 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
6962 assert_eq!(revoked_local_txn[0].input.len(), 1);
6963 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
6965 // Revoke local commitment tx
6966 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
6968 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6969 // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
6970 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
6971 check_closed_broadcast!(nodes[1], false);
6972 check_added_monitors!(nodes[1], 1);
6974 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
6975 assert_eq!(revoked_htlc_txn.len(), 6);
6976 if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6977 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
6978 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
6979 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
6980 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6981 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
6982 } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
6983 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
6984 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
6985 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
6986 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6987 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
6990 // Broadcast set of revoked txn on A
6991 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
6992 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6993 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);
6998 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
6999 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7000 // Verify claim tx are spending revoked HTLC txn
7001 assert_eq!(node_txn[4].input.len(), 2);
7002 assert_eq!(node_txn[4].output.len(), 1);
7003 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7004 first = node_txn[4].txid();
7005 // Store both feerates for later comparison
7006 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7007 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7008 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7012 // Connect three more block to see if bumped penalty are issued for HTLC txn
7013 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7014 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7016 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7017 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7019 check_spends!(node_txn[0], revoked_local_txn[0]);
7020 check_spends!(node_txn[1], revoked_local_txn[0]);
7025 // Few more blocks to confirm penalty txn
7026 let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7027 assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7028 let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7030 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7031 assert_eq!(node_txn.len(), 1);
7033 assert_eq!(node_txn[0].input.len(), 2);
7034 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7035 // Verify bumped tx is different and 25% bump heuristic
7036 assert_ne!(first, node_txn[0].txid());
7037 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7038 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7039 assert!(feerate_2 * 100 > feerate_1 * 125);
7040 let txn = vec![node_txn[0].clone()];
7044 // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7045 let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7046 nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7047 connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7049 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7050 // We verify than no new transaction has been broadcast because previously
7051 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7052 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7053 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7054 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7055 // up bumped justice generation.
7056 assert_eq!(node_txn.len(), 0);
7059 check_closed_broadcast!(nodes[0], false);
7060 check_added_monitors!(nodes[0], 1);
7064 fn test_bump_penalty_txn_on_remote_commitment() {
7065 // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7066 // we're able to claim outputs on remote commitment transaction before timelocks expiration
7069 // Provide preimage for one
7070 // Check aggregation
7072 let chanmon_cfgs = create_chanmon_cfgs(2);
7073 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7074 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7075 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7077 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7078 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7079 route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7081 // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7082 let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7083 assert_eq!(remote_txn[0].output.len(), 4);
7084 assert_eq!(remote_txn[0].input.len(), 1);
7085 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7087 // Claim a HTLC without revocation (provide B monitor with preimage)
7088 nodes[1].node.claim_funds(payment_preimage, 3_000_000);
7089 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7090 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7091 check_added_monitors!(nodes[1], 2);
7093 // One or more claim tx should have been broadcast, check it
7096 let feerate_timeout;
7097 let feerate_preimage;
7099 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7100 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7101 assert_eq!(node_txn[0].input.len(), 1);
7102 assert_eq!(node_txn[1].input.len(), 1);
7103 check_spends!(node_txn[0], remote_txn[0]);
7104 check_spends!(node_txn[1], remote_txn[0]);
7105 check_spends!(node_txn[2], chan.3);
7106 check_spends!(node_txn[3], node_txn[2]);
7107 check_spends!(node_txn[4], node_txn[2]);
7108 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7109 timeout = node_txn[0].txid();
7110 let index = node_txn[0].input[0].previous_output.vout;
7111 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7112 feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7114 preimage = node_txn[1].txid();
7115 let index = node_txn[1].input[0].previous_output.vout;
7116 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7117 feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7119 timeout = node_txn[1].txid();
7120 let index = node_txn[1].input[0].previous_output.vout;
7121 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7122 feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7124 preimage = node_txn[0].txid();
7125 let index = node_txn[0].input[0].previous_output.vout;
7126 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7127 feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7131 assert_ne!(feerate_timeout, 0);
7132 assert_ne!(feerate_preimage, 0);
7134 // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7135 connect_blocks(&nodes[1].block_notifier, 15, 1, true, header.bitcoin_hash());
7137 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7138 assert_eq!(node_txn.len(), 2);
7139 assert_eq!(node_txn[0].input.len(), 1);
7140 assert_eq!(node_txn[1].input.len(), 1);
7141 check_spends!(node_txn[0], remote_txn[0]);
7142 check_spends!(node_txn[1], remote_txn[0]);
7143 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7144 let index = node_txn[0].input[0].previous_output.vout;
7145 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7146 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7147 assert!(new_feerate * 100 > feerate_timeout * 125);
7148 assert_ne!(timeout, node_txn[0].txid());
7150 let index = node_txn[1].input[0].previous_output.vout;
7151 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7152 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7153 assert!(new_feerate * 100 > feerate_preimage * 125);
7154 assert_ne!(preimage, node_txn[1].txid());
7156 let index = node_txn[1].input[0].previous_output.vout;
7157 let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7158 let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7159 assert!(new_feerate * 100 > feerate_timeout * 125);
7160 assert_ne!(timeout, node_txn[1].txid());
7162 let index = node_txn[0].input[0].previous_output.vout;
7163 let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7164 let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7165 assert!(new_feerate * 100 > feerate_preimage * 125);
7166 assert_ne!(preimage, node_txn[0].txid());
7171 nodes[1].node.get_and_clear_pending_events();
7172 nodes[1].node.get_and_clear_pending_msg_events();
7176 fn test_set_outpoints_partial_claiming() {
7177 // - remote party claim tx, new bump tx
7178 // - disconnect remote claiming tx, new bump
7179 // - disconnect tx, see no tx anymore
7180 let chanmon_cfgs = create_chanmon_cfgs(2);
7181 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7182 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7183 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7185 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7186 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7187 let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7189 // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7190 let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7191 assert_eq!(remote_txn.len(), 3);
7192 assert_eq!(remote_txn[0].output.len(), 4);
7193 assert_eq!(remote_txn[0].input.len(), 1);
7194 assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7195 check_spends!(remote_txn[1], remote_txn[0]);
7196 check_spends!(remote_txn[2], remote_txn[0]);
7198 // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7199 let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7200 // Provide node A with both preimage
7201 nodes[0].node.claim_funds(payment_preimage_1, 3_000_000);
7202 nodes[0].node.claim_funds(payment_preimage_2, 3_000_000);
7203 check_added_monitors!(nodes[0], 2);
7204 nodes[0].node.get_and_clear_pending_events();
7205 nodes[0].node.get_and_clear_pending_msg_events();
7207 // Connect blocks on node A commitment transaction
7208 let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7209 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7210 check_closed_broadcast!(nodes[0], false);
7211 check_added_monitors!(nodes[0], 1);
7212 // Verify node A broadcast tx claiming both HTLCs
7214 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7215 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7216 assert_eq!(node_txn.len(), 4);
7217 check_spends!(node_txn[0], remote_txn[0]);
7218 check_spends!(node_txn[1], chan.3);
7219 check_spends!(node_txn[2], node_txn[1]);
7220 check_spends!(node_txn[3], node_txn[1]);
7221 assert_eq!(node_txn[0].input.len(), 2);
7225 // Connect blocks on node B
7226 connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7227 check_closed_broadcast!(nodes[1], false);
7228 check_added_monitors!(nodes[1], 1);
7229 // Verify node B broadcast 2 HTLC-timeout txn
7230 let partial_claim_tx = {
7231 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7232 assert_eq!(node_txn.len(), 3);
7233 check_spends!(node_txn[1], node_txn[0]);
7234 check_spends!(node_txn[2], node_txn[0]);
7235 assert_eq!(node_txn[1].input.len(), 1);
7236 assert_eq!(node_txn[2].input.len(), 1);
7240 // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7241 let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7242 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7244 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7245 assert_eq!(node_txn.len(), 1);
7246 check_spends!(node_txn[0], remote_txn[0]);
7247 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7250 nodes[0].node.get_and_clear_pending_msg_events();
7252 // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7253 nodes[0].block_notifier.block_disconnected(&header, 102);
7255 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7256 assert_eq!(node_txn.len(), 1);
7257 check_spends!(node_txn[0], remote_txn[0]);
7258 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7262 //// Disconnect one more block and then reconnect multiple no transaction should be generated
7263 nodes[0].block_notifier.block_disconnected(&header, 101);
7264 connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7266 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7267 assert_eq!(node_txn.len(), 0);
7273 fn test_counterparty_raa_skip_no_crash() {
7274 // Previously, if our counterparty sent two RAAs in a row without us having provided a
7275 // commitment transaction, we would have happily carried on and provided them the next
7276 // commitment transaction based on one RAA forward. This would probably eventually have led to
7277 // channel closure, but it would not have resulted in funds loss. Still, our
7278 // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7279 // check simply that the channel is closed in response to such an RAA, but don't check whether
7280 // we decide to punish our counterparty for revoking their funds (as we don't currently
7282 let chanmon_cfgs = create_chanmon_cfgs(2);
7283 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7284 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7285 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7286 let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::supported(), InitFeatures::supported()).2;
7288 let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7289 const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7290 let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7291 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7292 let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7294 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7295 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7296 assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7297 check_added_monitors!(nodes[1], 1);
7301 fn test_bump_txn_sanitize_tracking_maps() {
7302 // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7303 // verify we clean then right after expiration of ANTI_REORG_DELAY.
7305 let chanmon_cfgs = create_chanmon_cfgs(2);
7306 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7307 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7308 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7310 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::supported(), InitFeatures::supported());
7311 // Lock HTLC in both directions
7312 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7313 route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7315 let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7316 assert_eq!(revoked_local_txn[0].input.len(), 1);
7317 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7319 // Revoke local commitment tx
7320 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7322 // Broadcast set of revoked txn on A
7323 let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, false, Default::default());
7324 let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7325 nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7326 check_closed_broadcast!(nodes[0], false);
7327 check_added_monitors!(nodes[0], 1);
7329 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7330 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7331 check_spends!(node_txn[0], revoked_local_txn[0]);
7332 check_spends!(node_txn[1], revoked_local_txn[0]);
7333 check_spends!(node_txn[2], revoked_local_txn[0]);
7334 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7338 let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7339 nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7340 connect_blocks(&nodes[0].block_notifier, 5, 130, false, header_130.bitcoin_hash());
7342 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7343 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7344 assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7345 assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7351 fn test_override_channel_config() {
7352 let chanmon_cfgs = create_chanmon_cfgs(2);
7353 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7354 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7355 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7357 // Node0 initiates a channel to node1 using the override config.
7358 let mut override_config = UserConfig::default();
7359 override_config.own_channel_config.our_to_self_delay = 200;
7361 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7363 // Assert the channel created by node0 is using the override config.
7364 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7365 assert_eq!(res.channel_flags, 0);
7366 assert_eq!(res.to_self_delay, 200);
7370 fn test_override_0msat_htlc_minimum() {
7371 let mut zero_config = UserConfig::default();
7372 zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7373 let chanmon_cfgs = create_chanmon_cfgs(2);
7374 let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7375 let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7376 let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7378 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7379 let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7380 assert_eq!(res.htlc_minimum_msat, 1);
7382 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::supported(), &res);
7383 let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7384 assert_eq!(res.htlc_minimum_msat, 1);