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::chaininterface::{ChainListener, ChainWatchInterface};
7 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor, KeysManager};
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::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT, Channel, ChannelError};
13 use ln::router::{Route, RouteHop};
15 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, LocalFeatures, ErrorAction};
17 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
18 use util::errors::APIError;
19 use util::ser::{Writeable, ReadableArgs};
20 use util::config::UserConfig;
22 use bitcoin::util::hash::BitcoinHash;
23 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
24 use bitcoin::util::bip143;
25 use bitcoin::util::address::Address;
26 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
27 use bitcoin::blockdata::block::{Block, BlockHeader};
28 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
29 use bitcoin::blockdata::script::{Builder, Script};
30 use bitcoin::blockdata::opcodes;
31 use bitcoin::blockdata::constants::genesis_block;
32 use bitcoin::network::constants::Network;
34 use bitcoin_hashes::sha256::Hash as Sha256;
35 use bitcoin_hashes::Hash;
37 use secp256k1::{Secp256k1, Message};
38 use secp256k1::key::{PublicKey,SecretKey};
40 use std::collections::{BTreeSet, HashMap, HashSet};
41 use std::default::Default;
43 use std::sync::atomic::Ordering;
46 use rand::{thread_rng, Rng};
48 use ln::functional_test_utils::*;
51 fn test_insane_channel_opens() {
52 // Stand up a network of 2 nodes
53 let nodes = create_network(2, &[None, None]);
55 // Instantiate channel parameters where we push the maximum msats given our
57 let channel_value_sat = 31337; // same as funding satoshis
58 let channel_reserve_satoshis = Channel::get_our_channel_reserve_satoshis(channel_value_sat);
59 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
61 // Have node0 initiate a channel to node1 with aforementioned parameters
62 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42).unwrap();
64 // Extract the channel open message from node0 to node1
65 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
67 // Test helper that asserts we get the correct error string given a mutator
68 // that supposedly makes the channel open message insane
69 let insane_open_helper = |expected_error_str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
70 match nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &message_mutator(open_channel_message.clone())) {
71 Err(msgs::HandleError{ err: error_str, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) => {
72 assert_eq!(error_str, expected_error_str, "unexpected HandleError string (expected `{}`, actual `{}`)", expected_error_str, error_str)
74 Err(msgs::HandleError{..}) => {panic!("unexpected HandleError action")},
75 _ => panic!("insane OpenChannel message was somehow Ok"),
79 use ln::channel::MAX_FUNDING_SATOSHIS;
80 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
82 // Test all mutations that would make the channel open message insane
83 insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
85 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
87 insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
89 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
91 insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
93 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 });
95 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 });
97 insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
99 insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
103 fn test_async_inbound_update_fee() {
104 let mut nodes = create_network(2, &[None, None]);
105 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
106 let channel_id = chan.2;
109 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
113 // send (1) commitment_signed -.
114 // <- update_add_htlc/commitment_signed
115 // send (2) RAA (awaiting remote revoke) -.
116 // (1) commitment_signed is delivered ->
117 // .- send (3) RAA (awaiting remote revoke)
118 // (2) RAA is delivered ->
119 // .- send (4) commitment_signed
120 // <- (3) RAA is delivered
121 // send (5) commitment_signed -.
122 // <- (4) commitment_signed is delivered
124 // (5) commitment_signed is delivered ->
126 // (6) RAA is delivered ->
128 // First nodes[0] generates an update_fee
129 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
130 check_added_monitors!(nodes[0], 1);
132 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
133 assert_eq!(events_0.len(), 1);
134 let (update_msg, commitment_signed) = match events_0[0] { // (1)
135 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
136 (update_fee.as_ref(), commitment_signed)
138 _ => panic!("Unexpected event"),
141 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
143 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
144 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
145 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();
146 check_added_monitors!(nodes[1], 1);
148 let payment_event = {
149 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
150 assert_eq!(events_1.len(), 1);
151 SendEvent::from_event(events_1.remove(0))
153 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
154 assert_eq!(payment_event.msgs.len(), 1);
156 // ...now when the messages get delivered everyone should be happy
157 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
158 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
159 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
160 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
161 check_added_monitors!(nodes[0], 1);
163 // deliver(1), generate (3):
164 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
165 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
166 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
167 check_added_monitors!(nodes[1], 1);
169 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
170 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
171 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
172 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
173 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
174 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
175 assert!(bs_update.update_fee.is_none()); // (4)
176 check_added_monitors!(nodes[1], 1);
178 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
179 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
180 assert!(as_update.update_add_htlcs.is_empty()); // (5)
181 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
182 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
183 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
184 assert!(as_update.update_fee.is_none()); // (5)
185 check_added_monitors!(nodes[0], 1);
187 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
188 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
189 // only (6) so get_event_msg's assert(len == 1) passes
190 check_added_monitors!(nodes[0], 1);
192 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
193 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
194 check_added_monitors!(nodes[1], 1);
196 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
197 check_added_monitors!(nodes[0], 1);
199 let events_2 = nodes[0].node.get_and_clear_pending_events();
200 assert_eq!(events_2.len(), 1);
202 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
203 _ => panic!("Unexpected event"),
206 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
207 check_added_monitors!(nodes[1], 1);
211 fn test_update_fee_unordered_raa() {
212 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
213 // crash in an earlier version of the update_fee patch)
214 let mut nodes = create_network(2, &[None, None]);
215 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
216 let channel_id = chan.2;
219 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
221 // First nodes[0] generates an update_fee
222 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
223 check_added_monitors!(nodes[0], 1);
225 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
226 assert_eq!(events_0.len(), 1);
227 let update_msg = match events_0[0] { // (1)
228 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
231 _ => panic!("Unexpected event"),
234 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
236 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
237 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
238 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();
239 check_added_monitors!(nodes[1], 1);
241 let payment_event = {
242 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
243 assert_eq!(events_1.len(), 1);
244 SendEvent::from_event(events_1.remove(0))
246 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
247 assert_eq!(payment_event.msgs.len(), 1);
249 // ...now when the messages get delivered everyone should be happy
250 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
251 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
252 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
253 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
254 check_added_monitors!(nodes[0], 1);
256 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
257 check_added_monitors!(nodes[1], 1);
259 // We can't continue, sadly, because our (1) now has a bogus signature
263 fn test_multi_flight_update_fee() {
264 let nodes = create_network(2, &[None, None]);
265 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
266 let channel_id = chan.2;
269 // update_fee/commitment_signed ->
270 // .- send (1) RAA and (2) commitment_signed
271 // update_fee (never committed) ->
273 // We have to manually generate the above update_fee, it is allowed by the protocol but we
274 // don't track which updates correspond to which revoke_and_ack responses so we're in
275 // AwaitingRAA mode and will not generate the update_fee yet.
276 // <- (1) RAA delivered
277 // (3) is generated and send (4) CS -.
278 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
279 // know the per_commitment_point to use for it.
280 // <- (2) commitment_signed delivered
282 // B should send no response here
283 // (4) commitment_signed delivered ->
284 // <- RAA/commitment_signed delivered
287 // First nodes[0] generates an update_fee
288 let initial_feerate = get_feerate!(nodes[0], channel_id);
289 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
290 check_added_monitors!(nodes[0], 1);
292 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
293 assert_eq!(events_0.len(), 1);
294 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
295 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
296 (update_fee.as_ref().unwrap(), commitment_signed)
298 _ => panic!("Unexpected event"),
301 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
302 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
303 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
304 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
305 check_added_monitors!(nodes[1], 1);
307 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
309 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
310 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
311 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
313 // Create the (3) update_fee message that nodes[0] will generate before it does...
314 let mut update_msg_2 = msgs::UpdateFee {
315 channel_id: update_msg_1.channel_id.clone(),
316 feerate_per_kw: (initial_feerate + 30) as u32,
319 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
321 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
323 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
325 // Deliver (1), generating (3) and (4)
326 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
327 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
328 check_added_monitors!(nodes[0], 1);
329 assert!(as_second_update.update_add_htlcs.is_empty());
330 assert!(as_second_update.update_fulfill_htlcs.is_empty());
331 assert!(as_second_update.update_fail_htlcs.is_empty());
332 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
333 // Check that the update_fee newly generated matches what we delivered:
334 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
335 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
337 // Deliver (2) commitment_signed
338 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
339 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
340 check_added_monitors!(nodes[0], 1);
341 // No commitment_signed so get_event_msg's assert(len == 1) passes
343 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
344 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
345 check_added_monitors!(nodes[1], 1);
348 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
349 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
350 check_added_monitors!(nodes[1], 1);
352 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
353 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
354 check_added_monitors!(nodes[0], 1);
356 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
357 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
358 // No commitment_signed so get_event_msg's assert(len == 1) passes
359 check_added_monitors!(nodes[0], 1);
361 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
362 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
363 check_added_monitors!(nodes[1], 1);
367 fn test_update_fee_vanilla() {
368 let nodes = create_network(2, &[None, None]);
369 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
370 let channel_id = chan.2;
372 let feerate = get_feerate!(nodes[0], channel_id);
373 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
374 check_added_monitors!(nodes[0], 1);
376 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
377 assert_eq!(events_0.len(), 1);
378 let (update_msg, commitment_signed) = match events_0[0] {
379 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 } } => {
380 (update_fee.as_ref(), commitment_signed)
382 _ => panic!("Unexpected event"),
384 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
386 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
387 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
388 check_added_monitors!(nodes[1], 1);
390 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
391 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
392 check_added_monitors!(nodes[0], 1);
394 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
395 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
396 // No commitment_signed so get_event_msg's assert(len == 1) passes
397 check_added_monitors!(nodes[0], 1);
399 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
400 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
401 check_added_monitors!(nodes[1], 1);
405 fn test_update_fee_that_funder_cannot_afford() {
406 let nodes = create_network(2, &[None, None]);
407 let channel_value = 1888;
408 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, LocalFeatures::new(), LocalFeatures::new());
409 let channel_id = chan.2;
412 nodes[0].node.update_fee(channel_id, feerate).unwrap();
413 check_added_monitors!(nodes[0], 1);
414 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
416 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
418 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
420 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
421 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
423 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
424 let chan = chan_lock.by_id.get(&channel_id).unwrap();
426 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
427 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
428 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
429 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
430 actual_fee = channel_value - actual_fee;
431 assert_eq!(total_fee, actual_fee);
434 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
435 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
436 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
437 check_added_monitors!(nodes[0], 1);
439 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
441 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
443 //While producing the commitment_signed response after handling a received update_fee request the
444 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
445 //Should produce and error.
446 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
448 assert!(match err.err {
449 "Funding remote cannot afford proposed new fee" => true,
453 //clear the message we could not handle
454 nodes[1].node.get_and_clear_pending_msg_events();
458 fn test_update_fee_with_fundee_update_add_htlc() {
459 let mut nodes = create_network(2, &[None, None]);
460 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
461 let channel_id = chan.2;
464 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
466 let feerate = get_feerate!(nodes[0], channel_id);
467 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
468 check_added_monitors!(nodes[0], 1);
470 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
471 assert_eq!(events_0.len(), 1);
472 let (update_msg, commitment_signed) = match events_0[0] {
473 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 } } => {
474 (update_fee.as_ref(), commitment_signed)
476 _ => panic!("Unexpected event"),
478 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
479 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
480 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
481 check_added_monitors!(nodes[1], 1);
483 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
485 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
487 // nothing happens since node[1] is in AwaitingRemoteRevoke
488 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
490 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
491 assert_eq!(added_monitors.len(), 0);
492 added_monitors.clear();
494 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
495 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
496 // node[1] has nothing to do
498 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
499 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
500 check_added_monitors!(nodes[0], 1);
502 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
503 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
504 // No commitment_signed so get_event_msg's assert(len == 1) passes
505 check_added_monitors!(nodes[0], 1);
506 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
507 check_added_monitors!(nodes[1], 1);
508 // AwaitingRemoteRevoke ends here
510 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
511 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
512 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
513 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
514 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
515 assert_eq!(commitment_update.update_fee.is_none(), true);
517 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
518 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
519 check_added_monitors!(nodes[0], 1);
520 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
522 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
523 check_added_monitors!(nodes[1], 1);
524 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
526 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
527 check_added_monitors!(nodes[1], 1);
528 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
529 // No commitment_signed so get_event_msg's assert(len == 1) passes
531 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
532 check_added_monitors!(nodes[0], 1);
533 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
535 expect_pending_htlcs_forwardable!(nodes[0]);
537 let events = nodes[0].node.get_and_clear_pending_events();
538 assert_eq!(events.len(), 1);
540 Event::PaymentReceived { .. } => { },
541 _ => panic!("Unexpected event"),
544 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
546 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
547 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
548 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
552 fn test_update_fee() {
553 let nodes = create_network(2, &[None, None]);
554 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
555 let channel_id = chan.2;
558 // (1) update_fee/commitment_signed ->
559 // <- (2) revoke_and_ack
560 // .- send (3) commitment_signed
561 // (4) update_fee/commitment_signed ->
562 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
563 // <- (3) commitment_signed delivered
564 // send (6) revoke_and_ack -.
565 // <- (5) deliver revoke_and_ack
566 // (6) deliver revoke_and_ack ->
567 // .- send (7) commitment_signed in response to (4)
568 // <- (7) deliver commitment_signed
571 // Create and deliver (1)...
572 let feerate = get_feerate!(nodes[0], channel_id);
573 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
574 check_added_monitors!(nodes[0], 1);
576 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
577 assert_eq!(events_0.len(), 1);
578 let (update_msg, commitment_signed) = match events_0[0] {
579 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 } } => {
580 (update_fee.as_ref(), commitment_signed)
582 _ => panic!("Unexpected event"),
584 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
586 // Generate (2) and (3):
587 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
588 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
589 check_added_monitors!(nodes[1], 1);
592 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
593 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
594 check_added_monitors!(nodes[0], 1);
596 // Create and deliver (4)...
597 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
598 check_added_monitors!(nodes[0], 1);
599 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
600 assert_eq!(events_0.len(), 1);
601 let (update_msg, commitment_signed) = match events_0[0] {
602 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 } } => {
603 (update_fee.as_ref(), commitment_signed)
605 _ => panic!("Unexpected event"),
608 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
609 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
610 check_added_monitors!(nodes[1], 1);
612 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
613 // No commitment_signed so get_event_msg's assert(len == 1) passes
615 // Handle (3), creating (6):
616 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
617 check_added_monitors!(nodes[0], 1);
618 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
619 // No commitment_signed so get_event_msg's assert(len == 1) passes
622 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
623 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
624 check_added_monitors!(nodes[0], 1);
626 // Deliver (6), creating (7):
627 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
628 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
629 assert!(commitment_update.update_add_htlcs.is_empty());
630 assert!(commitment_update.update_fulfill_htlcs.is_empty());
631 assert!(commitment_update.update_fail_htlcs.is_empty());
632 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
633 assert!(commitment_update.update_fee.is_none());
634 check_added_monitors!(nodes[1], 1);
637 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
638 check_added_monitors!(nodes[0], 1);
639 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
640 // No commitment_signed so get_event_msg's assert(len == 1) passes
642 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
643 check_added_monitors!(nodes[1], 1);
644 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
646 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
647 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
648 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
652 fn pre_funding_lock_shutdown_test() {
653 // Test sending a shutdown prior to funding_locked after funding generation
654 let nodes = create_network(2, &[None, None]);
655 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, LocalFeatures::new(), LocalFeatures::new());
656 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
657 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
658 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
660 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
661 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
662 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
663 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
664 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
666 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
667 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
668 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
669 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
670 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
671 assert!(node_0_none.is_none());
673 assert!(nodes[0].node.list_channels().is_empty());
674 assert!(nodes[1].node.list_channels().is_empty());
678 fn updates_shutdown_wait() {
679 // Test sending a shutdown with outstanding updates pending
680 let mut nodes = create_network(3, &[None, None, None]);
681 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
682 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
683 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
684 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
686 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
688 nodes[0].node.close_channel(&chan_1.2).unwrap();
689 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
690 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
691 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
692 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
694 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
695 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
697 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
698 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
699 else { panic!("New sends should fail!") };
700 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
701 else { panic!("New sends should fail!") };
703 assert!(nodes[2].node.claim_funds(our_payment_preimage));
704 check_added_monitors!(nodes[2], 1);
705 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
706 assert!(updates.update_add_htlcs.is_empty());
707 assert!(updates.update_fail_htlcs.is_empty());
708 assert!(updates.update_fail_malformed_htlcs.is_empty());
709 assert!(updates.update_fee.is_none());
710 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
711 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
712 check_added_monitors!(nodes[1], 1);
713 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
714 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
716 assert!(updates_2.update_add_htlcs.is_empty());
717 assert!(updates_2.update_fail_htlcs.is_empty());
718 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
719 assert!(updates_2.update_fee.is_none());
720 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
721 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
722 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
724 let events = nodes[0].node.get_and_clear_pending_events();
725 assert_eq!(events.len(), 1);
727 Event::PaymentSent { ref payment_preimage } => {
728 assert_eq!(our_payment_preimage, *payment_preimage);
730 _ => panic!("Unexpected event"),
733 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
734 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
735 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
736 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
737 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
738 assert!(node_0_none.is_none());
740 assert!(nodes[0].node.list_channels().is_empty());
742 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
743 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
744 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
745 assert!(nodes[1].node.list_channels().is_empty());
746 assert!(nodes[2].node.list_channels().is_empty());
750 fn htlc_fail_async_shutdown() {
751 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
752 let mut nodes = create_network(3, &[None, None, None]);
753 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
754 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
756 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
757 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
758 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
759 check_added_monitors!(nodes[0], 1);
760 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
761 assert_eq!(updates.update_add_htlcs.len(), 1);
762 assert!(updates.update_fulfill_htlcs.is_empty());
763 assert!(updates.update_fail_htlcs.is_empty());
764 assert!(updates.update_fail_malformed_htlcs.is_empty());
765 assert!(updates.update_fee.is_none());
767 nodes[1].node.close_channel(&chan_1.2).unwrap();
768 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
769 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
770 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
772 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
773 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
774 check_added_monitors!(nodes[1], 1);
775 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
776 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
778 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
779 assert!(updates_2.update_add_htlcs.is_empty());
780 assert!(updates_2.update_fulfill_htlcs.is_empty());
781 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
782 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
783 assert!(updates_2.update_fee.is_none());
785 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
786 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
788 let events = nodes[0].node.get_and_clear_pending_events();
789 assert_eq!(events.len(), 1);
791 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
792 assert_eq!(our_payment_hash, *payment_hash);
793 assert!(!rejected_by_dest);
795 _ => panic!("Unexpected event"),
798 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
799 assert_eq!(msg_events.len(), 2);
800 let node_0_closing_signed = match msg_events[0] {
801 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
802 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
805 _ => panic!("Unexpected event"),
807 match msg_events[1] {
808 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
809 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
811 _ => panic!("Unexpected event"),
814 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
815 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
816 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
817 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
818 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
819 assert!(node_0_none.is_none());
821 assert!(nodes[0].node.list_channels().is_empty());
823 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
824 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
825 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
826 assert!(nodes[1].node.list_channels().is_empty());
827 assert!(nodes[2].node.list_channels().is_empty());
830 fn do_test_shutdown_rebroadcast(recv_count: u8) {
831 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
832 // messages delivered prior to disconnect
833 let nodes = create_network(3, &[None, None, None]);
834 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
835 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
837 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
839 nodes[1].node.close_channel(&chan_1.2).unwrap();
840 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
842 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
843 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
845 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
849 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
850 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
852 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
853 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
854 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
855 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
857 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
858 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
859 assert!(node_1_shutdown == node_1_2nd_shutdown);
861 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
862 let node_0_2nd_shutdown = if recv_count > 0 {
863 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
864 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
867 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
868 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
869 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
871 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
873 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
874 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
876 assert!(nodes[2].node.claim_funds(our_payment_preimage));
877 check_added_monitors!(nodes[2], 1);
878 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
879 assert!(updates.update_add_htlcs.is_empty());
880 assert!(updates.update_fail_htlcs.is_empty());
881 assert!(updates.update_fail_malformed_htlcs.is_empty());
882 assert!(updates.update_fee.is_none());
883 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
884 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
885 check_added_monitors!(nodes[1], 1);
886 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
887 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
889 assert!(updates_2.update_add_htlcs.is_empty());
890 assert!(updates_2.update_fail_htlcs.is_empty());
891 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
892 assert!(updates_2.update_fee.is_none());
893 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
894 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
895 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
897 let events = nodes[0].node.get_and_clear_pending_events();
898 assert_eq!(events.len(), 1);
900 Event::PaymentSent { ref payment_preimage } => {
901 assert_eq!(our_payment_preimage, *payment_preimage);
903 _ => panic!("Unexpected event"),
906 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
908 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
909 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
910 assert!(node_1_closing_signed.is_some());
913 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
914 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
916 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
917 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
918 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
920 // If all closing_signeds weren't delivered we can just resume where we left off...
921 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
923 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
924 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
925 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
927 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
928 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
929 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
931 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
932 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
934 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
935 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
936 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
938 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
939 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
940 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
941 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
942 assert!(node_0_none.is_none());
944 // If one node, however, received + responded with an identical closing_signed we end
945 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
946 // There isn't really anything better we can do simply, but in the future we might
947 // explore storing a set of recently-closed channels that got disconnected during
948 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
949 // give our counterparty enough time to (potentially) broadcast a cooperative closing
951 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
953 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
954 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
955 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
956 let msgs::ErrorMessage {ref channel_id, ..} = msg;
957 assert_eq!(*channel_id, chan_1.2);
958 } else { panic!("Needed SendErrorMessage close"); }
960 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
961 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
962 // closing_signed so we do it ourselves
963 check_closed_broadcast!(nodes[0]);
966 assert!(nodes[0].node.list_channels().is_empty());
968 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
969 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
970 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
971 assert!(nodes[1].node.list_channels().is_empty());
972 assert!(nodes[2].node.list_channels().is_empty());
976 fn test_shutdown_rebroadcast() {
977 do_test_shutdown_rebroadcast(0);
978 do_test_shutdown_rebroadcast(1);
979 do_test_shutdown_rebroadcast(2);
983 fn fake_network_test() {
984 // Simple test which builds a network of ChannelManagers, connects them to each other, and
985 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
986 let nodes = create_network(4, &[None, None, None, None]);
988 // Create some initial channels
989 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
990 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
991 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
993 // Rebalance the network a bit by relaying one payment through all the channels...
994 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
995 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
996 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
997 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
999 // Send some more payments
1000 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
1001 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
1002 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
1004 // Test failure packets
1005 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1006 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1008 // Add a new channel that skips 3
1009 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1011 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
1012 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
1013 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1014 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1015 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1016 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1017 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
1019 // Do some rebalance loop payments, simultaneously
1020 let mut hops = Vec::with_capacity(3);
1021 hops.push(RouteHop {
1022 pubkey: nodes[2].node.get_our_node_id(),
1023 short_channel_id: chan_2.0.contents.short_channel_id,
1025 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1027 hops.push(RouteHop {
1028 pubkey: nodes[3].node.get_our_node_id(),
1029 short_channel_id: chan_3.0.contents.short_channel_id,
1031 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1033 hops.push(RouteHop {
1034 pubkey: nodes[1].node.get_our_node_id(),
1035 short_channel_id: chan_4.0.contents.short_channel_id,
1037 cltv_expiry_delta: TEST_FINAL_CLTV,
1039 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;
1040 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;
1041 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1043 let mut hops = Vec::with_capacity(3);
1044 hops.push(RouteHop {
1045 pubkey: nodes[3].node.get_our_node_id(),
1046 short_channel_id: chan_4.0.contents.short_channel_id,
1048 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1050 hops.push(RouteHop {
1051 pubkey: nodes[2].node.get_our_node_id(),
1052 short_channel_id: chan_3.0.contents.short_channel_id,
1054 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1056 hops.push(RouteHop {
1057 pubkey: nodes[1].node.get_our_node_id(),
1058 short_channel_id: chan_2.0.contents.short_channel_id,
1060 cltv_expiry_delta: TEST_FINAL_CLTV,
1062 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;
1063 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;
1064 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1066 // Claim the rebalances...
1067 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1068 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1070 // Add a duplicate new channel from 2 to 4
1071 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1073 // Send some payments across both channels
1074 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1075 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1076 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1078 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1080 //TODO: Test that routes work again here as we've been notified that the channel is full
1082 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1083 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1084 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1086 // Close down the channels...
1087 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1088 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1089 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1090 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1091 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1095 fn holding_cell_htlc_counting() {
1096 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1097 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1098 // commitment dance rounds.
1099 let mut nodes = create_network(3, &[None, None, None]);
1100 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1101 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
1103 let mut payments = Vec::new();
1104 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1105 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1106 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1107 nodes[1].node.send_payment(route, payment_hash).unwrap();
1108 payments.push((payment_preimage, payment_hash));
1110 check_added_monitors!(nodes[1], 1);
1112 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1113 assert_eq!(events.len(), 1);
1114 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1115 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1117 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1118 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1120 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1121 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1122 if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() {
1123 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
1124 } else { panic!("Unexpected event"); }
1126 // This should also be true if we try to forward a payment.
1127 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1128 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1129 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
1130 check_added_monitors!(nodes[0], 1);
1132 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1133 assert_eq!(events.len(), 1);
1134 let payment_event = SendEvent::from_event(events.pop().unwrap());
1135 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1137 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
1138 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1139 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1140 // fails), the second will process the resulting failure and fail the HTLC backward.
1141 expect_pending_htlcs_forwardable!(nodes[1]);
1142 expect_pending_htlcs_forwardable!(nodes[1]);
1143 check_added_monitors!(nodes[1], 1);
1145 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1146 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]).unwrap();
1147 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1149 let events = nodes[0].node.get_and_clear_pending_msg_events();
1150 assert_eq!(events.len(), 1);
1152 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1153 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1155 _ => panic!("Unexpected event"),
1158 let events = nodes[0].node.get_and_clear_pending_events();
1159 assert_eq!(events.len(), 1);
1161 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1162 assert_eq!(payment_hash, payment_hash_2);
1163 assert!(!rejected_by_dest);
1165 _ => panic!("Unexpected event"),
1168 // Now forward all the pending HTLCs and claim them back
1169 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]).unwrap();
1170 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg).unwrap();
1171 check_added_monitors!(nodes[2], 1);
1173 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1174 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1175 check_added_monitors!(nodes[1], 1);
1176 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1178 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1179 check_added_monitors!(nodes[1], 1);
1180 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1182 for ref update in as_updates.update_add_htlcs.iter() {
1183 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update).unwrap();
1185 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed).unwrap();
1186 check_added_monitors!(nodes[2], 1);
1187 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
1188 check_added_monitors!(nodes[2], 1);
1189 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1191 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1192 check_added_monitors!(nodes[1], 1);
1193 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1194 check_added_monitors!(nodes[1], 1);
1195 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1197 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa).unwrap();
1198 check_added_monitors!(nodes[2], 1);
1200 expect_pending_htlcs_forwardable!(nodes[2]);
1202 let events = nodes[2].node.get_and_clear_pending_events();
1203 assert_eq!(events.len(), payments.len());
1204 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1206 &Event::PaymentReceived { ref payment_hash, .. } => {
1207 assert_eq!(*payment_hash, *hash);
1209 _ => panic!("Unexpected event"),
1213 for (preimage, _) in payments.drain(..) {
1214 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1217 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1221 fn duplicate_htlc_test() {
1222 // Test that we accept duplicate payment_hash HTLCs across the network and that
1223 // claiming/failing them are all separate and don't affect each other
1224 let mut nodes = create_network(6, &[None, None, None, None, None, None]);
1226 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1227 create_announced_chan_between_nodes(&nodes, 0, 3, LocalFeatures::new(), LocalFeatures::new());
1228 create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1229 create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
1230 create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
1231 create_announced_chan_between_nodes(&nodes, 3, 5, LocalFeatures::new(), LocalFeatures::new());
1233 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1235 *nodes[0].network_payment_count.borrow_mut() -= 1;
1236 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1238 *nodes[0].network_payment_count.borrow_mut() -= 1;
1239 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1241 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1242 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1243 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1246 fn do_channel_reserve_test(test_recv: bool) {
1247 use std::sync::atomic::Ordering;
1248 use ln::msgs::HandleError;
1250 let mut nodes = create_network(3, &[None, None, None]);
1251 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, LocalFeatures::new(), LocalFeatures::new());
1252 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, LocalFeatures::new(), LocalFeatures::new());
1254 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1255 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1257 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1258 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1260 macro_rules! get_route_and_payment_hash {
1261 ($recv_value: expr) => {{
1262 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1263 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1264 (route, payment_hash, payment_preimage)
1268 macro_rules! expect_forward {
1270 let mut events = $node.node.get_and_clear_pending_msg_events();
1271 assert_eq!(events.len(), 1);
1272 check_added_monitors!($node, 1);
1273 let payment_event = SendEvent::from_event(events.remove(0));
1278 let feemsat = 239; // somehow we know?
1279 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1281 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1283 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1285 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1286 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1287 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
1289 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight"),
1290 _ => panic!("Unknown error variants"),
1294 let mut htlc_id = 0;
1295 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1296 // nodes[0]'s wealth
1298 let amt_msat = recv_value_0 + total_fee_msat;
1299 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1302 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1305 let (stat01_, stat11_, stat12_, stat22_) = (
1306 get_channel_value_stat!(nodes[0], chan_1.2),
1307 get_channel_value_stat!(nodes[1], chan_1.2),
1308 get_channel_value_stat!(nodes[1], chan_2.2),
1309 get_channel_value_stat!(nodes[2], chan_2.2),
1312 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1313 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1314 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1315 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1316 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1320 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1321 // attempt to get channel_reserve violation
1322 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1323 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
1325 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the reserve value"),
1326 _ => panic!("Unknown error variants"),
1330 // adding pending output
1331 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1332 let amt_msat_1 = recv_value_1 + total_fee_msat;
1334 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1335 let payment_event_1 = {
1336 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
1337 check_added_monitors!(nodes[0], 1);
1339 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1340 assert_eq!(events.len(), 1);
1341 SendEvent::from_event(events.remove(0))
1343 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
1345 // channel reserve test with htlc pending output > 0
1346 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1348 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1349 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1350 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the reserve value"),
1351 _ => panic!("Unknown error variants"),
1356 // test channel_reserve test on nodes[1] side
1357 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1359 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1360 let secp_ctx = Secp256k1::new();
1361 let session_priv = SecretKey::from_slice(&{
1362 let mut session_key = [0; 32];
1363 let mut rng = thread_rng();
1364 rng.fill_bytes(&mut session_key);
1366 }).expect("RNG is bad!");
1368 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1369 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1370 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
1371 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
1372 let msg = msgs::UpdateAddHTLC {
1373 channel_id: chan_1.2,
1375 amount_msat: htlc_msat,
1376 payment_hash: our_payment_hash,
1377 cltv_expiry: htlc_cltv,
1378 onion_routing_packet: onion_packet,
1382 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
1384 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
1386 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1387 assert_eq!(nodes[1].node.list_channels().len(), 1);
1388 assert_eq!(nodes[1].node.list_channels().len(), 1);
1389 check_closed_broadcast!(nodes[1]);
1394 // split the rest to test holding cell
1395 let recv_value_21 = recv_value_2/2;
1396 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1398 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1399 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);
1402 // now see if they go through on both sides
1403 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1404 // but this will stuck in the holding cell
1405 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
1406 check_added_monitors!(nodes[0], 0);
1407 let events = nodes[0].node.get_and_clear_pending_events();
1408 assert_eq!(events.len(), 0);
1410 // test with outbound holding cell amount > 0
1412 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1413 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1414 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the reserve value"),
1415 _ => panic!("Unknown error variants"),
1419 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1420 // this will also stuck in the holding cell
1421 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
1422 check_added_monitors!(nodes[0], 0);
1423 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1424 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1426 // flush the pending htlc
1427 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
1428 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1429 check_added_monitors!(nodes[1], 1);
1431 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1432 check_added_monitors!(nodes[0], 1);
1433 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1435 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
1436 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1437 // No commitment_signed so get_event_msg's assert(len == 1) passes
1438 check_added_monitors!(nodes[0], 1);
1440 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1441 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1442 check_added_monitors!(nodes[1], 1);
1444 expect_pending_htlcs_forwardable!(nodes[1]);
1446 let ref payment_event_11 = expect_forward!(nodes[1]);
1447 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
1448 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1450 expect_pending_htlcs_forwardable!(nodes[2]);
1451 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1453 // flush the htlcs in the holding cell
1454 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1455 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
1456 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
1457 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1458 expect_pending_htlcs_forwardable!(nodes[1]);
1460 let ref payment_event_3 = expect_forward!(nodes[1]);
1461 assert_eq!(payment_event_3.msgs.len(), 2);
1462 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
1463 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
1465 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1466 expect_pending_htlcs_forwardable!(nodes[2]);
1468 let events = nodes[2].node.get_and_clear_pending_events();
1469 assert_eq!(events.len(), 2);
1471 Event::PaymentReceived { ref payment_hash, amt } => {
1472 assert_eq!(our_payment_hash_21, *payment_hash);
1473 assert_eq!(recv_value_21, amt);
1475 _ => panic!("Unexpected event"),
1478 Event::PaymentReceived { ref payment_hash, amt } => {
1479 assert_eq!(our_payment_hash_22, *payment_hash);
1480 assert_eq!(recv_value_22, amt);
1482 _ => panic!("Unexpected event"),
1485 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1486 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1487 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1489 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);
1490 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1491 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1492 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1494 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1495 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1499 fn channel_reserve_test() {
1500 do_channel_reserve_test(false);
1501 do_channel_reserve_test(true);
1505 fn channel_reserve_in_flight_removes() {
1506 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1507 // can send to its counterparty, but due to update ordering, the other side may not yet have
1508 // considered those HTLCs fully removed.
1509 // This tests that we don't count HTLCs which will not be included in the next remote
1510 // commitment transaction towards the reserve value (as it implies no commitment transaction
1511 // will be generated which violates the remote reserve value).
1512 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1514 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1515 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1516 // you only consider the value of the first HTLC, it may not),
1517 // * start routing a third HTLC from A to B,
1518 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1519 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1520 // * deliver the first fulfill from B
1521 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1523 // * deliver A's response CS and RAA.
1524 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1525 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1526 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1527 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1528 let mut nodes = create_network(2, &[None, None]);
1529 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1531 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1532 // Route the first two HTLCs.
1533 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1534 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1536 // Start routing the third HTLC (this is just used to get everyone in the right state).
1537 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1539 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1540 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
1541 check_added_monitors!(nodes[0], 1);
1542 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1543 assert_eq!(events.len(), 1);
1544 SendEvent::from_event(events.remove(0))
1547 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1548 // initial fulfill/CS.
1549 assert!(nodes[1].node.claim_funds(payment_preimage_1));
1550 check_added_monitors!(nodes[1], 1);
1551 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1553 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1554 // remove the second HTLC when we send the HTLC back from B to A.
1555 assert!(nodes[1].node.claim_funds(payment_preimage_2));
1556 check_added_monitors!(nodes[1], 1);
1557 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1559 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]).unwrap();
1560 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed).unwrap();
1561 check_added_monitors!(nodes[0], 1);
1562 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1563 expect_payment_sent!(nodes[0], payment_preimage_1);
1565 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]).unwrap();
1566 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg).unwrap();
1567 check_added_monitors!(nodes[1], 1);
1568 // B is already AwaitingRAA, so cant generate a CS here
1569 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1571 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1572 check_added_monitors!(nodes[1], 1);
1573 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1575 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1576 check_added_monitors!(nodes[0], 1);
1577 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1579 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1580 check_added_monitors!(nodes[1], 1);
1581 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1583 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1584 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1585 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1586 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1587 // on-chain as necessary).
1588 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]).unwrap();
1589 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
1590 check_added_monitors!(nodes[0], 1);
1591 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1592 expect_payment_sent!(nodes[0], payment_preimage_2);
1594 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1595 check_added_monitors!(nodes[1], 1);
1596 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1598 expect_pending_htlcs_forwardable!(nodes[1]);
1599 expect_payment_received!(nodes[1], payment_hash_3, 100000);
1601 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1602 // resolve the second HTLC from A's point of view.
1603 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1604 check_added_monitors!(nodes[0], 1);
1605 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1607 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1608 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1609 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1611 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1612 nodes[1].node.send_payment(route, payment_hash_4).unwrap();
1613 check_added_monitors!(nodes[1], 1);
1614 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1615 assert_eq!(events.len(), 1);
1616 SendEvent::from_event(events.remove(0))
1619 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]).unwrap();
1620 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg).unwrap();
1621 check_added_monitors!(nodes[0], 1);
1622 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1624 // Now just resolve all the outstanding messages/HTLCs for completeness...
1626 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1627 check_added_monitors!(nodes[1], 1);
1628 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1630 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1631 check_added_monitors!(nodes[1], 1);
1633 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1634 check_added_monitors!(nodes[0], 1);
1635 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1637 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1638 check_added_monitors!(nodes[1], 1);
1639 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1641 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1642 check_added_monitors!(nodes[0], 1);
1644 expect_pending_htlcs_forwardable!(nodes[0]);
1645 expect_payment_received!(nodes[0], payment_hash_4, 10000);
1647 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4);
1648 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3);
1652 fn channel_monitor_network_test() {
1653 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1654 // tests that ChannelMonitor is able to recover from various states.
1655 let nodes = create_network(5, &[None, None, None, None, None]);
1657 // Create some initial channels
1658 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1659 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
1660 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
1661 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
1663 // Rebalance the network a bit by relaying one payment through all the channels...
1664 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1665 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1666 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1667 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1669 // Simple case with no pending HTLCs:
1670 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1672 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1673 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1674 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1675 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1677 get_announce_close_broadcast_events(&nodes, 0, 1);
1678 assert_eq!(nodes[0].node.list_channels().len(), 0);
1679 assert_eq!(nodes[1].node.list_channels().len(), 1);
1681 // One pending HTLC is discarded by the force-close:
1682 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1684 // Simple case of one pending HTLC to HTLC-Timeout
1685 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1687 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1688 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1689 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1690 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1692 get_announce_close_broadcast_events(&nodes, 1, 2);
1693 assert_eq!(nodes[1].node.list_channels().len(), 0);
1694 assert_eq!(nodes[2].node.list_channels().len(), 1);
1696 macro_rules! claim_funds {
1697 ($node: expr, $prev_node: expr, $preimage: expr) => {
1699 assert!($node.node.claim_funds($preimage));
1700 check_added_monitors!($node, 1);
1702 let events = $node.node.get_and_clear_pending_msg_events();
1703 assert_eq!(events.len(), 1);
1705 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1706 assert!(update_add_htlcs.is_empty());
1707 assert!(update_fail_htlcs.is_empty());
1708 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
1710 _ => panic!("Unexpected event"),
1716 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
1717 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
1718 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
1720 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
1722 // Claim the payment on nodes[3], giving it knowledge of the preimage
1723 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
1725 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1726 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
1728 check_preimage_claim(&nodes[3], &node_txn);
1730 get_announce_close_broadcast_events(&nodes, 2, 3);
1731 assert_eq!(nodes[2].node.list_channels().len(), 0);
1732 assert_eq!(nodes[3].node.list_channels().len(), 1);
1734 { // Cheat and reset nodes[4]'s height to 1
1735 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1736 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
1739 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
1740 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
1741 // One pending HTLC to time out:
1742 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
1743 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
1747 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1748 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1749 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
1750 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1751 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1754 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
1756 // Claim the payment on nodes[4], giving it knowledge of the preimage
1757 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
1759 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1760 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1761 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
1762 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1763 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1766 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
1768 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1769 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
1771 check_preimage_claim(&nodes[4], &node_txn);
1773 get_announce_close_broadcast_events(&nodes, 3, 4);
1774 assert_eq!(nodes[3].node.list_channels().len(), 0);
1775 assert_eq!(nodes[4].node.list_channels().len(), 0);
1779 fn test_justice_tx() {
1780 // Test justice txn built on revoked HTLC-Success tx, against both sides
1782 let mut alice_config = UserConfig::new();
1783 alice_config.channel_options.announced_channel = true;
1784 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
1785 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
1786 let mut bob_config = UserConfig::new();
1787 bob_config.channel_options.announced_channel = true;
1788 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
1789 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
1790 let nodes = create_network(2, &[Some(alice_config), Some(bob_config)]);
1791 // Create some new channels:
1792 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1794 // A pending HTLC which will be revoked:
1795 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1796 // Get the will-be-revoked local txn from nodes[0]
1797 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1798 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
1799 assert_eq!(revoked_local_txn[0].input.len(), 1);
1800 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
1801 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
1802 assert_eq!(revoked_local_txn[1].input.len(), 1);
1803 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1804 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1805 // Revoke the old state
1806 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
1809 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1810 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1812 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1813 assert_eq!(node_txn.len(), 3);
1814 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1815 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
1817 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1818 node_txn.swap_remove(0);
1820 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
1822 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1823 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
1824 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1825 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1826 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
1828 get_announce_close_broadcast_events(&nodes, 0, 1);
1830 assert_eq!(nodes[0].node.list_channels().len(), 0);
1831 assert_eq!(nodes[1].node.list_channels().len(), 0);
1833 // We test justice_tx build by A on B's revoked HTLC-Success tx
1834 // Create some new channels:
1835 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1837 // A pending HTLC which will be revoked:
1838 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1839 // Get the will-be-revoked local txn from B
1840 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1841 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
1842 assert_eq!(revoked_local_txn[0].input.len(), 1);
1843 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
1844 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
1845 // Revoke the old state
1846 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
1848 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1849 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1851 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
1852 assert_eq!(node_txn.len(), 3);
1853 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1854 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
1856 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1857 node_txn.swap_remove(0);
1859 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
1861 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1862 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
1863 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1864 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1865 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
1867 get_announce_close_broadcast_events(&nodes, 0, 1);
1868 assert_eq!(nodes[0].node.list_channels().len(), 0);
1869 assert_eq!(nodes[1].node.list_channels().len(), 0);
1873 fn revoked_output_claim() {
1874 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
1875 // transaction is broadcast by its counterparty
1876 let nodes = create_network(2, &[None, None]);
1877 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1878 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
1879 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1880 assert_eq!(revoked_local_txn.len(), 1);
1881 // Only output is the full channel value back to nodes[0]:
1882 assert_eq!(revoked_local_txn[0].output.len(), 1);
1883 // Send a payment through, updating everyone's latest commitment txn
1884 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
1886 // Inform nodes[1] that nodes[0] broadcast a stale tx
1887 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1888 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1889 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1890 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
1892 assert_eq!(node_txn[0], node_txn[2]);
1894 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1895 check_spends!(node_txn[1], chan_1.3.clone());
1897 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
1898 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1899 get_announce_close_broadcast_events(&nodes, 0, 1);
1903 fn claim_htlc_outputs_shared_tx() {
1904 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
1905 let nodes = create_network(2, &[None, None]);
1907 // Create some new channel:
1908 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1910 // Rebalance the network to generate htlc in the two directions
1911 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1912 // 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
1913 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1914 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
1916 // Get the will-be-revoked local txn from node[0]
1917 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1918 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
1919 assert_eq!(revoked_local_txn[0].input.len(), 1);
1920 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
1921 assert_eq!(revoked_local_txn[1].input.len(), 1);
1922 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1923 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1924 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
1926 //Revoke the old state
1927 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
1930 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1931 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1932 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1933 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
1935 let events = nodes[1].node.get_and_clear_pending_events();
1936 assert_eq!(events.len(), 1);
1938 Event::PaymentFailed { payment_hash, .. } => {
1939 assert_eq!(payment_hash, payment_hash_2);
1941 _ => panic!("Unexpected event"),
1944 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1945 assert_eq!(node_txn.len(), 4);
1947 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
1948 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1950 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
1952 let mut witness_lens = BTreeSet::new();
1953 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
1954 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
1955 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
1956 assert_eq!(witness_lens.len(), 3);
1957 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
1958 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
1959 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
1961 // Next nodes[1] broadcasts its current local tx state:
1962 assert_eq!(node_txn[1].input.len(), 1);
1963 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
1965 assert_eq!(node_txn[2].input.len(), 1);
1966 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
1967 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
1968 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
1969 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
1970 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
1972 get_announce_close_broadcast_events(&nodes, 0, 1);
1973 assert_eq!(nodes[0].node.list_channels().len(), 0);
1974 assert_eq!(nodes[1].node.list_channels().len(), 0);
1978 fn claim_htlc_outputs_single_tx() {
1979 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
1980 let nodes = create_network(2, &[None, None]);
1982 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1984 // Rebalance the network to generate htlc in the two directions
1985 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1986 // 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
1987 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
1988 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1989 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
1991 // Get the will-be-revoked local txn from node[0]
1992 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1994 //Revoke the old state
1995 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
1998 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1999 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2000 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2001 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2003 let events = nodes[1].node.get_and_clear_pending_events();
2004 assert_eq!(events.len(), 1);
2006 Event::PaymentFailed { payment_hash, .. } => {
2007 assert_eq!(payment_hash, payment_hash_2);
2009 _ => panic!("Unexpected event"),
2012 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2013 assert_eq!(node_txn.len(), 22); // ChannelManager : 2, ChannelMontitor: 8 (1 standard revoked output, 2 revocation htlc tx, 1 local commitment tx + 1 htlc timeout tx) * 2 (block-rescan) + 5 * (1 local commitment tx + 1 htlc timeout tx)
2015 assert_eq!(node_txn[0], node_txn[7]);
2016 assert_eq!(node_txn[1], node_txn[8]);
2017 assert_eq!(node_txn[2], node_txn[9]);
2018 assert_eq!(node_txn[3], node_txn[10]);
2019 assert_eq!(node_txn[4], node_txn[11]);
2020 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcasted by ChannelManger
2021 assert_eq!(node_txn[4], node_txn[6]);
2024 if i % 2 == 0 { assert_eq!(node_txn[3], node_txn[i]); } else { assert_eq!(node_txn[4], node_txn[i]); }
2027 assert_eq!(node_txn[0].input.len(), 1);
2028 assert_eq!(node_txn[1].input.len(), 1);
2029 assert_eq!(node_txn[2].input.len(), 1);
2031 let mut revoked_tx_map = HashMap::new();
2032 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
2033 node_txn[0].verify(&revoked_tx_map).unwrap();
2034 node_txn[1].verify(&revoked_tx_map).unwrap();
2035 node_txn[2].verify(&revoked_tx_map).unwrap();
2037 let mut witness_lens = BTreeSet::new();
2038 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2039 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2040 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2041 assert_eq!(witness_lens.len(), 3);
2042 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2043 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2044 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2046 assert_eq!(node_txn[3].input.len(), 1);
2047 check_spends!(node_txn[3], chan_1.3.clone());
2049 assert_eq!(node_txn[4].input.len(), 1);
2050 let witness_script = node_txn[4].input[0].witness.last().unwrap();
2051 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2052 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
2053 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2054 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
2056 get_announce_close_broadcast_events(&nodes, 0, 1);
2057 assert_eq!(nodes[0].node.list_channels().len(), 0);
2058 assert_eq!(nodes[1].node.list_channels().len(), 0);
2062 fn test_htlc_on_chain_success() {
2063 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2064 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2065 // broadcasting the right event to other nodes in payment path.
2066 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2067 // A --------------------> B ----------------------> C (preimage)
2068 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2069 // commitment transaction was broadcast.
2070 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2072 // B should be able to claim via preimage if A then broadcasts its local tx.
2073 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2074 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2075 // PaymentSent event).
2077 let nodes = create_network(3, &[None, None, None]);
2079 // Create some initial channels
2080 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2081 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2083 // Rebalance the network a bit by relaying one payment through all the channels...
2084 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2085 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2087 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2088 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2089 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2091 // Broadcast legit commitment tx from C on B's chain
2092 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2093 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2094 assert_eq!(commitment_tx.len(), 1);
2095 check_spends!(commitment_tx[0], chan_2.3.clone());
2096 nodes[2].node.claim_funds(our_payment_preimage);
2097 nodes[2].node.claim_funds(our_payment_preimage_2);
2098 check_added_monitors!(nodes[2], 2);
2099 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2100 assert!(updates.update_add_htlcs.is_empty());
2101 assert!(updates.update_fail_htlcs.is_empty());
2102 assert!(updates.update_fail_malformed_htlcs.is_empty());
2103 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2105 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2106 check_closed_broadcast!(nodes[2]);
2107 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
2108 assert_eq!(node_txn.len(), 5);
2109 assert_eq!(node_txn[0], node_txn[3]);
2110 assert_eq!(node_txn[1], node_txn[4]);
2111 assert_eq!(node_txn[2], commitment_tx[0]);
2112 check_spends!(node_txn[0], commitment_tx[0].clone());
2113 check_spends!(node_txn[1], commitment_tx[0].clone());
2114 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2115 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2116 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2117 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2118 assert_eq!(node_txn[0].lock_time, 0);
2119 assert_eq!(node_txn[1].lock_time, 0);
2121 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2122 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
2123 let events = nodes[1].node.get_and_clear_pending_msg_events();
2125 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2126 assert_eq!(added_monitors.len(), 2);
2127 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2128 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2129 added_monitors.clear();
2131 assert_eq!(events.len(), 2);
2133 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2134 _ => panic!("Unexpected event"),
2137 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, .. } } => {
2138 assert!(update_add_htlcs.is_empty());
2139 assert!(update_fail_htlcs.is_empty());
2140 assert_eq!(update_fulfill_htlcs.len(), 1);
2141 assert!(update_fail_malformed_htlcs.is_empty());
2142 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2144 _ => panic!("Unexpected event"),
2146 macro_rules! check_tx_local_broadcast {
2147 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2148 // ChannelManager : 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 (block-rescan)
2149 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2150 assert_eq!(node_txn.len(), 7);
2151 assert_eq!(node_txn[0], node_txn[5]);
2152 assert_eq!(node_txn[1], node_txn[6]);
2153 check_spends!(node_txn[0], $commitment_tx.clone());
2154 check_spends!(node_txn[1], $commitment_tx.clone());
2155 assert_ne!(node_txn[0].lock_time, 0);
2156 assert_ne!(node_txn[1].lock_time, 0);
2158 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2159 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2160 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2161 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2163 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2164 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2165 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2166 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2168 check_spends!(node_txn[2], $chan_tx.clone());
2169 check_spends!(node_txn[3], node_txn[2].clone());
2170 check_spends!(node_txn[4], node_txn[2].clone());
2171 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2172 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2173 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2174 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2175 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2176 assert_ne!(node_txn[3].lock_time, 0);
2177 assert_ne!(node_txn[4].lock_time, 0);
2181 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2182 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2183 // timeout-claim of the output that nodes[2] just claimed via success.
2184 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2186 // Broadcast legit commitment tx from A on B's chain
2187 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2188 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2189 check_spends!(commitment_tx[0], chan_1.3.clone());
2190 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2191 check_closed_broadcast!(nodes[1]);
2192 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
2193 assert_eq!(node_txn.len(), 3);
2194 assert_eq!(node_txn[0], node_txn[2]);
2195 check_spends!(node_txn[0], commitment_tx[0].clone());
2196 assert_eq!(node_txn[0].input.len(), 2);
2197 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2198 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2199 assert_eq!(node_txn[0].lock_time, 0);
2200 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2201 check_spends!(node_txn[1], chan_1.3.clone());
2202 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2203 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2204 // we already checked the same situation with A.
2206 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2207 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2208 check_closed_broadcast!(nodes[0]);
2209 let events = nodes[0].node.get_and_clear_pending_events();
2210 assert_eq!(events.len(), 2);
2211 let mut first_claimed = false;
2212 for event in events {
2214 Event::PaymentSent { payment_preimage } => {
2215 if payment_preimage == our_payment_preimage {
2216 assert!(!first_claimed);
2217 first_claimed = true;
2219 assert_eq!(payment_preimage, our_payment_preimage_2);
2222 _ => panic!("Unexpected event"),
2225 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2229 fn test_htlc_on_chain_timeout() {
2230 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2231 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2232 // broadcasting the right event to other nodes in payment path.
2233 // A ------------------> B ----------------------> C (timeout)
2234 // B's commitment tx C's commitment tx
2236 // B's HTLC timeout tx B's timeout tx
2238 let nodes = create_network(3, &[None, None, None]);
2240 // Create some intial channels
2241 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2242 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2244 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2245 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2246 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2248 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2249 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2251 // Broadcast legit commitment tx from C on B's chain
2252 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2253 check_spends!(commitment_tx[0], chan_2.3.clone());
2254 nodes[2].node.fail_htlc_backwards(&payment_hash);
2255 check_added_monitors!(nodes[2], 0);
2256 expect_pending_htlcs_forwardable!(nodes[2]);
2257 check_added_monitors!(nodes[2], 1);
2259 let events = nodes[2].node.get_and_clear_pending_msg_events();
2260 assert_eq!(events.len(), 1);
2262 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, .. } } => {
2263 assert!(update_add_htlcs.is_empty());
2264 assert!(!update_fail_htlcs.is_empty());
2265 assert!(update_fulfill_htlcs.is_empty());
2266 assert!(update_fail_malformed_htlcs.is_empty());
2267 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2269 _ => panic!("Unexpected event"),
2271 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2272 check_closed_broadcast!(nodes[2]);
2273 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2274 assert_eq!(node_txn.len(), 1);
2275 check_spends!(node_txn[0], chan_2.3.clone());
2276 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2278 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2279 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2280 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2283 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2284 assert_eq!(node_txn.len(), 8); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 6 (HTLC-Timeout tx, commitment tx, timeout tx) * 2 (block-rescan)
2285 assert_eq!(node_txn[0], node_txn[5]);
2286 assert_eq!(node_txn[1], node_txn[6]);
2287 assert_eq!(node_txn[2], node_txn[7]);
2288 check_spends!(node_txn[0], commitment_tx[0].clone());
2289 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2290 check_spends!(node_txn[1], chan_2.3.clone());
2291 check_spends!(node_txn[2], node_txn[1].clone());
2292 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2293 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2294 check_spends!(node_txn[3], chan_2.3.clone());
2295 check_spends!(node_txn[4], node_txn[3].clone());
2296 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2297 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2298 timeout_tx = node_txn[0].clone();
2302 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
2303 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2304 check_added_monitors!(nodes[1], 0);
2305 check_closed_broadcast!(nodes[1]);
2307 expect_pending_htlcs_forwardable!(nodes[1]);
2308 check_added_monitors!(nodes[1], 1);
2309 let events = nodes[1].node.get_and_clear_pending_msg_events();
2310 assert_eq!(events.len(), 1);
2312 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, .. } } => {
2313 assert!(update_add_htlcs.is_empty());
2314 assert!(!update_fail_htlcs.is_empty());
2315 assert!(update_fulfill_htlcs.is_empty());
2316 assert!(update_fail_malformed_htlcs.is_empty());
2317 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2319 _ => panic!("Unexpected event"),
2321 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
2322 assert_eq!(node_txn.len(), 0);
2324 // Broadcast legit commitment tx from B on A's chain
2325 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2326 check_spends!(commitment_tx[0], chan_1.3.clone());
2328 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2329 check_closed_broadcast!(nodes[0]);
2330 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan
2331 assert_eq!(node_txn.len(), 4);
2332 assert_eq!(node_txn[0], node_txn[3]);
2333 check_spends!(node_txn[0], commitment_tx[0].clone());
2334 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2335 check_spends!(node_txn[1], chan_1.3.clone());
2336 check_spends!(node_txn[2], node_txn[1].clone());
2337 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2338 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2342 fn test_simple_commitment_revoked_fail_backward() {
2343 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2344 // and fail backward accordingly.
2346 let nodes = create_network(3, &[None, None, None]);
2348 // Create some initial channels
2349 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2350 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2352 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2353 // Get the will-be-revoked local txn from nodes[2]
2354 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2355 // Revoke the old state
2356 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2358 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2360 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2361 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2362 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2363 check_added_monitors!(nodes[1], 0);
2364 check_closed_broadcast!(nodes[1]);
2366 expect_pending_htlcs_forwardable!(nodes[1]);
2367 check_added_monitors!(nodes[1], 1);
2368 let events = nodes[1].node.get_and_clear_pending_msg_events();
2369 assert_eq!(events.len(), 1);
2371 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, .. } } => {
2372 assert!(update_add_htlcs.is_empty());
2373 assert_eq!(update_fail_htlcs.len(), 1);
2374 assert!(update_fulfill_htlcs.is_empty());
2375 assert!(update_fail_malformed_htlcs.is_empty());
2376 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2378 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2379 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2381 let events = nodes[0].node.get_and_clear_pending_msg_events();
2382 assert_eq!(events.len(), 1);
2384 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2385 _ => panic!("Unexpected event"),
2387 let events = nodes[0].node.get_and_clear_pending_events();
2388 assert_eq!(events.len(), 1);
2390 Event::PaymentFailed { .. } => {},
2391 _ => panic!("Unexpected event"),
2394 _ => panic!("Unexpected event"),
2398 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2399 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2400 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2401 // commitment transaction anymore.
2402 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2403 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2404 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2405 // technically disallowed and we should probably handle it reasonably.
2406 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2407 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2409 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2410 // commitment_signed (implying it will be in the latest remote commitment transaction).
2411 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2412 // and once they revoke the previous commitment transaction (allowing us to send a new
2413 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2414 let mut nodes = create_network(3, &[None, None, None]);
2416 // Create some initial channels
2417 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2418 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2420 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2421 // Get the will-be-revoked local txn from nodes[2]
2422 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2423 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2424 // Revoke the old state
2425 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2427 let value = if use_dust {
2428 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2429 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2430 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2433 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2434 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2435 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2437 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2438 expect_pending_htlcs_forwardable!(nodes[2]);
2439 check_added_monitors!(nodes[2], 1);
2440 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2441 assert!(updates.update_add_htlcs.is_empty());
2442 assert!(updates.update_fulfill_htlcs.is_empty());
2443 assert!(updates.update_fail_malformed_htlcs.is_empty());
2444 assert_eq!(updates.update_fail_htlcs.len(), 1);
2445 assert!(updates.update_fee.is_none());
2446 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2447 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2448 // Drop the last RAA from 3 -> 2
2450 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2451 expect_pending_htlcs_forwardable!(nodes[2]);
2452 check_added_monitors!(nodes[2], 1);
2453 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2454 assert!(updates.update_add_htlcs.is_empty());
2455 assert!(updates.update_fulfill_htlcs.is_empty());
2456 assert!(updates.update_fail_malformed_htlcs.is_empty());
2457 assert_eq!(updates.update_fail_htlcs.len(), 1);
2458 assert!(updates.update_fee.is_none());
2459 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2460 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2461 check_added_monitors!(nodes[1], 1);
2462 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2463 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2464 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2465 check_added_monitors!(nodes[2], 1);
2467 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2468 expect_pending_htlcs_forwardable!(nodes[2]);
2469 check_added_monitors!(nodes[2], 1);
2470 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2471 assert!(updates.update_add_htlcs.is_empty());
2472 assert!(updates.update_fulfill_htlcs.is_empty());
2473 assert!(updates.update_fail_malformed_htlcs.is_empty());
2474 assert_eq!(updates.update_fail_htlcs.len(), 1);
2475 assert!(updates.update_fee.is_none());
2476 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2477 // At this point first_payment_hash has dropped out of the latest two commitment
2478 // transactions that nodes[1] is tracking...
2479 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2480 check_added_monitors!(nodes[1], 1);
2481 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2482 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2483 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2484 check_added_monitors!(nodes[2], 1);
2486 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2487 // on nodes[2]'s RAA.
2488 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2489 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2490 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
2491 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2492 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2493 check_added_monitors!(nodes[1], 0);
2496 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
2497 // One monitor for the new revocation preimage, no second on as we won't generate a new
2498 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2499 check_added_monitors!(nodes[1], 1);
2500 let events = nodes[1].node.get_and_clear_pending_events();
2501 assert_eq!(events.len(), 1);
2503 Event::PendingHTLCsForwardable { .. } => { },
2504 _ => panic!("Unexpected event"),
2506 // Deliberately don't process the pending fail-back so they all fail back at once after
2507 // block connection just like the !deliver_bs_raa case
2510 let mut failed_htlcs = HashSet::new();
2511 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2513 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2514 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2515 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2517 let events = nodes[1].node.get_and_clear_pending_events();
2518 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2520 Event::PaymentFailed { ref payment_hash, .. } => {
2521 assert_eq!(*payment_hash, fourth_payment_hash);
2523 _ => panic!("Unexpected event"),
2525 if !deliver_bs_raa {
2527 Event::PendingHTLCsForwardable { .. } => { },
2528 _ => panic!("Unexpected event"),
2531 nodes[1].node.process_pending_htlc_forwards();
2532 check_added_monitors!(nodes[1], 1);
2534 let events = nodes[1].node.get_and_clear_pending_msg_events();
2535 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2536 match events[if deliver_bs_raa { 1 } else { 0 }] {
2537 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2538 _ => panic!("Unexpected event"),
2542 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, .. } } => {
2543 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2544 assert_eq!(update_add_htlcs.len(), 1);
2545 assert!(update_fulfill_htlcs.is_empty());
2546 assert!(update_fail_htlcs.is_empty());
2547 assert!(update_fail_malformed_htlcs.is_empty());
2549 _ => panic!("Unexpected event"),
2552 match events[if deliver_bs_raa { 2 } else { 1 }] {
2553 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, .. } } => {
2554 assert!(update_add_htlcs.is_empty());
2555 assert_eq!(update_fail_htlcs.len(), 3);
2556 assert!(update_fulfill_htlcs.is_empty());
2557 assert!(update_fail_malformed_htlcs.is_empty());
2558 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2560 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2561 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]).unwrap();
2562 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]).unwrap();
2564 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2566 let events = nodes[0].node.get_and_clear_pending_msg_events();
2567 // If we delivered B's RAA we got an unknown preimage error, not something
2568 // that we should update our routing table for.
2569 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2570 for event in events {
2572 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2573 _ => panic!("Unexpected event"),
2576 let events = nodes[0].node.get_and_clear_pending_events();
2577 assert_eq!(events.len(), 3);
2579 Event::PaymentFailed { ref payment_hash, .. } => {
2580 assert!(failed_htlcs.insert(payment_hash.0));
2582 _ => panic!("Unexpected event"),
2585 Event::PaymentFailed { ref payment_hash, .. } => {
2586 assert!(failed_htlcs.insert(payment_hash.0));
2588 _ => panic!("Unexpected event"),
2591 Event::PaymentFailed { ref payment_hash, .. } => {
2592 assert!(failed_htlcs.insert(payment_hash.0));
2594 _ => panic!("Unexpected event"),
2597 _ => panic!("Unexpected event"),
2600 assert!(failed_htlcs.contains(&first_payment_hash.0));
2601 assert!(failed_htlcs.contains(&second_payment_hash.0));
2602 assert!(failed_htlcs.contains(&third_payment_hash.0));
2606 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2607 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2608 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2609 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2610 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2614 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2615 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2616 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2617 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2618 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2622 fn test_htlc_ignore_latest_remote_commitment() {
2623 // Test that HTLC transactions spending the latest remote commitment transaction are simply
2624 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2625 let nodes = create_network(2, &[None, None]);
2626 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2628 route_payment(&nodes[0], &[&nodes[1]], 10000000);
2629 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
2630 check_closed_broadcast!(nodes[0]);
2632 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2633 assert_eq!(node_txn.len(), 2);
2635 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2636 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
2637 check_closed_broadcast!(nodes[1]);
2639 // Duplicate the block_connected call since this may happen due to other listeners
2640 // registering new transactions
2641 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
2645 fn test_force_close_fail_back() {
2646 // Check which HTLCs are failed-backwards on channel force-closure
2647 let mut nodes = create_network(3, &[None, None, None]);
2648 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2649 create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2651 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
2653 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2655 let mut payment_event = {
2656 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
2657 check_added_monitors!(nodes[0], 1);
2659 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2660 assert_eq!(events.len(), 1);
2661 SendEvent::from_event(events.remove(0))
2664 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2665 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2667 expect_pending_htlcs_forwardable!(nodes[1]);
2669 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
2670 assert_eq!(events_2.len(), 1);
2671 payment_event = SendEvent::from_event(events_2.remove(0));
2672 assert_eq!(payment_event.msgs.len(), 1);
2674 check_added_monitors!(nodes[1], 1);
2675 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2676 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2677 check_added_monitors!(nodes[2], 1);
2678 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2680 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
2681 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
2682 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
2684 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
2685 check_closed_broadcast!(nodes[2]);
2687 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2688 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
2689 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
2690 // back to nodes[1] upon timeout otherwise.
2691 assert_eq!(node_txn.len(), 1);
2695 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2696 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
2698 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
2699 check_closed_broadcast!(nodes[1]);
2701 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
2703 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
2704 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
2705 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
2707 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
2708 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2709 assert_eq!(node_txn.len(), 1);
2710 assert_eq!(node_txn[0].input.len(), 1);
2711 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
2712 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
2713 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
2715 check_spends!(node_txn[0], tx);
2719 fn test_unconf_chan() {
2720 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
2721 let nodes = create_network(2, &[None, None]);
2722 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2724 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2725 assert_eq!(channel_state.by_id.len(), 1);
2726 assert_eq!(channel_state.short_to_id.len(), 1);
2727 mem::drop(channel_state);
2729 let mut headers = Vec::new();
2730 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2731 headers.push(header.clone());
2733 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2734 headers.push(header.clone());
2736 let mut height = 99;
2737 while !headers.is_empty() {
2738 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
2741 check_closed_broadcast!(nodes[0]);
2742 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2743 assert_eq!(channel_state.by_id.len(), 0);
2744 assert_eq!(channel_state.short_to_id.len(), 0);
2748 fn test_simple_peer_disconnect() {
2749 // Test that we can reconnect when there are no lost messages
2750 let nodes = create_network(3, &[None, None, None]);
2751 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2752 create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2754 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2755 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2756 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2758 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2759 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2760 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
2761 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
2763 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2764 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2765 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2767 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2768 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2769 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2770 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2772 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2773 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2775 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
2776 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
2778 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
2780 let events = nodes[0].node.get_and_clear_pending_events();
2781 assert_eq!(events.len(), 2);
2783 Event::PaymentSent { payment_preimage } => {
2784 assert_eq!(payment_preimage, payment_preimage_3);
2786 _ => panic!("Unexpected event"),
2789 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
2790 assert_eq!(payment_hash, payment_hash_5);
2791 assert!(rejected_by_dest);
2793 _ => panic!("Unexpected event"),
2797 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
2798 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
2801 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
2802 // Test that we can reconnect when in-flight HTLC updates get dropped
2803 let mut nodes = create_network(2, &[None, None]);
2804 if messages_delivered == 0 {
2805 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
2806 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
2808 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2811 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();
2812 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
2814 let payment_event = {
2815 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
2816 check_added_monitors!(nodes[0], 1);
2818 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2819 assert_eq!(events.len(), 1);
2820 SendEvent::from_event(events.remove(0))
2822 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
2824 if messages_delivered < 2 {
2825 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
2827 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2828 if messages_delivered >= 3 {
2829 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2830 check_added_monitors!(nodes[1], 1);
2831 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2833 if messages_delivered >= 4 {
2834 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2835 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2836 check_added_monitors!(nodes[0], 1);
2838 if messages_delivered >= 5 {
2839 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
2840 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2841 // No commitment_signed so get_event_msg's assert(len == 1) passes
2842 check_added_monitors!(nodes[0], 1);
2844 if messages_delivered >= 6 {
2845 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2846 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2847 check_added_monitors!(nodes[1], 1);
2854 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2855 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2856 if messages_delivered < 3 {
2857 // Even if the funding_locked messages get exchanged, as long as nothing further was
2858 // received on either side, both sides will need to resend them.
2859 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
2860 } else if messages_delivered == 3 {
2861 // nodes[0] still wants its RAA + commitment_signed
2862 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
2863 } else if messages_delivered == 4 {
2864 // nodes[0] still wants its commitment_signed
2865 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
2866 } else if messages_delivered == 5 {
2867 // nodes[1] still wants its final RAA
2868 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
2869 } else if messages_delivered == 6 {
2870 // Everything was delivered...
2871 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2874 let events_1 = nodes[1].node.get_and_clear_pending_events();
2875 assert_eq!(events_1.len(), 1);
2877 Event::PendingHTLCsForwardable { .. } => { },
2878 _ => panic!("Unexpected event"),
2881 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2882 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2883 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2885 nodes[1].node.process_pending_htlc_forwards();
2887 let events_2 = nodes[1].node.get_and_clear_pending_events();
2888 assert_eq!(events_2.len(), 1);
2890 Event::PaymentReceived { ref payment_hash, amt } => {
2891 assert_eq!(payment_hash_1, *payment_hash);
2892 assert_eq!(amt, 1000000);
2894 _ => panic!("Unexpected event"),
2897 nodes[1].node.claim_funds(payment_preimage_1);
2898 check_added_monitors!(nodes[1], 1);
2900 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
2901 assert_eq!(events_3.len(), 1);
2902 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
2903 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2904 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2905 assert!(updates.update_add_htlcs.is_empty());
2906 assert!(updates.update_fail_htlcs.is_empty());
2907 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2908 assert!(updates.update_fail_malformed_htlcs.is_empty());
2909 assert!(updates.update_fee.is_none());
2910 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
2912 _ => panic!("Unexpected event"),
2915 if messages_delivered >= 1 {
2916 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
2918 let events_4 = nodes[0].node.get_and_clear_pending_events();
2919 assert_eq!(events_4.len(), 1);
2921 Event::PaymentSent { ref payment_preimage } => {
2922 assert_eq!(payment_preimage_1, *payment_preimage);
2924 _ => panic!("Unexpected event"),
2927 if messages_delivered >= 2 {
2928 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
2929 check_added_monitors!(nodes[0], 1);
2930 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2932 if messages_delivered >= 3 {
2933 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2934 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2935 check_added_monitors!(nodes[1], 1);
2937 if messages_delivered >= 4 {
2938 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
2939 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2940 // No commitment_signed so get_event_msg's assert(len == 1) passes
2941 check_added_monitors!(nodes[1], 1);
2943 if messages_delivered >= 5 {
2944 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2945 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2946 check_added_monitors!(nodes[0], 1);
2953 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2954 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2955 if messages_delivered < 2 {
2956 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
2957 //TODO: Deduplicate PaymentSent events, then enable this if:
2958 //if messages_delivered < 1 {
2959 let events_4 = nodes[0].node.get_and_clear_pending_events();
2960 assert_eq!(events_4.len(), 1);
2962 Event::PaymentSent { ref payment_preimage } => {
2963 assert_eq!(payment_preimage_1, *payment_preimage);
2965 _ => panic!("Unexpected event"),
2968 } else if messages_delivered == 2 {
2969 // nodes[0] still wants its RAA + commitment_signed
2970 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
2971 } else if messages_delivered == 3 {
2972 // nodes[0] still wants its commitment_signed
2973 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
2974 } else if messages_delivered == 4 {
2975 // nodes[1] still wants its final RAA
2976 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
2977 } else if messages_delivered == 5 {
2978 // Everything was delivered...
2979 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2982 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2983 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2984 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2986 // Channel should still work fine...
2987 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
2988 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
2992 fn test_drop_messages_peer_disconnect_a() {
2993 do_test_drop_messages_peer_disconnect(0);
2994 do_test_drop_messages_peer_disconnect(1);
2995 do_test_drop_messages_peer_disconnect(2);
2996 do_test_drop_messages_peer_disconnect(3);
3000 fn test_drop_messages_peer_disconnect_b() {
3001 do_test_drop_messages_peer_disconnect(4);
3002 do_test_drop_messages_peer_disconnect(5);
3003 do_test_drop_messages_peer_disconnect(6);
3007 fn test_funding_peer_disconnect() {
3008 // Test that we can lock in our funding tx while disconnected
3009 let nodes = create_network(2, &[None, None]);
3010 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
3012 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3013 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3015 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
3016 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3017 assert_eq!(events_1.len(), 1);
3019 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3020 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3022 _ => panic!("Unexpected event"),
3025 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3027 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3028 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3030 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
3031 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3032 assert_eq!(events_2.len(), 2);
3034 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3035 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3037 _ => panic!("Unexpected event"),
3040 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
3041 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3043 _ => panic!("Unexpected event"),
3046 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3048 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
3049 // rebroadcasting announcement_signatures upon reconnect.
3051 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();
3052 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3053 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
3057 fn test_drop_messages_peer_disconnect_dual_htlc() {
3058 // Test that we can handle reconnecting when both sides of a channel have pending
3059 // commitment_updates when we disconnect.
3060 let mut nodes = create_network(2, &[None, None]);
3061 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3063 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3065 // Now try to send a second payment which will fail to send
3066 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3067 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3069 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3070 check_added_monitors!(nodes[0], 1);
3072 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3073 assert_eq!(events_1.len(), 1);
3075 MessageSendEvent::UpdateHTLCs { .. } => {},
3076 _ => panic!("Unexpected event"),
3079 assert!(nodes[1].node.claim_funds(payment_preimage_1));
3080 check_added_monitors!(nodes[1], 1);
3082 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3083 assert_eq!(events_2.len(), 1);
3085 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 } } => {
3086 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3087 assert!(update_add_htlcs.is_empty());
3088 assert_eq!(update_fulfill_htlcs.len(), 1);
3089 assert!(update_fail_htlcs.is_empty());
3090 assert!(update_fail_malformed_htlcs.is_empty());
3091 assert!(update_fee.is_none());
3093 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
3094 let events_3 = nodes[0].node.get_and_clear_pending_events();
3095 assert_eq!(events_3.len(), 1);
3097 Event::PaymentSent { ref payment_preimage } => {
3098 assert_eq!(*payment_preimage, payment_preimage_1);
3100 _ => panic!("Unexpected event"),
3103 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
3104 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3105 // No commitment_signed so get_event_msg's assert(len == 1) passes
3106 check_added_monitors!(nodes[0], 1);
3108 _ => panic!("Unexpected event"),
3111 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3112 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3114 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3115 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3116 assert_eq!(reestablish_1.len(), 1);
3117 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3118 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3119 assert_eq!(reestablish_2.len(), 1);
3121 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3122 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3123 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3124 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3126 assert!(as_resp.0.is_none());
3127 assert!(bs_resp.0.is_none());
3129 assert!(bs_resp.1.is_none());
3130 assert!(bs_resp.2.is_none());
3132 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3134 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3135 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3136 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3137 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3138 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3139 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
3140 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
3141 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3142 // No commitment_signed so get_event_msg's assert(len == 1) passes
3143 check_added_monitors!(nodes[1], 1);
3145 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
3146 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3147 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3148 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3149 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3150 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3151 assert!(bs_second_commitment_signed.update_fee.is_none());
3152 check_added_monitors!(nodes[1], 1);
3154 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3155 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3156 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3157 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3158 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3159 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3160 assert!(as_commitment_signed.update_fee.is_none());
3161 check_added_monitors!(nodes[0], 1);
3163 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
3164 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3165 // No commitment_signed so get_event_msg's assert(len == 1) passes
3166 check_added_monitors!(nodes[0], 1);
3168 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
3169 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3170 // No commitment_signed so get_event_msg's assert(len == 1) passes
3171 check_added_monitors!(nodes[1], 1);
3173 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3174 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3175 check_added_monitors!(nodes[1], 1);
3177 expect_pending_htlcs_forwardable!(nodes[1]);
3179 let events_5 = nodes[1].node.get_and_clear_pending_events();
3180 assert_eq!(events_5.len(), 1);
3182 Event::PaymentReceived { ref payment_hash, amt: _ } => {
3183 assert_eq!(payment_hash_2, *payment_hash);
3185 _ => panic!("Unexpected event"),
3188 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
3189 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3190 check_added_monitors!(nodes[0], 1);
3192 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
3196 fn test_invalid_channel_announcement() {
3197 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3198 let secp_ctx = Secp256k1::new();
3199 let nodes = create_network(2, &[None, None]);
3201 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], LocalFeatures::new(), LocalFeatures::new());
3203 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3204 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3205 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3206 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3208 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 } );
3210 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
3211 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
3213 let as_network_key = nodes[0].node.get_our_node_id();
3214 let bs_network_key = nodes[1].node.get_our_node_id();
3216 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3218 let mut chan_announcement;
3220 macro_rules! dummy_unsigned_msg {
3222 msgs::UnsignedChannelAnnouncement {
3223 features: msgs::GlobalFeatures::new(),
3224 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3225 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3226 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3227 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3228 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3229 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3230 excess_data: Vec::new(),
3235 macro_rules! sign_msg {
3236 ($unsigned_msg: expr) => {
3237 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3238 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
3239 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
3240 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3241 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3242 chan_announcement = msgs::ChannelAnnouncement {
3243 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3244 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3245 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3246 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3247 contents: $unsigned_msg
3252 let unsigned_msg = dummy_unsigned_msg!();
3253 sign_msg!(unsigned_msg);
3254 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3255 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 } );
3257 // Configured with Network::Testnet
3258 let mut unsigned_msg = dummy_unsigned_msg!();
3259 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3260 sign_msg!(unsigned_msg);
3261 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3263 let mut unsigned_msg = dummy_unsigned_msg!();
3264 unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3265 sign_msg!(unsigned_msg);
3266 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3270 fn test_no_txn_manager_serialize_deserialize() {
3271 let mut nodes = create_network(2, &[None, None]);
3273 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
3275 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3277 let nodes_0_serialized = nodes[0].node.encode();
3278 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3279 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3281 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3282 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3283 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3284 assert!(chan_0_monitor_read.is_empty());
3286 let mut nodes_0_read = &nodes_0_serialized[..];
3287 let config = UserConfig::new();
3288 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3289 let (_, nodes_0_deserialized) = {
3290 let mut channel_monitors = HashMap::new();
3291 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3292 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3293 default_config: config,
3295 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3296 monitor: nodes[0].chan_monitor.clone(),
3297 chain_monitor: nodes[0].chain_monitor.clone(),
3298 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3299 logger: Arc::new(test_utils::TestLogger::new()),
3300 channel_monitors: &channel_monitors,
3303 assert!(nodes_0_read.is_empty());
3305 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3306 nodes[0].node = Arc::new(nodes_0_deserialized);
3307 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
3308 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
3309 assert_eq!(nodes[0].node.list_channels().len(), 1);
3310 check_added_monitors!(nodes[0], 1);
3312 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3313 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3314 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3315 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3317 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3318 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3319 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3320 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3322 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3323 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3324 for node in nodes.iter() {
3325 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3326 node.router.handle_channel_update(&as_update).unwrap();
3327 node.router.handle_channel_update(&bs_update).unwrap();
3330 send_payment(&nodes[0], &[&nodes[1]], 1000000);
3334 fn test_simple_manager_serialize_deserialize() {
3335 let mut nodes = create_network(2, &[None, None]);
3336 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3338 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3339 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3341 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3343 let nodes_0_serialized = nodes[0].node.encode();
3344 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3345 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3347 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3348 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3349 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3350 assert!(chan_0_monitor_read.is_empty());
3352 let mut nodes_0_read = &nodes_0_serialized[..];
3353 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3354 let (_, nodes_0_deserialized) = {
3355 let mut channel_monitors = HashMap::new();
3356 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3357 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3358 default_config: UserConfig::new(),
3360 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3361 monitor: nodes[0].chan_monitor.clone(),
3362 chain_monitor: nodes[0].chain_monitor.clone(),
3363 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3364 logger: Arc::new(test_utils::TestLogger::new()),
3365 channel_monitors: &channel_monitors,
3368 assert!(nodes_0_read.is_empty());
3370 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3371 nodes[0].node = Arc::new(nodes_0_deserialized);
3372 check_added_monitors!(nodes[0], 1);
3374 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3376 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3377 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3381 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3382 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3383 let mut nodes = create_network(4, &[None, None, None, None]);
3384 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3385 create_announced_chan_between_nodes(&nodes, 2, 0, LocalFeatures::new(), LocalFeatures::new());
3386 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, LocalFeatures::new(), LocalFeatures::new());
3388 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3390 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3391 let nodes_0_serialized = nodes[0].node.encode();
3393 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3394 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3395 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3396 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3398 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3400 let mut node_0_monitors_serialized = Vec::new();
3401 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3402 let mut writer = test_utils::TestVecWriter(Vec::new());
3403 monitor.1.write_for_disk(&mut writer).unwrap();
3404 node_0_monitors_serialized.push(writer.0);
3407 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new()), Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 })));
3408 let mut node_0_monitors = Vec::new();
3409 for serialized in node_0_monitors_serialized.iter() {
3410 let mut read = &serialized[..];
3411 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3412 assert!(read.is_empty());
3413 node_0_monitors.push(monitor);
3416 let mut nodes_0_read = &nodes_0_serialized[..];
3417 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3418 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3419 default_config: UserConfig::new(),
3421 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3422 monitor: nodes[0].chan_monitor.clone(),
3423 chain_monitor: nodes[0].chain_monitor.clone(),
3424 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3425 logger: Arc::new(test_utils::TestLogger::new()),
3426 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
3428 assert!(nodes_0_read.is_empty());
3430 { // Channel close should result in a commitment tx and an HTLC tx
3431 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3432 assert_eq!(txn.len(), 2);
3433 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3434 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3437 for monitor in node_0_monitors.drain(..) {
3438 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
3439 check_added_monitors!(nodes[0], 1);
3441 nodes[0].node = Arc::new(nodes_0_deserialized);
3443 // nodes[1] and nodes[2] have no lost state with nodes[0]...
3444 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3445 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3446 //... and we can even still claim the payment!
3447 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
3449 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
3450 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3451 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
3452 if let Err(msgs::HandleError { action: Some(msgs::ErrorAction::SendErrorMessage { msg }), .. }) = nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish) {
3453 assert_eq!(msg.channel_id, channel_id);
3454 } else { panic!("Unexpected result"); }
3457 macro_rules! check_spendable_outputs {
3458 ($node: expr, $der_idx: expr) => {
3460 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3461 let mut txn = Vec::new();
3462 for event in events {
3464 Event::SpendableOutputs { ref outputs } => {
3465 for outp in outputs {
3467 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
3469 previous_output: outpoint.clone(),
3470 script_sig: Script::new(),
3472 witness: Vec::new(),
3475 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3476 value: output.value,
3478 let mut spend_tx = Transaction {
3484 let secp_ctx = Secp256k1::new();
3485 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
3486 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
3487 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3488 let remotesig = secp_ctx.sign(&sighash, key);
3489 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
3490 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3491 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
3494 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
3496 previous_output: outpoint.clone(),
3497 script_sig: Script::new(),
3498 sequence: *to_self_delay as u32,
3499 witness: Vec::new(),
3502 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3503 value: output.value,
3505 let mut spend_tx = Transaction {
3511 let secp_ctx = Secp256k1::new();
3512 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
3513 let local_delaysig = secp_ctx.sign(&sighash, key);
3514 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
3515 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3516 spend_tx.input[0].witness.push(vec!(0));
3517 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
3520 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
3521 let secp_ctx = Secp256k1::new();
3523 previous_output: outpoint.clone(),
3524 script_sig: Script::new(),
3526 witness: Vec::new(),
3529 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3530 value: output.value,
3532 let mut spend_tx = Transaction {
3536 output: vec![outp.clone()],
3539 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
3541 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
3543 Err(_) => panic!("Your RNG is busted"),
3546 Err(_) => panic!("Your rng is busted"),
3549 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
3550 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
3551 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3552 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
3553 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
3554 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3555 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
3561 _ => panic!("Unexpected event"),
3570 fn test_claim_sizeable_push_msat() {
3571 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
3572 let nodes = create_network(2, &[None, None]);
3574 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, LocalFeatures::new(), LocalFeatures::new());
3575 nodes[1].node.force_close_channel(&chan.2);
3576 check_closed_broadcast!(nodes[1]);
3577 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3578 assert_eq!(node_txn.len(), 1);
3579 check_spends!(node_txn[0], chan.3.clone());
3580 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
3582 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3583 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3584 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3585 assert_eq!(spend_txn.len(), 1);
3586 check_spends!(spend_txn[0], node_txn[0].clone());
3590 fn test_claim_on_remote_sizeable_push_msat() {
3591 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3592 // to_remote output is encumbered by a P2WPKH
3594 let nodes = create_network(2, &[None, None]);
3596 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, LocalFeatures::new(), LocalFeatures::new());
3597 nodes[0].node.force_close_channel(&chan.2);
3598 check_closed_broadcast!(nodes[0]);
3600 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3601 assert_eq!(node_txn.len(), 1);
3602 check_spends!(node_txn[0], chan.3.clone());
3603 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
3605 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3606 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3607 check_closed_broadcast!(nodes[1]);
3608 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3609 assert_eq!(spend_txn.len(), 2);
3610 assert_eq!(spend_txn[0], spend_txn[1]);
3611 check_spends!(spend_txn[0], node_txn[0].clone());
3615 fn test_claim_on_remote_revoked_sizeable_push_msat() {
3616 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3617 // to_remote output is encumbered by a P2WPKH
3619 let nodes = create_network(2, &[None, None]);
3621 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, LocalFeatures::new(), LocalFeatures::new());
3622 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3623 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
3624 assert_eq!(revoked_local_txn[0].input.len(), 1);
3625 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
3627 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3628 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3629 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3630 check_closed_broadcast!(nodes[1]);
3632 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3633 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3634 assert_eq!(spend_txn.len(), 4);
3635 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
3636 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
3637 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
3638 check_spends!(spend_txn[1], node_txn[0].clone());
3642 fn test_static_spendable_outputs_preimage_tx() {
3643 let nodes = create_network(2, &[None, None]);
3645 // Create some initial channels
3646 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3648 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3650 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3651 assert_eq!(commitment_tx[0].input.len(), 1);
3652 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
3654 // Settle A's commitment tx on B's chain
3655 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3656 assert!(nodes[1].node.claim_funds(payment_preimage));
3657 check_added_monitors!(nodes[1], 1);
3658 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
3659 let events = nodes[1].node.get_and_clear_pending_msg_events();
3661 MessageSendEvent::UpdateHTLCs { .. } => {},
3662 _ => panic!("Unexpected event"),
3665 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3666 _ => panic!("Unexepected event"),
3669 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
3670 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
3671 check_spends!(node_txn[0], commitment_tx[0].clone());
3672 assert_eq!(node_txn[0], node_txn[2]);
3673 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3674 check_spends!(node_txn[1], chan_1.3.clone());
3676 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
3677 assert_eq!(spend_txn.len(), 2);
3678 assert_eq!(spend_txn[0], spend_txn[1]);
3679 check_spends!(spend_txn[0], node_txn[0].clone());
3683 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
3684 let nodes = create_network(2, &[None, None]);
3686 // Create some initial channels
3687 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3689 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3690 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
3691 assert_eq!(revoked_local_txn[0].input.len(), 1);
3692 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3694 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3696 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3697 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3698 check_closed_broadcast!(nodes[1]);
3700 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3701 assert_eq!(node_txn.len(), 3);
3702 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
3703 assert_eq!(node_txn[0].input.len(), 2);
3704 check_spends!(node_txn[0], revoked_local_txn[0].clone());
3706 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3707 assert_eq!(spend_txn.len(), 2);
3708 assert_eq!(spend_txn[0], spend_txn[1]);
3709 check_spends!(spend_txn[0], node_txn[0].clone());
3713 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
3714 let nodes = create_network(2, &[None, None]);
3716 // Create some initial channels
3717 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3719 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3720 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3721 assert_eq!(revoked_local_txn[0].input.len(), 1);
3722 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3724 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3726 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3727 // A will generate HTLC-Timeout from revoked commitment tx
3728 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3729 check_closed_broadcast!(nodes[0]);
3731 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3732 assert_eq!(revoked_htlc_txn.len(), 3);
3733 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3734 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3735 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3736 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3737 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
3739 // B will generate justice tx from A's revoked commitment/HTLC tx
3740 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3741 check_closed_broadcast!(nodes[1]);
3743 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3744 assert_eq!(node_txn.len(), 4);
3745 assert_eq!(node_txn[3].input.len(), 1);
3746 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3748 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
3749 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3750 assert_eq!(spend_txn.len(), 3);
3751 assert_eq!(spend_txn[0], spend_txn[1]);
3752 check_spends!(spend_txn[0], node_txn[0].clone());
3753 check_spends!(spend_txn[2], node_txn[3].clone());
3757 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
3758 let nodes = create_network(2, &[None, None]);
3760 // Create some initial channels
3761 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3763 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3764 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3765 assert_eq!(revoked_local_txn[0].input.len(), 1);
3766 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3768 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3770 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3771 // B will generate HTLC-Success from revoked commitment tx
3772 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3773 check_closed_broadcast!(nodes[1]);
3774 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3776 assert_eq!(revoked_htlc_txn.len(), 3);
3777 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3778 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3779 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3780 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3782 // A will generate justice tx from B's revoked commitment/HTLC tx
3783 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3784 check_closed_broadcast!(nodes[0]);
3786 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3787 assert_eq!(node_txn.len(), 4);
3788 assert_eq!(node_txn[3].input.len(), 1);
3789 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3791 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
3792 let spend_txn = check_spendable_outputs!(nodes[0], 1);
3793 assert_eq!(spend_txn.len(), 5);
3794 assert_eq!(spend_txn[0], spend_txn[2]);
3795 assert_eq!(spend_txn[1], spend_txn[3]);
3796 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
3797 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
3798 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
3802 fn test_onchain_to_onchain_claim() {
3803 // Test that in case of channel closure, we detect the state of output thanks to
3804 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
3805 // First, have C claim an HTLC against its own latest commitment transaction.
3806 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
3808 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
3811 let nodes = create_network(3, &[None, None, None]);
3813 // Create some initial channels
3814 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3815 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
3817 // Rebalance the network a bit by relaying one payment through all the channels ...
3818 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3819 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3821 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3822 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3823 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3824 check_spends!(commitment_tx[0], chan_2.3.clone());
3825 nodes[2].node.claim_funds(payment_preimage);
3826 check_added_monitors!(nodes[2], 1);
3827 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3828 assert!(updates.update_add_htlcs.is_empty());
3829 assert!(updates.update_fail_htlcs.is_empty());
3830 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3831 assert!(updates.update_fail_malformed_htlcs.is_empty());
3833 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3834 check_closed_broadcast!(nodes[2]);
3836 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
3837 assert_eq!(c_txn.len(), 3);
3838 assert_eq!(c_txn[0], c_txn[2]);
3839 assert_eq!(commitment_tx[0], c_txn[1]);
3840 check_spends!(c_txn[1], chan_2.3.clone());
3841 check_spends!(c_txn[2], c_txn[1].clone());
3842 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
3843 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3844 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3845 assert_eq!(c_txn[0].lock_time, 0); // Success tx
3847 // 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
3848 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
3850 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3851 assert_eq!(b_txn.len(), 4);
3852 assert_eq!(b_txn[0], b_txn[3]);
3853 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
3854 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
3855 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3856 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3857 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3858 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
3859 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3860 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3861 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3864 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
3865 check_added_monitors!(nodes[1], 1);
3866 match msg_events[0] {
3867 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3868 _ => panic!("Unexpected event"),
3870 match msg_events[1] {
3871 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, .. } } => {
3872 assert!(update_add_htlcs.is_empty());
3873 assert!(update_fail_htlcs.is_empty());
3874 assert_eq!(update_fulfill_htlcs.len(), 1);
3875 assert!(update_fail_malformed_htlcs.is_empty());
3876 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3878 _ => panic!("Unexpected event"),
3880 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
3881 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3882 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3883 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3884 assert_eq!(b_txn.len(), 3);
3885 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
3886 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
3887 check_spends!(b_txn[0], commitment_tx[0].clone());
3888 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3889 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3890 assert_eq!(b_txn[2].lock_time, 0); // Success tx
3892 check_closed_broadcast!(nodes[1]);
3896 fn test_duplicate_payment_hash_one_failure_one_success() {
3897 // Topology : A --> B --> C
3898 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
3899 let mut nodes = create_network(3, &[None, None, None]);
3901 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3902 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
3904 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
3905 *nodes[0].network_payment_count.borrow_mut() -= 1;
3906 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
3908 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3909 assert_eq!(commitment_txn[0].input.len(), 1);
3910 check_spends!(commitment_txn[0], chan_2.3.clone());
3912 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3913 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
3914 check_closed_broadcast!(nodes[1]);
3916 let htlc_timeout_tx;
3917 { // Extract one of the two HTLC-Timeout transaction
3918 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3919 assert_eq!(node_txn.len(), 7);
3920 assert_eq!(node_txn[0], node_txn[5]);
3921 assert_eq!(node_txn[1], node_txn[6]);
3922 check_spends!(node_txn[0], commitment_txn[0].clone());
3923 assert_eq!(node_txn[0].input.len(), 1);
3924 check_spends!(node_txn[1], commitment_txn[0].clone());
3925 assert_eq!(node_txn[1].input.len(), 1);
3926 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
3927 check_spends!(node_txn[2], chan_2.3.clone());
3928 check_spends!(node_txn[3], node_txn[2].clone());
3929 check_spends!(node_txn[4], node_txn[2].clone());
3930 htlc_timeout_tx = node_txn[1].clone();
3933 nodes[2].node.claim_funds(our_payment_preimage);
3934 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
3935 check_added_monitors!(nodes[2], 2);
3936 let events = nodes[2].node.get_and_clear_pending_msg_events();
3938 MessageSendEvent::UpdateHTLCs { .. } => {},
3939 _ => panic!("Unexpected event"),
3942 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3943 _ => panic!("Unexepected event"),
3945 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3946 assert_eq!(htlc_success_txn.len(), 5);
3947 check_spends!(htlc_success_txn[2], chan_2.3.clone());
3948 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
3949 assert_eq!(htlc_success_txn[0].input.len(), 1);
3950 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3951 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
3952 assert_eq!(htlc_success_txn[1].input.len(), 1);
3953 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3954 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
3955 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
3956 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
3958 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
3959 connect_blocks(&nodes[1].chain_monitor, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
3960 expect_pending_htlcs_forwardable!(nodes[1]);
3961 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3962 assert!(htlc_updates.update_add_htlcs.is_empty());
3963 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
3964 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
3965 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
3966 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
3967 check_added_monitors!(nodes[1], 1);
3969 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
3970 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3972 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
3973 let events = nodes[0].node.get_and_clear_pending_msg_events();
3974 assert_eq!(events.len(), 1);
3976 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
3978 _ => { panic!("Unexpected event"); }
3981 let events = nodes[0].node.get_and_clear_pending_events();
3983 Event::PaymentFailed { ref payment_hash, .. } => {
3984 assert_eq!(*payment_hash, duplicate_payment_hash);
3986 _ => panic!("Unexpected event"),
3989 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
3990 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
3991 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3992 assert!(updates.update_add_htlcs.is_empty());
3993 assert!(updates.update_fail_htlcs.is_empty());
3994 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3995 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
3996 assert!(updates.update_fail_malformed_htlcs.is_empty());
3997 check_added_monitors!(nodes[1], 1);
3999 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4000 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4002 let events = nodes[0].node.get_and_clear_pending_events();
4004 Event::PaymentSent { ref payment_preimage } => {
4005 assert_eq!(*payment_preimage, our_payment_preimage);
4007 _ => panic!("Unexpected event"),
4012 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4013 let nodes = create_network(2, &[None, None]);
4015 // Create some initial channels
4016 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4018 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4019 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4020 assert_eq!(local_txn[0].input.len(), 1);
4021 check_spends!(local_txn[0], chan_1.3.clone());
4023 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4024 nodes[1].node.claim_funds(payment_preimage);
4025 check_added_monitors!(nodes[1], 1);
4026 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4027 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4028 let events = nodes[1].node.get_and_clear_pending_msg_events();
4030 MessageSendEvent::UpdateHTLCs { .. } => {},
4031 _ => panic!("Unexpected event"),
4034 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4035 _ => panic!("Unexepected event"),
4037 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4038 assert_eq!(node_txn[0].input.len(), 1);
4039 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4040 check_spends!(node_txn[0], local_txn[0].clone());
4042 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4043 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4044 assert_eq!(spend_txn.len(), 2);
4045 check_spends!(spend_txn[0], node_txn[0].clone());
4046 check_spends!(spend_txn[1], node_txn[2].clone());
4049 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4050 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4051 // unrevoked commitment transaction.
4052 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4053 // a remote RAA before they could be failed backwards (and combinations thereof).
4054 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4055 // use the same payment hashes.
4056 // Thus, we use a six-node network:
4061 // And test where C fails back to A/B when D announces its latest commitment transaction
4062 let nodes = create_network(6, &[None, None, None, None, None, None]);
4064 create_announced_chan_between_nodes(&nodes, 0, 2, LocalFeatures::new(), LocalFeatures::new());
4065 create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
4066 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
4067 create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
4068 create_announced_chan_between_nodes(&nodes, 3, 5, LocalFeatures::new(), LocalFeatures::new());
4070 // Rebalance and check output sanity...
4071 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
4072 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
4073 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 2);
4075 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4077 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
4079 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
4080 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();
4082 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
4084 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
4086 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4088 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4089 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4091 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4093 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4096 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4098 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();
4099 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
4102 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
4104 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4105 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4107 // Double-check that six of the new HTLC were added
4108 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4109 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4110 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.len(), 1);
4111 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 8);
4113 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4114 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4115 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
4116 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
4117 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
4118 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
4119 check_added_monitors!(nodes[4], 0);
4120 expect_pending_htlcs_forwardable!(nodes[4]);
4121 check_added_monitors!(nodes[4], 1);
4123 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4124 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]).unwrap();
4125 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]).unwrap();
4126 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]).unwrap();
4127 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]).unwrap();
4128 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4130 // Fail 3rd below-dust and 7th above-dust HTLCs
4131 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
4132 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
4133 check_added_monitors!(nodes[5], 0);
4134 expect_pending_htlcs_forwardable!(nodes[5]);
4135 check_added_monitors!(nodes[5], 1);
4137 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4138 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]).unwrap();
4139 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]).unwrap();
4140 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4142 let ds_prev_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
4144 expect_pending_htlcs_forwardable!(nodes[3]);
4145 check_added_monitors!(nodes[3], 1);
4146 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4147 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]).unwrap();
4148 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]).unwrap();
4149 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]).unwrap();
4150 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]).unwrap();
4151 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]).unwrap();
4152 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]).unwrap();
4153 if deliver_last_raa {
4154 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4156 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4159 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4160 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4161 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4162 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4164 // We now broadcast the latest commitment transaction, which *should* result in failures for
4165 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4166 // the non-broadcast above-dust HTLCs.
4168 // Alternatively, we may broadcast the previous commitment transaction, which should only
4169 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4170 let ds_last_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
4172 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4173 if announce_latest {
4174 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_last_commitment_tx[0]], &[1; 1]);
4176 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_prev_commitment_tx[0]], &[1; 1]);
4178 connect_blocks(&nodes[2].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4179 check_closed_broadcast!(nodes[2]);
4180 expect_pending_htlcs_forwardable!(nodes[2]);
4181 check_added_monitors!(nodes[2], 2);
4183 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4184 assert_eq!(cs_msgs.len(), 2);
4185 let mut a_done = false;
4186 for msg in cs_msgs {
4188 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4189 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4190 // should be failed-backwards here.
4191 let target = if *node_id == nodes[0].node.get_our_node_id() {
4192 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4193 for htlc in &updates.update_fail_htlcs {
4194 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 });
4196 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4201 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4202 for htlc in &updates.update_fail_htlcs {
4203 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4205 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4206 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4209 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
4210 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
4211 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]).unwrap();
4212 if announce_latest {
4213 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]).unwrap();
4214 if *node_id == nodes[0].node.get_our_node_id() {
4215 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]).unwrap();
4218 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4220 _ => panic!("Unexpected event"),
4224 let as_events = nodes[0].node.get_and_clear_pending_events();
4225 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4226 let mut as_failds = HashSet::new();
4227 for event in as_events.iter() {
4228 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4229 assert!(as_failds.insert(*payment_hash));
4230 if *payment_hash != payment_hash_2 {
4231 assert_eq!(*rejected_by_dest, deliver_last_raa);
4233 assert!(!rejected_by_dest);
4235 } else { panic!("Unexpected event"); }
4237 assert!(as_failds.contains(&payment_hash_1));
4238 assert!(as_failds.contains(&payment_hash_2));
4239 if announce_latest {
4240 assert!(as_failds.contains(&payment_hash_3));
4241 assert!(as_failds.contains(&payment_hash_5));
4243 assert!(as_failds.contains(&payment_hash_6));
4245 let bs_events = nodes[1].node.get_and_clear_pending_events();
4246 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4247 let mut bs_failds = HashSet::new();
4248 for event in bs_events.iter() {
4249 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4250 assert!(bs_failds.insert(*payment_hash));
4251 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4252 assert_eq!(*rejected_by_dest, deliver_last_raa);
4254 assert!(!rejected_by_dest);
4256 } else { panic!("Unexpected event"); }
4258 assert!(bs_failds.contains(&payment_hash_1));
4259 assert!(bs_failds.contains(&payment_hash_2));
4260 if announce_latest {
4261 assert!(bs_failds.contains(&payment_hash_4));
4263 assert!(bs_failds.contains(&payment_hash_5));
4265 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4266 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4267 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4268 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4269 // PaymentFailureNetworkUpdates.
4270 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4271 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4272 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4273 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4274 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4276 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4277 _ => panic!("Unexpected event"),
4283 fn test_fail_backwards_latest_remote_announce_a() {
4284 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4288 fn test_fail_backwards_latest_remote_announce_b() {
4289 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4293 fn test_fail_backwards_previous_remote_announce() {
4294 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4295 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4296 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4300 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4301 let nodes = create_network(2, &[None, None]);
4303 // Create some initial channels
4304 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4306 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4307 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4308 assert_eq!(local_txn[0].input.len(), 1);
4309 check_spends!(local_txn[0], chan_1.3.clone());
4311 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4312 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4313 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4314 check_closed_broadcast!(nodes[0]);
4316 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4317 assert_eq!(node_txn[0].input.len(), 1);
4318 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4319 check_spends!(node_txn[0], local_txn[0].clone());
4321 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4322 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4323 assert_eq!(spend_txn.len(), 8);
4324 assert_eq!(spend_txn[0], spend_txn[2]);
4325 assert_eq!(spend_txn[0], spend_txn[4]);
4326 assert_eq!(spend_txn[0], spend_txn[6]);
4327 assert_eq!(spend_txn[1], spend_txn[3]);
4328 assert_eq!(spend_txn[1], spend_txn[5]);
4329 assert_eq!(spend_txn[1], spend_txn[7]);
4330 check_spends!(spend_txn[0], local_txn[0].clone());
4331 check_spends!(spend_txn[1], node_txn[0].clone());
4335 fn test_static_output_closing_tx() {
4336 let nodes = create_network(2, &[None, None]);
4338 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4340 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4341 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4343 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4344 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4345 let spend_txn = check_spendable_outputs!(nodes[0], 2);
4346 assert_eq!(spend_txn.len(), 1);
4347 check_spends!(spend_txn[0], closing_tx.clone());
4349 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4350 let spend_txn = check_spendable_outputs!(nodes[1], 2);
4351 assert_eq!(spend_txn.len(), 1);
4352 check_spends!(spend_txn[0], closing_tx);
4355 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4356 let nodes = create_network(2, &[None, None]);
4357 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4359 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4361 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4362 // present in B's local commitment transaction, but none of A's commitment transactions.
4363 assert!(nodes[1].node.claim_funds(our_payment_preimage));
4364 check_added_monitors!(nodes[1], 1);
4366 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4367 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]).unwrap();
4368 let events = nodes[0].node.get_and_clear_pending_events();
4369 assert_eq!(events.len(), 1);
4371 Event::PaymentSent { payment_preimage } => {
4372 assert_eq!(payment_preimage, our_payment_preimage);
4374 _ => panic!("Unexpected event"),
4377 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4378 check_added_monitors!(nodes[0], 1);
4379 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4380 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4381 check_added_monitors!(nodes[1], 1);
4383 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4384 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4385 nodes[1].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4386 header.prev_blockhash = header.bitcoin_hash();
4388 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4389 check_closed_broadcast!(nodes[1]);
4392 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4393 let mut nodes = create_network(2, &[None, None]);
4394 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4396 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();
4397 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4398 nodes[0].node.send_payment(route, payment_hash).unwrap();
4399 check_added_monitors!(nodes[0], 1);
4401 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4403 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4404 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4405 // to "time out" the HTLC.
4407 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4408 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4409 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4410 header.prev_blockhash = header.bitcoin_hash();
4412 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4413 check_closed_broadcast!(nodes[0]);
4416 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4417 let nodes = create_network(3, &[None, None, None]);
4418 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4420 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4421 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4422 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4423 // actually revoked.
4424 let htlc_value = if use_dust { 50000 } else { 3000000 };
4425 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4426 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4427 expect_pending_htlcs_forwardable!(nodes[1]);
4428 check_added_monitors!(nodes[1], 1);
4430 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4431 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]).unwrap();
4432 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4433 check_added_monitors!(nodes[0], 1);
4434 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4435 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4436 check_added_monitors!(nodes[1], 1);
4437 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1).unwrap();
4438 check_added_monitors!(nodes[1], 1);
4439 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4441 if check_revoke_no_close {
4442 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4443 check_added_monitors!(nodes[0], 1);
4446 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4447 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4448 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4449 header.prev_blockhash = header.bitcoin_hash();
4451 if !check_revoke_no_close {
4452 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4453 check_closed_broadcast!(nodes[0]);
4455 let events = nodes[0].node.get_and_clear_pending_events();
4456 assert_eq!(events.len(), 1);
4458 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4459 assert_eq!(payment_hash, our_payment_hash);
4460 assert!(rejected_by_dest);
4462 _ => panic!("Unexpected event"),
4467 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
4468 // There are only a few cases to test here:
4469 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
4470 // broadcastable commitment transactions result in channel closure,
4471 // * its included in an unrevoked-but-previous remote commitment transaction,
4472 // * its included in the latest remote or local commitment transactions.
4473 // We test each of the three possible commitment transactions individually and use both dust and
4475 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
4476 // assume they are handled the same across all six cases, as both outbound and inbound failures are
4477 // tested for at least one of the cases in other tests.
4479 fn htlc_claim_single_commitment_only_a() {
4480 do_htlc_claim_local_commitment_only(true);
4481 do_htlc_claim_local_commitment_only(false);
4483 do_htlc_claim_current_remote_commitment_only(true);
4484 do_htlc_claim_current_remote_commitment_only(false);
4488 fn htlc_claim_single_commitment_only_b() {
4489 do_htlc_claim_previous_remote_commitment_only(true, false);
4490 do_htlc_claim_previous_remote_commitment_only(false, false);
4491 do_htlc_claim_previous_remote_commitment_only(true, true);
4492 do_htlc_claim_previous_remote_commitment_only(false, true);
4495 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>)
4496 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4499 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);
4503 // 0: node1 fails backward
4504 // 1: final node fails backward
4505 // 2: payment completed but the user rejects the payment
4506 // 3: final node fails backward (but tamper onion payloads from node0)
4507 // 100: trigger error in the intermediate node and tamper returning fail_htlc
4508 // 200: trigger error in the final node and tamper returning fail_htlc
4509 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>)
4510 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4511 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
4514 use ln::msgs::HTLCFailChannelUpdate;
4516 // reset block height
4517 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4518 for ix in 0..nodes.len() {
4519 nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
4522 macro_rules! expect_event {
4523 ($node: expr, $event_type: path) => {{
4524 let events = $node.node.get_and_clear_pending_events();
4525 assert_eq!(events.len(), 1);
4527 $event_type { .. } => {},
4528 _ => panic!("Unexpected event"),
4533 macro_rules! expect_htlc_forward {
4535 expect_event!($node, Event::PendingHTLCsForwardable);
4536 $node.node.process_pending_htlc_forwards();
4540 // 0 ~~> 2 send payment
4541 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
4542 check_added_monitors!(nodes[0], 1);
4543 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4544 // temper update_add (0 => 1)
4545 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
4546 if test_case == 0 || test_case == 3 || test_case == 100 {
4547 callback_msg(&mut update_add_0);
4550 // 0 => 1 update_add & CS
4551 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
4552 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
4554 let update_1_0 = match test_case {
4555 0|100 => { // intermediate node failure; fail backward to 0
4556 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4557 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));
4560 1|2|3|200 => { // final node failure; forwarding to 2
4561 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4563 if test_case != 200 {
4566 expect_htlc_forward!(&nodes[1]);
4568 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
4569 check_added_monitors!(&nodes[1], 1);
4570 assert_eq!(update_1.update_add_htlcs.len(), 1);
4571 // tamper update_add (1 => 2)
4572 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
4573 if test_case != 3 && test_case != 200 {
4574 callback_msg(&mut update_add_1);
4578 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
4579 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
4581 if test_case == 2 || test_case == 200 {
4582 expect_htlc_forward!(&nodes[2]);
4583 expect_event!(&nodes[2], Event::PaymentReceived);
4585 expect_pending_htlcs_forwardable!(nodes[2]);
4588 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4589 if test_case == 2 || test_case == 200 {
4590 check_added_monitors!(&nodes[2], 1);
4592 assert!(update_2_1.update_fail_htlcs.len() == 1);
4594 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
4595 if test_case == 200 {
4596 callback_fail(&mut fail_msg);
4600 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
4601 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
4603 // backward fail on 1
4604 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4605 assert!(update_1_0.update_fail_htlcs.len() == 1);
4608 _ => unreachable!(),
4611 // 1 => 0 commitment_signed_dance
4612 if update_1_0.update_fail_htlcs.len() > 0 {
4613 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
4614 if test_case == 100 {
4615 callback_fail(&mut fail_msg);
4617 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
4619 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
4622 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
4624 let events = nodes[0].node.get_and_clear_pending_events();
4625 assert_eq!(events.len(), 1);
4626 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
4627 assert_eq!(*rejected_by_dest, !expected_retryable);
4628 assert_eq!(*error_code, expected_error_code);
4630 panic!("Uexpected event");
4633 let events = nodes[0].node.get_and_clear_pending_msg_events();
4634 if expected_channel_update.is_some() {
4635 assert_eq!(events.len(), 1);
4637 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
4639 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
4640 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
4641 panic!("channel_update not found!");
4644 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
4645 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4646 assert!(*short_channel_id == *expected_short_channel_id);
4647 assert!(*is_permanent == *expected_is_permanent);
4649 panic!("Unexpected message event");
4652 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
4653 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4654 assert!(*node_id == *expected_node_id);
4655 assert!(*is_permanent == *expected_is_permanent);
4657 panic!("Unexpected message event");
4662 _ => panic!("Unexpected message event"),
4665 assert_eq!(events.len(), 0);
4669 impl msgs::ChannelUpdate {
4670 fn dummy() -> msgs::ChannelUpdate {
4671 use secp256k1::ffi::Signature as FFISignature;
4672 use secp256k1::Signature;
4673 msgs::ChannelUpdate {
4674 signature: Signature::from(FFISignature::new()),
4675 contents: msgs::UnsignedChannelUpdate {
4676 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
4677 short_channel_id: 0,
4680 cltv_expiry_delta: 0,
4681 htlc_minimum_msat: 0,
4683 fee_proportional_millionths: 0,
4684 excess_data: vec![],
4691 fn test_onion_failure() {
4692 use ln::msgs::ChannelUpdate;
4693 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
4696 const BADONION: u16 = 0x8000;
4697 const PERM: u16 = 0x4000;
4698 const NODE: u16 = 0x2000;
4699 const UPDATE: u16 = 0x1000;
4701 let mut nodes = create_network(3, &[None, None, None]);
4702 for node in nodes.iter() {
4703 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
4705 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()), create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new())];
4706 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4707 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
4709 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
4711 // intermediate node failure
4712 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
4713 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4714 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4715 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4716 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4717 onion_payloads[0].realm = 3;
4718 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4719 }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
4721 // final node failure
4722 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
4723 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4724 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4725 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4726 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4727 onion_payloads[1].realm = 3;
4728 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4729 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4731 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
4732 // receiving simulated fail messages
4733 // intermediate node failure
4734 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4736 msg.amount_msat -= 1;
4738 // and tamper returning error message
4739 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4740 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4741 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
4742 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
4744 // final node failure
4745 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4746 // and tamper returning error message
4747 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4748 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4749 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
4751 nodes[2].node.fail_htlc_backwards(&payment_hash);
4752 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
4754 // intermediate node failure
4755 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4756 msg.amount_msat -= 1;
4758 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4759 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4760 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
4761 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4763 // final node failure
4764 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4765 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4766 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4767 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
4769 nodes[2].node.fail_htlc_backwards(&payment_hash);
4770 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4772 // intermediate node failure
4773 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4774 msg.amount_msat -= 1;
4776 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4777 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4778 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
4780 nodes[2].node.fail_htlc_backwards(&payment_hash);
4781 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4783 // final node failure
4784 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4785 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4786 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4787 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
4789 nodes[2].node.fail_htlc_backwards(&payment_hash);
4790 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4792 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
4793 Some(BADONION|PERM|4), None);
4795 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
4796 Some(BADONION|PERM|5), None);
4798 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
4799 Some(BADONION|PERM|6), None);
4801 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4802 msg.amount_msat -= 1;
4804 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4805 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4806 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
4807 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4809 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4810 msg.amount_msat -= 1;
4812 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4813 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4814 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
4815 // short_channel_id from the processing node
4816 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4818 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4819 msg.amount_msat -= 1;
4821 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4822 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4823 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
4824 // short_channel_id from the processing node
4825 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4827 let mut bogus_route = route.clone();
4828 bogus_route.hops[1].short_channel_id -= 1;
4829 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
4830 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
4832 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
4833 let mut bogus_route = route.clone();
4834 let route_len = bogus_route.hops.len();
4835 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
4836 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4838 //TODO: with new config API, we will be able to generate both valid and
4839 //invalid channel_update cases.
4840 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
4841 msg.amount_msat -= 1;
4842 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4844 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
4845 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
4846 msg.cltv_expiry -= 1;
4847 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4849 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
4850 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
4851 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4852 nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
4853 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4855 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
4856 nodes[2].node.fail_htlc_backwards(&payment_hash);
4857 }, false, Some(PERM|15), None);
4859 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
4860 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
4861 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4862 nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
4863 }, || {}, true, Some(17), None);
4865 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
4866 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4867 for f in pending_forwards.iter_mut() {
4869 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4870 forward_info.outgoing_cltv_value += 1,
4875 }, true, Some(18), None);
4877 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
4878 // violate amt_to_forward > msg.amount_msat
4879 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4880 for f in pending_forwards.iter_mut() {
4882 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4883 forward_info.amt_to_forward -= 1,
4888 }, true, Some(19), None);
4890 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
4891 // disconnect event to the channel between nodes[1] ~ nodes[2]
4892 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
4893 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4894 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4895 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4897 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
4898 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4899 let mut route = route.clone();
4901 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
4902 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4903 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
4904 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4905 msg.cltv_expiry = htlc_cltv;
4906 msg.onion_routing_packet = onion_packet;
4907 }, ||{}, true, Some(21), None);
4912 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
4913 let nodes = create_network(2, &[None, None]);
4914 //Force duplicate channel ids
4915 for node in nodes.iter() {
4916 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
4919 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
4920 let channel_value_satoshis=10000;
4921 let push_msat=10001;
4922 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).unwrap();
4923 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
4924 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &node0_to_1_send_open_channel).unwrap();
4926 //Create a second channel with a channel_id collision
4927 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4931 fn bolt2_open_channel_sending_node_checks_part2() {
4932 let nodes = create_network(2, &[None, None]);
4934 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
4935 let channel_value_satoshis=2^24;
4936 let push_msat=10001;
4937 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4939 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
4940 let channel_value_satoshis=10000;
4941 // Test when push_msat is equal to 1000 * funding_satoshis.
4942 let push_msat=1000*channel_value_satoshis+1;
4943 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4945 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
4946 let channel_value_satoshis=10000;
4947 let push_msat=10001;
4948 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_ok()); //Create a valid channel
4949 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
4950 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
4952 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
4953 // 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
4954 assert!(node0_to_1_send_open_channel.channel_flags<=1);
4956 // 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.
4957 assert!(BREAKDOWN_TIMEOUT>0);
4958 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
4960 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
4961 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
4962 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
4964 // 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.
4965 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
4966 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
4967 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
4968 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
4969 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
4972 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
4973 // 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.
4974 //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.
4977 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
4978 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
4979 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
4980 let mut nodes = create_network(2, &[None, None]);
4981 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
4982 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4983 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4985 route.hops[0].fee_msat = 0;
4987 let err = nodes[0].node.send_payment(route, our_payment_hash);
4989 if let Err(APIError::ChannelUnavailable{err}) = err {
4990 assert_eq!(err, "Cannot send less than their minimum HTLC value");
4997 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
4998 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
4999 //It is enforced when constructing a route.
5000 let mut nodes = create_network(2, &[None, None]);
5001 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, LocalFeatures::new(), LocalFeatures::new());
5002 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5003 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5005 let err = nodes[0].node.send_payment(route, our_payment_hash);
5007 if let Err(APIError::RouteError{err}) = err {
5008 assert_eq!(err, "Channel CLTV overflowed?!");
5015 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5016 //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.
5017 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5018 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5019 let mut nodes = create_network(2, &[None, None]);
5020 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, LocalFeatures::new(), LocalFeatures::new());
5021 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5023 for i in 0..max_accepted_htlcs {
5024 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5025 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5026 let payment_event = {
5027 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5028 check_added_monitors!(nodes[0], 1);
5030 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5031 assert_eq!(events.len(), 1);
5032 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5033 assert_eq!(htlcs[0].htlc_id, i);
5037 SendEvent::from_event(events.remove(0))
5039 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5040 check_added_monitors!(nodes[1], 0);
5041 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5043 expect_pending_htlcs_forwardable!(nodes[1]);
5044 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5046 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5047 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5048 let err = nodes[0].node.send_payment(route, our_payment_hash);
5050 if let Err(APIError::ChannelUnavailable{err}) = err {
5051 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
5058 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5059 //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.
5060 let mut nodes = create_network(2, &[None, None]);
5061 let channel_value = 100000;
5062 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, LocalFeatures::new(), LocalFeatures::new());
5063 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5065 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
5067 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5068 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5069 let err = nodes[0].node.send_payment(route, our_payment_hash);
5071 if let Err(APIError::ChannelUnavailable{err}) = err {
5072 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight");
5077 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
5080 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5082 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5083 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5084 let mut nodes = create_network(2, &[None, None]);
5085 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5086 let htlc_minimum_msat: u64;
5088 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5089 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5090 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5092 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5093 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5094 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5095 check_added_monitors!(nodes[0], 1);
5096 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5097 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5098 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5099 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5100 assert_eq!(err, "Remote side tried to send less than our minimum HTLC value");
5104 assert!(nodes[1].node.list_channels().is_empty());
5105 check_closed_broadcast!(nodes[1]);
5109 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5110 //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
5111 let mut nodes = create_network(2, &[None, None]);
5112 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5114 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5116 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5117 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5118 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5119 check_added_monitors!(nodes[0], 1);
5120 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5122 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5123 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5125 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5126 assert_eq!(err, "Remote HTLC add would put them over their reserve value");
5131 assert!(nodes[1].node.list_channels().is_empty());
5132 check_closed_broadcast!(nodes[1]);
5136 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5137 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5138 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5139 let mut nodes = create_network(2, &[None, None]);
5140 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5141 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5142 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5144 let session_priv = SecretKey::from_slice(&{
5145 let mut session_key = [0; 32];
5146 let mut rng = thread_rng();
5147 rng.fill_bytes(&mut session_key);
5149 }).expect("RNG is bad!");
5151 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5152 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
5153 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5154 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
5156 let mut msg = msgs::UpdateAddHTLC {
5160 payment_hash: our_payment_hash,
5161 cltv_expiry: htlc_cltv,
5162 onion_routing_packet: onion_packet.clone(),
5165 for i in 0..super::channel::OUR_MAX_HTLCS {
5166 msg.htlc_id = i as u64;
5167 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).unwrap();
5169 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5170 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5172 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5173 assert_eq!(err, "Remote tried to push more than our max accepted HTLCs");
5178 assert!(nodes[1].node.list_channels().is_empty());
5179 check_closed_broadcast!(nodes[1]);
5183 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5184 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5185 let mut nodes = create_network(2, &[None, None]);
5186 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5187 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5188 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5189 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5190 check_added_monitors!(nodes[0], 1);
5191 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5192 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5193 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5195 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5196 assert_eq!(err,"Remote HTLC add would put them over their max HTLC value in flight");
5201 assert!(nodes[1].node.list_channels().is_empty());
5202 check_closed_broadcast!(nodes[1]);
5206 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5207 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
5208 let mut nodes = create_network(2, &[None, None]);
5209 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5210 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5211 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5212 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5213 check_added_monitors!(nodes[0], 1);
5214 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5215 updates.update_add_htlcs[0].cltv_expiry = 500000000;
5216 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5218 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5219 assert_eq!(err,"Remote provided CLTV expiry in seconds instead of block height");
5224 assert!(nodes[1].node.list_channels().is_empty());
5225 check_closed_broadcast!(nodes[1]);
5229 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5230 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5231 // We test this by first testing that that repeated HTLCs pass commitment signature checks
5232 // after disconnect and that non-sequential htlc_ids result in a channel failure.
5233 let mut nodes = create_network(2, &[None, None]);
5234 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5235 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5236 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5237 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5238 check_added_monitors!(nodes[0], 1);
5239 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5240 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5242 //Disconnect and Reconnect
5243 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5244 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5245 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5246 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5247 assert_eq!(reestablish_1.len(), 1);
5248 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5249 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5250 assert_eq!(reestablish_2.len(), 1);
5251 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
5252 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5253 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
5254 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5257 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5258 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5259 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5260 check_added_monitors!(nodes[1], 1);
5261 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5263 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5264 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5265 assert_eq!(err, "Remote skipped HTLC ID");
5270 assert!(nodes[1].node.list_channels().is_empty());
5271 check_closed_broadcast!(nodes[1]);
5275 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5276 //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.
5278 let mut nodes = create_network(2, &[None, None]);
5279 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5281 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5282 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5283 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5284 check_added_monitors!(nodes[0], 1);
5285 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5286 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5288 let update_msg = msgs::UpdateFulfillHTLC{
5291 payment_preimage: our_payment_preimage,
5294 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5296 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5297 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5302 assert!(nodes[0].node.list_channels().is_empty());
5303 check_closed_broadcast!(nodes[0]);
5307 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5308 //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.
5310 let mut nodes = create_network(2, &[None, None]);
5311 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5313 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5314 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5315 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5316 check_added_monitors!(nodes[0], 1);
5317 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5318 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5320 let update_msg = msgs::UpdateFailHTLC{
5323 reason: msgs::OnionErrorPacket { data: Vec::new()},
5326 let err = nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5328 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5329 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5334 assert!(nodes[0].node.list_channels().is_empty());
5335 check_closed_broadcast!(nodes[0]);
5339 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5340 //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.
5342 let mut nodes = create_network(2, &[None, None]);
5343 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5345 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5346 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5347 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5348 check_added_monitors!(nodes[0], 1);
5349 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5350 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5352 let update_msg = msgs::UpdateFailMalformedHTLC{
5355 sha256_of_onion: [1; 32],
5356 failure_code: 0x8000,
5359 let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5361 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5362 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5367 assert!(nodes[0].node.list_channels().is_empty());
5368 check_closed_broadcast!(nodes[0]);
5372 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
5373 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
5375 let nodes = create_network(2, &[None, None]);
5376 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5378 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5380 nodes[1].node.claim_funds(our_payment_preimage);
5381 check_added_monitors!(nodes[1], 1);
5383 let events = nodes[1].node.get_and_clear_pending_msg_events();
5384 assert_eq!(events.len(), 1);
5385 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5387 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, .. } } => {
5388 assert!(update_add_htlcs.is_empty());
5389 assert_eq!(update_fulfill_htlcs.len(), 1);
5390 assert!(update_fail_htlcs.is_empty());
5391 assert!(update_fail_malformed_htlcs.is_empty());
5392 assert!(update_fee.is_none());
5393 update_fulfill_htlcs[0].clone()
5395 _ => panic!("Unexpected event"),
5399 update_fulfill_msg.htlc_id = 1;
5401 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5402 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5403 assert_eq!(err, "Remote tried to fulfill/fail an HTLC we couldn't find");
5408 assert!(nodes[0].node.list_channels().is_empty());
5409 check_closed_broadcast!(nodes[0]);
5413 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
5414 //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.
5416 let nodes = create_network(2, &[None, None]);
5417 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5419 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5421 nodes[1].node.claim_funds(our_payment_preimage);
5422 check_added_monitors!(nodes[1], 1);
5424 let events = nodes[1].node.get_and_clear_pending_msg_events();
5425 assert_eq!(events.len(), 1);
5426 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5428 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, .. } } => {
5429 assert!(update_add_htlcs.is_empty());
5430 assert_eq!(update_fulfill_htlcs.len(), 1);
5431 assert!(update_fail_htlcs.is_empty());
5432 assert!(update_fail_malformed_htlcs.is_empty());
5433 assert!(update_fee.is_none());
5434 update_fulfill_htlcs[0].clone()
5436 _ => panic!("Unexpected event"),
5440 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
5442 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5443 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5444 assert_eq!(err, "Remote tried to fulfill HTLC with an incorrect preimage");
5449 assert!(nodes[0].node.list_channels().is_empty());
5450 check_closed_broadcast!(nodes[0]);
5455 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
5456 //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.
5458 let mut nodes = create_network(2, &[None, None]);
5459 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5460 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5461 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5462 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5463 check_added_monitors!(nodes[0], 1);
5465 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5466 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5468 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5469 check_added_monitors!(nodes[1], 0);
5470 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
5472 let events = nodes[1].node.get_and_clear_pending_msg_events();
5474 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
5476 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, .. } } => {
5477 assert!(update_add_htlcs.is_empty());
5478 assert!(update_fulfill_htlcs.is_empty());
5479 assert!(update_fail_htlcs.is_empty());
5480 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5481 assert!(update_fee.is_none());
5482 update_fail_malformed_htlcs[0].clone()
5484 _ => panic!("Unexpected event"),
5487 update_msg.failure_code &= !0x8000;
5488 let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5489 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5490 assert_eq!(err, "Got update_fail_malformed_htlc with BADONION not set");
5495 assert!(nodes[0].node.list_channels().is_empty());
5496 check_closed_broadcast!(nodes[0]);
5500 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
5501 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
5502 // * 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.
5504 let mut nodes = create_network(3, &[None, None, None]);
5505 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5506 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5508 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
5509 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5512 let mut payment_event = {
5513 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5514 check_added_monitors!(nodes[0], 1);
5515 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5516 assert_eq!(events.len(), 1);
5517 SendEvent::from_event(events.remove(0))
5519 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5520 check_added_monitors!(nodes[1], 0);
5521 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5522 expect_pending_htlcs_forwardable!(nodes[1]);
5523 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
5524 assert_eq!(events_2.len(), 1);
5525 check_added_monitors!(nodes[1], 1);
5526 payment_event = SendEvent::from_event(events_2.remove(0));
5527 assert_eq!(payment_event.msgs.len(), 1);
5530 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5531 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5532 check_added_monitors!(nodes[2], 0);
5533 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
5535 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
5536 assert_eq!(events_3.len(), 1);
5537 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
5539 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 } } => {
5540 assert!(update_add_htlcs.is_empty());
5541 assert!(update_fulfill_htlcs.is_empty());
5542 assert!(update_fail_htlcs.is_empty());
5543 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5544 assert!(update_fee.is_none());
5545 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
5547 _ => panic!("Unexpected event"),
5551 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0).unwrap();
5553 check_added_monitors!(nodes[1], 0);
5554 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
5555 expect_pending_htlcs_forwardable!(nodes[1]);
5556 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
5557 assert_eq!(events_4.len(), 1);
5559 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
5561 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, .. } } => {
5562 assert!(update_add_htlcs.is_empty());
5563 assert!(update_fulfill_htlcs.is_empty());
5564 assert_eq!(update_fail_htlcs.len(), 1);
5565 assert!(update_fail_malformed_htlcs.is_empty());
5566 assert!(update_fee.is_none());
5568 _ => panic!("Unexpected event"),
5571 check_added_monitors!(nodes[1], 1);
5574 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
5575 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
5576 // 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
5577 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
5579 let nodes = create_network(2, &[None, None]);
5580 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5582 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5584 // We route 2 dust-HTLCs between A and B
5585 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5586 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5587 route_payment(&nodes[0], &[&nodes[1]], 1000000);
5589 // Cache one local commitment tx as previous
5590 let as_prev_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5592 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
5593 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
5594 check_added_monitors!(nodes[1], 0);
5595 expect_pending_htlcs_forwardable!(nodes[1]);
5596 check_added_monitors!(nodes[1], 1);
5598 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5599 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]).unwrap();
5600 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed).unwrap();
5601 check_added_monitors!(nodes[0], 1);
5603 // Cache one local commitment tx as lastest
5604 let as_last_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5606 let events = nodes[0].node.get_and_clear_pending_msg_events();
5608 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
5609 assert_eq!(node_id, nodes[1].node.get_our_node_id());
5611 _ => panic!("Unexpected event"),
5614 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
5615 assert_eq!(node_id, nodes[1].node.get_our_node_id());
5617 _ => panic!("Unexpected event"),
5620 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
5621 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
5622 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5623 if announce_latest {
5624 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&as_last_commitment_tx[0]], &[1; 1]);
5626 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&as_prev_commitment_tx[0]], &[1; 1]);
5629 let events = nodes[0].node.get_and_clear_pending_msg_events();
5630 assert_eq!(events.len(), 1);
5632 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5633 _ => panic!("Unexpected event"),
5636 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5637 connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
5638 let events = nodes[0].node.get_and_clear_pending_events();
5639 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
5640 assert_eq!(events.len(), 2);
5641 let mut first_failed = false;
5642 for event in events {
5644 Event::PaymentFailed { payment_hash, .. } => {
5645 if payment_hash == payment_hash_1 {
5646 assert!(!first_failed);
5647 first_failed = true;
5649 assert_eq!(payment_hash, payment_hash_2);
5652 _ => panic!("Unexpected event"),
5658 fn test_failure_delay_dust_htlc_local_commitment() {
5659 do_test_failure_delay_dust_htlc_local_commitment(true);
5660 do_test_failure_delay_dust_htlc_local_commitment(false);
5664 fn test_no_failure_dust_htlc_local_commitment() {
5665 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
5666 // prone to error, we test here that a dummy transaction don't fail them.
5668 let nodes = create_network(2, &[None, None]);
5669 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5672 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
5674 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5675 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5677 // We route 2 dust-HTLCs between A and B
5678 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5679 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
5681 // Build a dummy invalid transaction trying to spend a commitment tx
5683 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
5684 script_sig: Script::new(),
5686 witness: Vec::new(),
5690 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
5694 let dummy_tx = Transaction {
5701 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5702 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
5703 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5704 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5705 // We broadcast a few more block to check everything is all right
5706 connect_blocks(&nodes[0].chain_monitor, 20, 1, true, header.bitcoin_hash());
5707 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5708 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5710 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1);
5711 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2);
5714 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
5715 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
5716 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
5717 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
5718 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
5719 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
5720 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
5722 let nodes = create_network(3, &[None, None, None]);
5723 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5725 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5727 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5728 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5730 let as_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5731 let bs_commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5733 // We revoked bs_commitment_tx
5735 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5736 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
5739 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5740 let mut timeout_tx = Vec::new();
5742 // We fail dust-HTLC 1 by broadcast of local commitment tx
5743 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&as_commitment_tx[0]], &[1; 1]);
5744 let events = nodes[0].node.get_and_clear_pending_msg_events();
5745 assert_eq!(events.len(), 1);
5747 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5748 _ => panic!("Unexpected event"),
5750 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5751 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5752 let parent_hash = connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5753 let events = nodes[0].node.get_and_clear_pending_events();
5754 assert_eq!(events.len(), 1);
5756 Event::PaymentFailed { payment_hash, .. } => {
5757 assert_eq!(payment_hash, dust_hash);
5759 _ => panic!("Unexpected event"),
5761 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5762 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
5763 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5764 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5765 nodes[0].chain_monitor.block_connected_checked(&header_2, 7, &[&timeout_tx[0]], &[1; 1]);
5766 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5767 connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5768 let events = nodes[0].node.get_and_clear_pending_events();
5769 assert_eq!(events.len(), 1);
5771 Event::PaymentFailed { payment_hash, .. } => {
5772 assert_eq!(payment_hash, non_dust_hash);
5774 _ => panic!("Unexpected event"),
5777 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
5778 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&bs_commitment_tx[0]], &[1; 1]);
5779 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5780 let events = nodes[0].node.get_and_clear_pending_msg_events();
5781 assert_eq!(events.len(), 1);
5783 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5784 _ => panic!("Unexpected event"),
5786 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5787 let parent_hash = connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5788 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5790 let events = nodes[0].node.get_and_clear_pending_events();
5791 assert_eq!(events.len(), 1);
5793 Event::PaymentFailed { payment_hash, .. } => {
5794 assert_eq!(payment_hash, dust_hash);
5796 _ => panic!("Unexpected event"),
5798 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5799 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
5800 nodes[0].chain_monitor.block_connected_checked(&header_2, 7, &[&timeout_tx[0]], &[1; 1]);
5801 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5802 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5803 connect_blocks(&nodes[0].chain_monitor, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5804 let events = nodes[0].node.get_and_clear_pending_events();
5805 assert_eq!(events.len(), 1);
5807 Event::PaymentFailed { payment_hash, .. } => {
5808 assert_eq!(payment_hash, non_dust_hash);
5810 _ => panic!("Unexpected event"),
5813 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
5815 let events = nodes[0].node.get_and_clear_pending_events();
5816 assert_eq!(events.len(), 2);
5819 Event::PaymentFailed { payment_hash, .. } => {
5820 if payment_hash == dust_hash { first = true; }
5821 else { first = false; }
5823 _ => panic!("Unexpected event"),
5826 Event::PaymentFailed { payment_hash, .. } => {
5827 if first { assert_eq!(payment_hash, non_dust_hash); }
5828 else { assert_eq!(payment_hash, dust_hash); }
5830 _ => panic!("Unexpected event"),
5837 fn test_sweep_outbound_htlc_failure_update() {
5838 do_test_sweep_outbound_htlc_failure_update(false, true);
5839 do_test_sweep_outbound_htlc_failure_update(false, false);
5840 do_test_sweep_outbound_htlc_failure_update(true, false);
5844 fn test_upfront_shutdown_script() {
5845 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
5846 // enforce it at shutdown message
5848 let mut config = UserConfig::new();
5849 config.channel_options.announced_channel = true;
5850 config.peer_channel_config_limits.force_announced_channel_preference = false;
5851 config.channel_options.commit_upfront_shutdown_pubkey = false;
5852 let nodes = create_network(3, &[None, Some(config), None]);
5854 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
5855 let flags = LocalFeatures::new();
5856 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5857 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5858 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5859 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5860 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
5861 if let Err(error) = nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown) {
5862 if let Some(error) = error.action {
5864 ErrorAction::SendErrorMessage { msg } => {
5865 assert_eq!(msg.data,"Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
5867 _ => { assert!(false); }
5869 } else { assert!(false); }
5870 } else { assert!(false); }
5871 let events = nodes[2].node.get_and_clear_pending_msg_events();
5872 assert_eq!(events.len(), 1);
5874 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5875 _ => panic!("Unexpected event"),
5878 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
5879 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5880 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5881 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5882 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
5883 if let Ok(_) = nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown) {}
5884 else { assert!(false) }
5885 let events = nodes[2].node.get_and_clear_pending_msg_events();
5886 assert_eq!(events.len(), 1);
5888 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
5889 _ => panic!("Unexpected event"),
5892 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
5893 let mut flags_no = LocalFeatures::new();
5894 flags_no.unset_upfront_shutdown_script();
5895 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
5896 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5897 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
5898 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5899 if let Ok(_) = nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown) {}
5900 else { assert!(false) }
5901 let events = nodes[1].node.get_and_clear_pending_msg_events();
5902 assert_eq!(events.len(), 1);
5904 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
5905 _ => panic!("Unexpected event"),
5908 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
5909 // channel smoothly, opt-out is from channel initiator here
5910 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
5911 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5912 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5913 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5914 if let Ok(_) = nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown) {}
5915 else { assert!(false) }
5916 let events = nodes[0].node.get_and_clear_pending_msg_events();
5917 assert_eq!(events.len(), 1);
5919 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
5920 _ => panic!("Unexpected event"),
5923 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
5924 //// channel smoothly
5925 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
5926 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5927 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
5928 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5929 if let Ok(_) = nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown) {}
5930 else { assert!(false) }
5931 let events = nodes[0].node.get_and_clear_pending_msg_events();
5932 assert_eq!(events.len(), 2);
5934 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
5935 _ => panic!("Unexpected event"),
5938 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
5939 _ => panic!("Unexpected event"),
5944 fn test_user_configurable_csv_delay() {
5945 // We test our channel constructors yield errors when we pass them absurd csv delay
5947 let mut low_our_to_self_config = UserConfig::new();
5948 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
5949 let mut high_their_to_self_config = UserConfig::new();
5950 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
5951 let nodes = create_network(2, &[Some(high_their_to_self_config.clone()), None]);
5953 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
5954 let keys_manager: Arc<KeysInterface> = Arc::new(KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()), 10, 20));
5955 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) {
5957 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
5958 _ => panic!("Unexpected event"),
5960 } else { assert!(false) }
5962 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
5963 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
5964 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
5965 open_channel.to_self_delay = 200;
5966 if let Err(error) = Channel::new_from_req(&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), LocalFeatures::new(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &low_our_to_self_config) {
5968 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
5969 _ => panic!("Unexpected event"),
5971 } else { assert!(false); }
5973 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
5974 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
5975 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id())).unwrap();
5976 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
5977 accept_channel.to_self_delay = 200;
5978 if let Err(error) = nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), LocalFeatures::new(), &accept_channel) {
5979 if let Some(error) = error.action {
5981 ErrorAction::SendErrorMessage { msg } => {
5982 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
5984 _ => { assert!(false); }
5986 } else { assert!(false); }
5987 } else { assert!(false); }
5989 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
5990 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
5991 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
5992 open_channel.to_self_delay = 200;
5993 if let Err(error) = Channel::new_from_req(&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), LocalFeatures::new(), &open_channel, 0, Arc::new(test_utils::TestLogger::new()), &high_their_to_self_config) {
5995 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
5996 _ => panic!("Unexpected event"),
5998 } else { assert!(false); }