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, ChainWatchInterfaceUtil};
7 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor, KeysManager};
8 use chain::keysinterface;
9 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
10 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, BREAKDOWN_TIMEOUT};
11 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
12 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT, Channel, ChannelError};
14 use ln::router::{Route, RouteHop};
16 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, LocalFeatures, ErrorAction};
18 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
19 use util::errors::APIError;
20 use util::ser::{Writeable, ReadableArgs};
21 use util::config::UserConfig;
22 use util::logger::Logger;
24 use bitcoin::util::hash::BitcoinHash;
25 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
26 use bitcoin::util::bip143;
27 use bitcoin::util::address::Address;
28 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
29 use bitcoin::blockdata::block::{Block, BlockHeader};
30 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
31 use bitcoin::blockdata::script::{Builder, Script};
32 use bitcoin::blockdata::opcodes;
33 use bitcoin::blockdata::constants::genesis_block;
34 use bitcoin::network::constants::Network;
36 use bitcoin_hashes::sha256::Hash as Sha256;
37 use bitcoin_hashes::Hash;
39 use secp256k1::{Secp256k1, Message};
40 use secp256k1::key::{PublicKey,SecretKey};
42 use std::collections::{BTreeSet, HashMap, HashSet};
43 use std::default::Default;
44 use std::sync::{Arc, Mutex};
45 use std::sync::atomic::Ordering;
48 use rand::{thread_rng, Rng};
50 use ln::functional_test_utils::*;
53 fn test_insane_channel_opens() {
54 // Stand up a network of 2 nodes
55 let nodes = create_network(2, &[None, None]);
57 // Instantiate channel parameters where we push the maximum msats given our
59 let channel_value_sat = 31337; // same as funding satoshis
60 let channel_reserve_satoshis = Channel::get_our_channel_reserve_satoshis(channel_value_sat);
61 let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
63 // Have node0 initiate a channel to node1 with aforementioned parameters
64 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42).unwrap();
66 // Extract the channel open message from node0 to node1
67 let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
69 // Test helper that asserts we get the correct error string given a mutator
70 // that supposedly makes the channel open message insane
71 let insane_open_helper = |expected_error_str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
72 match nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &message_mutator(open_channel_message.clone())) {
73 Err(msgs::LightningError{ err: error_str, action: msgs::ErrorAction::SendErrorMessage {..}}) => {
74 assert_eq!(error_str, expected_error_str, "unexpected LightningError string (expected `{}`, actual `{}`)", expected_error_str, error_str)
76 Err(msgs::LightningError{..}) => {panic!("unexpected LightningError action")},
77 _ => panic!("insane OpenChannel message was somehow Ok"),
81 use ln::channel::MAX_FUNDING_SATOSHIS;
82 use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
84 // Test all mutations that would make the channel open message insane
85 insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
87 insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
89 insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
91 insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
93 insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
95 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 });
97 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 });
99 insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
101 insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
105 fn test_async_inbound_update_fee() {
106 let mut nodes = create_network(2, &[None, None]);
107 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
108 let channel_id = chan.2;
111 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
115 // send (1) commitment_signed -.
116 // <- update_add_htlc/commitment_signed
117 // send (2) RAA (awaiting remote revoke) -.
118 // (1) commitment_signed is delivered ->
119 // .- send (3) RAA (awaiting remote revoke)
120 // (2) RAA is delivered ->
121 // .- send (4) commitment_signed
122 // <- (3) RAA is delivered
123 // send (5) commitment_signed -.
124 // <- (4) commitment_signed is delivered
126 // (5) commitment_signed is delivered ->
128 // (6) RAA is delivered ->
130 // First nodes[0] generates an update_fee
131 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
132 check_added_monitors!(nodes[0], 1);
134 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
135 assert_eq!(events_0.len(), 1);
136 let (update_msg, commitment_signed) = match events_0[0] { // (1)
137 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
138 (update_fee.as_ref(), commitment_signed)
140 _ => panic!("Unexpected event"),
143 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
145 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
146 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
147 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();
148 check_added_monitors!(nodes[1], 1);
150 let payment_event = {
151 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
152 assert_eq!(events_1.len(), 1);
153 SendEvent::from_event(events_1.remove(0))
155 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
156 assert_eq!(payment_event.msgs.len(), 1);
158 // ...now when the messages get delivered everyone should be happy
159 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
160 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
161 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
162 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
163 check_added_monitors!(nodes[0], 1);
165 // deliver(1), generate (3):
166 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
167 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
168 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
169 check_added_monitors!(nodes[1], 1);
171 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
172 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
173 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
174 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
175 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
176 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
177 assert!(bs_update.update_fee.is_none()); // (4)
178 check_added_monitors!(nodes[1], 1);
180 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
181 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
182 assert!(as_update.update_add_htlcs.is_empty()); // (5)
183 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
184 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
185 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
186 assert!(as_update.update_fee.is_none()); // (5)
187 check_added_monitors!(nodes[0], 1);
189 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
190 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
191 // only (6) so get_event_msg's assert(len == 1) passes
192 check_added_monitors!(nodes[0], 1);
194 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
195 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
196 check_added_monitors!(nodes[1], 1);
198 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
199 check_added_monitors!(nodes[0], 1);
201 let events_2 = nodes[0].node.get_and_clear_pending_events();
202 assert_eq!(events_2.len(), 1);
204 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
205 _ => panic!("Unexpected event"),
208 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
209 check_added_monitors!(nodes[1], 1);
213 fn test_update_fee_unordered_raa() {
214 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
215 // crash in an earlier version of the update_fee patch)
216 let mut nodes = create_network(2, &[None, None]);
217 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
218 let channel_id = chan.2;
221 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
223 // First nodes[0] generates an update_fee
224 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
225 check_added_monitors!(nodes[0], 1);
227 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
228 assert_eq!(events_0.len(), 1);
229 let update_msg = match events_0[0] { // (1)
230 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
233 _ => panic!("Unexpected event"),
236 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
238 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
239 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
240 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();
241 check_added_monitors!(nodes[1], 1);
243 let payment_event = {
244 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
245 assert_eq!(events_1.len(), 1);
246 SendEvent::from_event(events_1.remove(0))
248 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
249 assert_eq!(payment_event.msgs.len(), 1);
251 // ...now when the messages get delivered everyone should be happy
252 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
253 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
254 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
255 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
256 check_added_monitors!(nodes[0], 1);
258 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
259 check_added_monitors!(nodes[1], 1);
261 // We can't continue, sadly, because our (1) now has a bogus signature
265 fn test_multi_flight_update_fee() {
266 let nodes = create_network(2, &[None, None]);
267 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
268 let channel_id = chan.2;
271 // update_fee/commitment_signed ->
272 // .- send (1) RAA and (2) commitment_signed
273 // update_fee (never committed) ->
275 // We have to manually generate the above update_fee, it is allowed by the protocol but we
276 // don't track which updates correspond to which revoke_and_ack responses so we're in
277 // AwaitingRAA mode and will not generate the update_fee yet.
278 // <- (1) RAA delivered
279 // (3) is generated and send (4) CS -.
280 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
281 // know the per_commitment_point to use for it.
282 // <- (2) commitment_signed delivered
284 // B should send no response here
285 // (4) commitment_signed delivered ->
286 // <- RAA/commitment_signed delivered
289 // First nodes[0] generates an update_fee
290 let initial_feerate = get_feerate!(nodes[0], channel_id);
291 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
292 check_added_monitors!(nodes[0], 1);
294 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
295 assert_eq!(events_0.len(), 1);
296 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
297 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
298 (update_fee.as_ref().unwrap(), commitment_signed)
300 _ => panic!("Unexpected event"),
303 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
304 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
305 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
306 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
307 check_added_monitors!(nodes[1], 1);
309 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
311 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
312 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
313 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
315 // Create the (3) update_fee message that nodes[0] will generate before it does...
316 let mut update_msg_2 = msgs::UpdateFee {
317 channel_id: update_msg_1.channel_id.clone(),
318 feerate_per_kw: (initial_feerate + 30) as u32,
321 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
323 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
325 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
327 // Deliver (1), generating (3) and (4)
328 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
329 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
330 check_added_monitors!(nodes[0], 1);
331 assert!(as_second_update.update_add_htlcs.is_empty());
332 assert!(as_second_update.update_fulfill_htlcs.is_empty());
333 assert!(as_second_update.update_fail_htlcs.is_empty());
334 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
335 // Check that the update_fee newly generated matches what we delivered:
336 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
337 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
339 // Deliver (2) commitment_signed
340 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
341 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
342 check_added_monitors!(nodes[0], 1);
343 // No commitment_signed so get_event_msg's assert(len == 1) passes
345 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
346 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
347 check_added_monitors!(nodes[1], 1);
350 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
351 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
352 check_added_monitors!(nodes[1], 1);
354 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
355 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
356 check_added_monitors!(nodes[0], 1);
358 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
359 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
360 // No commitment_signed so get_event_msg's assert(len == 1) passes
361 check_added_monitors!(nodes[0], 1);
363 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
364 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
365 check_added_monitors!(nodes[1], 1);
369 fn test_update_fee_vanilla() {
370 let nodes = create_network(2, &[None, None]);
371 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
372 let channel_id = chan.2;
374 let feerate = get_feerate!(nodes[0], channel_id);
375 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
376 check_added_monitors!(nodes[0], 1);
378 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
379 assert_eq!(events_0.len(), 1);
380 let (update_msg, commitment_signed) = match events_0[0] {
381 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 } } => {
382 (update_fee.as_ref(), commitment_signed)
384 _ => panic!("Unexpected event"),
386 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
388 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
389 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
390 check_added_monitors!(nodes[1], 1);
392 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
393 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
394 check_added_monitors!(nodes[0], 1);
396 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
397 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
398 // No commitment_signed so get_event_msg's assert(len == 1) passes
399 check_added_monitors!(nodes[0], 1);
401 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
402 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
403 check_added_monitors!(nodes[1], 1);
407 fn test_update_fee_that_funder_cannot_afford() {
408 let nodes = create_network(2, &[None, None]);
409 let channel_value = 1888;
410 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, LocalFeatures::new(), LocalFeatures::new());
411 let channel_id = chan.2;
414 nodes[0].node.update_fee(channel_id, feerate).unwrap();
415 check_added_monitors!(nodes[0], 1);
416 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
418 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
420 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
422 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
423 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
425 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
426 let chan = chan_lock.by_id.get(&channel_id).unwrap();
428 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
429 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
430 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
431 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
432 actual_fee = channel_value - actual_fee;
433 assert_eq!(total_fee, actual_fee);
436 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
437 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
438 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
439 check_added_monitors!(nodes[0], 1);
441 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
443 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
445 //While producing the commitment_signed response after handling a received update_fee request the
446 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
447 //Should produce and error.
448 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
450 assert!(match err.err {
451 "Funding remote cannot afford proposed new fee" => true,
455 //clear the message we could not handle
456 nodes[1].node.get_and_clear_pending_msg_events();
460 fn test_update_fee_with_fundee_update_add_htlc() {
461 let mut nodes = create_network(2, &[None, None]);
462 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
463 let channel_id = chan.2;
466 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
468 let feerate = get_feerate!(nodes[0], channel_id);
469 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
470 check_added_monitors!(nodes[0], 1);
472 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
473 assert_eq!(events_0.len(), 1);
474 let (update_msg, commitment_signed) = match events_0[0] {
475 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 } } => {
476 (update_fee.as_ref(), commitment_signed)
478 _ => panic!("Unexpected event"),
480 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
481 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
482 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
483 check_added_monitors!(nodes[1], 1);
485 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
487 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
489 // nothing happens since node[1] is in AwaitingRemoteRevoke
490 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
492 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
493 assert_eq!(added_monitors.len(), 0);
494 added_monitors.clear();
496 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
497 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
498 // node[1] has nothing to do
500 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
501 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
502 check_added_monitors!(nodes[0], 1);
504 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
505 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
506 // No commitment_signed so get_event_msg's assert(len == 1) passes
507 check_added_monitors!(nodes[0], 1);
508 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
509 check_added_monitors!(nodes[1], 1);
510 // AwaitingRemoteRevoke ends here
512 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
513 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
514 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
515 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
516 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
517 assert_eq!(commitment_update.update_fee.is_none(), true);
519 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
520 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
521 check_added_monitors!(nodes[0], 1);
522 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
524 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
525 check_added_monitors!(nodes[1], 1);
526 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
528 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
529 check_added_monitors!(nodes[1], 1);
530 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
531 // No commitment_signed so get_event_msg's assert(len == 1) passes
533 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
534 check_added_monitors!(nodes[0], 1);
535 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
537 expect_pending_htlcs_forwardable!(nodes[0]);
539 let events = nodes[0].node.get_and_clear_pending_events();
540 assert_eq!(events.len(), 1);
542 Event::PaymentReceived { .. } => { },
543 _ => panic!("Unexpected event"),
546 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
548 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
549 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
550 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
554 fn test_update_fee() {
555 let nodes = create_network(2, &[None, None]);
556 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
557 let channel_id = chan.2;
560 // (1) update_fee/commitment_signed ->
561 // <- (2) revoke_and_ack
562 // .- send (3) commitment_signed
563 // (4) update_fee/commitment_signed ->
564 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
565 // <- (3) commitment_signed delivered
566 // send (6) revoke_and_ack -.
567 // <- (5) deliver revoke_and_ack
568 // (6) deliver revoke_and_ack ->
569 // .- send (7) commitment_signed in response to (4)
570 // <- (7) deliver commitment_signed
573 // Create and deliver (1)...
574 let feerate = get_feerate!(nodes[0], channel_id);
575 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
576 check_added_monitors!(nodes[0], 1);
578 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
579 assert_eq!(events_0.len(), 1);
580 let (update_msg, commitment_signed) = match events_0[0] {
581 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 } } => {
582 (update_fee.as_ref(), commitment_signed)
584 _ => panic!("Unexpected event"),
586 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
588 // Generate (2) and (3):
589 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
590 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
591 check_added_monitors!(nodes[1], 1);
594 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
595 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
596 check_added_monitors!(nodes[0], 1);
598 // Create and deliver (4)...
599 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
600 check_added_monitors!(nodes[0], 1);
601 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
602 assert_eq!(events_0.len(), 1);
603 let (update_msg, commitment_signed) = match events_0[0] {
604 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 } } => {
605 (update_fee.as_ref(), commitment_signed)
607 _ => panic!("Unexpected event"),
610 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
611 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
612 check_added_monitors!(nodes[1], 1);
614 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
615 // No commitment_signed so get_event_msg's assert(len == 1) passes
617 // Handle (3), creating (6):
618 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
619 check_added_monitors!(nodes[0], 1);
620 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
621 // No commitment_signed so get_event_msg's assert(len == 1) passes
624 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
625 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
626 check_added_monitors!(nodes[0], 1);
628 // Deliver (6), creating (7):
629 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
630 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
631 assert!(commitment_update.update_add_htlcs.is_empty());
632 assert!(commitment_update.update_fulfill_htlcs.is_empty());
633 assert!(commitment_update.update_fail_htlcs.is_empty());
634 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
635 assert!(commitment_update.update_fee.is_none());
636 check_added_monitors!(nodes[1], 1);
639 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
640 check_added_monitors!(nodes[0], 1);
641 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
642 // No commitment_signed so get_event_msg's assert(len == 1) passes
644 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
645 check_added_monitors!(nodes[1], 1);
646 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
648 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
649 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
650 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
654 fn pre_funding_lock_shutdown_test() {
655 // Test sending a shutdown prior to funding_locked after funding generation
656 let nodes = create_network(2, &[None, None]);
657 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, LocalFeatures::new(), LocalFeatures::new());
658 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
659 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
660 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
662 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
663 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
664 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
665 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
666 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
668 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
669 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
670 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
671 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
672 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
673 assert!(node_0_none.is_none());
675 assert!(nodes[0].node.list_channels().is_empty());
676 assert!(nodes[1].node.list_channels().is_empty());
680 fn updates_shutdown_wait() {
681 // Test sending a shutdown with outstanding updates pending
682 let mut nodes = create_network(3, &[None, None, None]);
683 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
684 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
685 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
686 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
688 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
690 nodes[0].node.close_channel(&chan_1.2).unwrap();
691 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
692 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
693 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
694 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
696 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
697 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
699 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
700 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
701 else { panic!("New sends should fail!") };
702 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
703 else { panic!("New sends should fail!") };
705 assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
706 check_added_monitors!(nodes[2], 1);
707 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
708 assert!(updates.update_add_htlcs.is_empty());
709 assert!(updates.update_fail_htlcs.is_empty());
710 assert!(updates.update_fail_malformed_htlcs.is_empty());
711 assert!(updates.update_fee.is_none());
712 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
713 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
714 check_added_monitors!(nodes[1], 1);
715 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
716 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
718 assert!(updates_2.update_add_htlcs.is_empty());
719 assert!(updates_2.update_fail_htlcs.is_empty());
720 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
721 assert!(updates_2.update_fee.is_none());
722 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
723 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
724 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
726 let events = nodes[0].node.get_and_clear_pending_events();
727 assert_eq!(events.len(), 1);
729 Event::PaymentSent { ref payment_preimage } => {
730 assert_eq!(our_payment_preimage, *payment_preimage);
732 _ => panic!("Unexpected event"),
735 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
736 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
737 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
738 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
739 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
740 assert!(node_0_none.is_none());
742 assert!(nodes[0].node.list_channels().is_empty());
744 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
745 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
746 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
747 assert!(nodes[1].node.list_channels().is_empty());
748 assert!(nodes[2].node.list_channels().is_empty());
752 fn htlc_fail_async_shutdown() {
753 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
754 let mut nodes = create_network(3, &[None, None, None]);
755 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
756 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
758 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
759 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
760 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
761 check_added_monitors!(nodes[0], 1);
762 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
763 assert_eq!(updates.update_add_htlcs.len(), 1);
764 assert!(updates.update_fulfill_htlcs.is_empty());
765 assert!(updates.update_fail_htlcs.is_empty());
766 assert!(updates.update_fail_malformed_htlcs.is_empty());
767 assert!(updates.update_fee.is_none());
769 nodes[1].node.close_channel(&chan_1.2).unwrap();
770 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
771 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
772 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
774 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
775 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
776 check_added_monitors!(nodes[1], 1);
777 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
778 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
780 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
781 assert!(updates_2.update_add_htlcs.is_empty());
782 assert!(updates_2.update_fulfill_htlcs.is_empty());
783 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
784 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
785 assert!(updates_2.update_fee.is_none());
787 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
788 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
790 let events = nodes[0].node.get_and_clear_pending_events();
791 assert_eq!(events.len(), 1);
793 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
794 assert_eq!(our_payment_hash, *payment_hash);
795 assert!(!rejected_by_dest);
797 _ => panic!("Unexpected event"),
800 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
801 assert_eq!(msg_events.len(), 2);
802 let node_0_closing_signed = match msg_events[0] {
803 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
804 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
807 _ => panic!("Unexpected event"),
809 match msg_events[1] {
810 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
811 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
813 _ => panic!("Unexpected event"),
816 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
817 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
818 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
819 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
820 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
821 assert!(node_0_none.is_none());
823 assert!(nodes[0].node.list_channels().is_empty());
825 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
826 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
827 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
828 assert!(nodes[1].node.list_channels().is_empty());
829 assert!(nodes[2].node.list_channels().is_empty());
832 fn do_test_shutdown_rebroadcast(recv_count: u8) {
833 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
834 // messages delivered prior to disconnect
835 let nodes = create_network(3, &[None, None, None]);
836 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
837 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
839 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
841 nodes[1].node.close_channel(&chan_1.2).unwrap();
842 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
844 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
845 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
847 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
851 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
852 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
854 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
855 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
856 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
857 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
859 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
860 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
861 assert!(node_1_shutdown == node_1_2nd_shutdown);
863 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
864 let node_0_2nd_shutdown = if recv_count > 0 {
865 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
866 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
869 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
870 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
871 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
873 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
875 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
876 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
878 assert!(nodes[2].node.claim_funds(our_payment_preimage, 100_000));
879 check_added_monitors!(nodes[2], 1);
880 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
881 assert!(updates.update_add_htlcs.is_empty());
882 assert!(updates.update_fail_htlcs.is_empty());
883 assert!(updates.update_fail_malformed_htlcs.is_empty());
884 assert!(updates.update_fee.is_none());
885 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
886 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
887 check_added_monitors!(nodes[1], 1);
888 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
889 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
891 assert!(updates_2.update_add_htlcs.is_empty());
892 assert!(updates_2.update_fail_htlcs.is_empty());
893 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
894 assert!(updates_2.update_fee.is_none());
895 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
896 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
897 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
899 let events = nodes[0].node.get_and_clear_pending_events();
900 assert_eq!(events.len(), 1);
902 Event::PaymentSent { ref payment_preimage } => {
903 assert_eq!(our_payment_preimage, *payment_preimage);
905 _ => panic!("Unexpected event"),
908 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
910 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
911 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
912 assert!(node_1_closing_signed.is_some());
915 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
916 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
918 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
919 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
920 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
922 // If all closing_signeds weren't delivered we can just resume where we left off...
923 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
925 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
926 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
927 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
929 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
930 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
931 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
933 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
934 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
936 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
937 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
938 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
940 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
941 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
942 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
943 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
944 assert!(node_0_none.is_none());
946 // If one node, however, received + responded with an identical closing_signed we end
947 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
948 // There isn't really anything better we can do simply, but in the future we might
949 // explore storing a set of recently-closed channels that got disconnected during
950 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
951 // give our counterparty enough time to (potentially) broadcast a cooperative closing
953 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
955 if let Err(msgs::LightningError{action: msgs::ErrorAction::SendErrorMessage{msg}, ..}) =
956 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
957 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
958 let msgs::ErrorMessage {ref channel_id, ..} = msg;
959 assert_eq!(*channel_id, chan_1.2);
960 } else { panic!("Needed SendErrorMessage close"); }
962 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
963 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
964 // closing_signed so we do it ourselves
965 check_closed_broadcast!(nodes[0]);
968 assert!(nodes[0].node.list_channels().is_empty());
970 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
971 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
972 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
973 assert!(nodes[1].node.list_channels().is_empty());
974 assert!(nodes[2].node.list_channels().is_empty());
978 fn test_shutdown_rebroadcast() {
979 do_test_shutdown_rebroadcast(0);
980 do_test_shutdown_rebroadcast(1);
981 do_test_shutdown_rebroadcast(2);
985 fn fake_network_test() {
986 // Simple test which builds a network of ChannelManagers, connects them to each other, and
987 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
988 let nodes = create_network(4, &[None, None, None, None]);
990 // Create some initial channels
991 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
992 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
993 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
995 // Rebalance the network a bit by relaying one payment through all the channels...
996 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
997 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
998 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
999 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1001 // Send some more payments
1002 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1003 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1004 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1006 // Test failure packets
1007 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1008 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1010 // Add a new channel that skips 3
1011 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1013 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1014 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1015 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1016 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1017 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1018 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1019 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1021 // Do some rebalance loop payments, simultaneously
1022 let mut hops = Vec::with_capacity(3);
1023 hops.push(RouteHop {
1024 pubkey: nodes[2].node.get_our_node_id(),
1025 short_channel_id: chan_2.0.contents.short_channel_id,
1027 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1029 hops.push(RouteHop {
1030 pubkey: nodes[3].node.get_our_node_id(),
1031 short_channel_id: chan_3.0.contents.short_channel_id,
1033 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1035 hops.push(RouteHop {
1036 pubkey: nodes[1].node.get_our_node_id(),
1037 short_channel_id: chan_4.0.contents.short_channel_id,
1039 cltv_expiry_delta: TEST_FINAL_CLTV,
1041 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;
1042 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;
1043 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1045 let mut hops = Vec::with_capacity(3);
1046 hops.push(RouteHop {
1047 pubkey: nodes[3].node.get_our_node_id(),
1048 short_channel_id: chan_4.0.contents.short_channel_id,
1050 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1052 hops.push(RouteHop {
1053 pubkey: nodes[2].node.get_our_node_id(),
1054 short_channel_id: chan_3.0.contents.short_channel_id,
1056 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1058 hops.push(RouteHop {
1059 pubkey: nodes[1].node.get_our_node_id(),
1060 short_channel_id: chan_2.0.contents.short_channel_id,
1062 cltv_expiry_delta: TEST_FINAL_CLTV,
1064 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;
1065 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;
1066 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1068 // Claim the rebalances...
1069 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1070 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1072 // Add a duplicate new channel from 2 to 4
1073 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1075 // Send some payments across both channels
1076 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1077 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1078 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1080 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1082 //TODO: Test that routes work again here as we've been notified that the channel is full
1084 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1085 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1086 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1088 // Close down the channels...
1089 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1090 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1091 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1092 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1093 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1097 fn holding_cell_htlc_counting() {
1098 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1099 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1100 // commitment dance rounds.
1101 let mut nodes = create_network(3, &[None, None, None]);
1102 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1103 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
1105 let mut payments = Vec::new();
1106 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1107 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1108 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1109 nodes[1].node.send_payment(route, payment_hash).unwrap();
1110 payments.push((payment_preimage, payment_hash));
1112 check_added_monitors!(nodes[1], 1);
1114 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1115 assert_eq!(events.len(), 1);
1116 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1117 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1119 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1120 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1122 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1123 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1124 if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() {
1125 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
1126 } else { panic!("Unexpected event"); }
1128 // This should also be true if we try to forward a payment.
1129 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1130 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1131 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
1132 check_added_monitors!(nodes[0], 1);
1134 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1135 assert_eq!(events.len(), 1);
1136 let payment_event = SendEvent::from_event(events.pop().unwrap());
1137 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1139 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
1140 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1141 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1142 // fails), the second will process the resulting failure and fail the HTLC backward.
1143 expect_pending_htlcs_forwardable!(nodes[1]);
1144 expect_pending_htlcs_forwardable!(nodes[1]);
1145 check_added_monitors!(nodes[1], 1);
1147 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1148 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]).unwrap();
1149 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1151 let events = nodes[0].node.get_and_clear_pending_msg_events();
1152 assert_eq!(events.len(), 1);
1154 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1155 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1157 _ => panic!("Unexpected event"),
1160 let events = nodes[0].node.get_and_clear_pending_events();
1161 assert_eq!(events.len(), 1);
1163 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1164 assert_eq!(payment_hash, payment_hash_2);
1165 assert!(!rejected_by_dest);
1167 _ => panic!("Unexpected event"),
1170 // Now forward all the pending HTLCs and claim them back
1171 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]).unwrap();
1172 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg).unwrap();
1173 check_added_monitors!(nodes[2], 1);
1175 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1176 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1177 check_added_monitors!(nodes[1], 1);
1178 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1180 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1181 check_added_monitors!(nodes[1], 1);
1182 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1184 for ref update in as_updates.update_add_htlcs.iter() {
1185 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update).unwrap();
1187 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed).unwrap();
1188 check_added_monitors!(nodes[2], 1);
1189 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
1190 check_added_monitors!(nodes[2], 1);
1191 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1193 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1194 check_added_monitors!(nodes[1], 1);
1195 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1196 check_added_monitors!(nodes[1], 1);
1197 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1199 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa).unwrap();
1200 check_added_monitors!(nodes[2], 1);
1202 expect_pending_htlcs_forwardable!(nodes[2]);
1204 let events = nodes[2].node.get_and_clear_pending_events();
1205 assert_eq!(events.len(), payments.len());
1206 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1208 &Event::PaymentReceived { ref payment_hash, .. } => {
1209 assert_eq!(*payment_hash, *hash);
1211 _ => panic!("Unexpected event"),
1215 for (preimage, _) in payments.drain(..) {
1216 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1219 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1223 fn duplicate_htlc_test() {
1224 // Test that we accept duplicate payment_hash HTLCs across the network and that
1225 // claiming/failing them are all separate and don't affect each other
1226 let mut nodes = create_network(6, &[None, None, None, None, None, None]);
1228 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1229 create_announced_chan_between_nodes(&nodes, 0, 3, LocalFeatures::new(), LocalFeatures::new());
1230 create_announced_chan_between_nodes(&nodes, 1, 3, LocalFeatures::new(), LocalFeatures::new());
1231 create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
1232 create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
1233 create_announced_chan_between_nodes(&nodes, 3, 5, LocalFeatures::new(), LocalFeatures::new());
1235 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1237 *nodes[0].network_payment_count.borrow_mut() -= 1;
1238 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1240 *nodes[0].network_payment_count.borrow_mut() -= 1;
1241 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1243 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1244 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1245 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1249 fn test_duplicate_htlc_different_direction_onchain() {
1250 // Test that ChannelMonitor doesn't generate 2 preimage txn
1251 // when we have 2 HTLCs with same preimage that go across a node
1252 // in opposite directions.
1253 let nodes = create_network(2, &[None, None]);
1255 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1258 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1260 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1262 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV).unwrap();
1263 send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1265 // Provide preimage to node 0 by claiming payment
1266 nodes[0].node.claim_funds(payment_preimage, 800_000);
1267 check_added_monitors!(nodes[0], 1);
1269 // Broadcast node 1 commitment txn
1270 let remote_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1272 assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1273 let mut has_both_htlcs = 0; // check htlcs match ones committed
1274 for outp in remote_txn[0].output.iter() {
1275 if outp.value == 800_000 / 1000 {
1276 has_both_htlcs += 1;
1277 } else if outp.value == 900_000 / 1000 {
1278 has_both_htlcs += 1;
1281 assert_eq!(has_both_htlcs, 2);
1283 let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1284 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1286 // Check we only broadcast 1 timeout tx
1287 let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1288 let htlc_pair = if claim_txn[0].output[0].value == 800_000 / 1000 { (claim_txn[0].clone(), claim_txn[1].clone()) } else { (claim_txn[1].clone(), claim_txn[0].clone()) };
1289 assert_eq!(claim_txn.len(), 6);
1290 assert_eq!(htlc_pair.0.input.len(), 1);
1291 assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1292 check_spends!(htlc_pair.0, remote_txn[0].clone());
1293 assert_eq!(htlc_pair.1.input.len(), 1);
1294 assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1295 check_spends!(htlc_pair.1, remote_txn[0].clone());
1297 let events = nodes[0].node.get_and_clear_pending_msg_events();
1298 assert_eq!(events.len(), 2);
1301 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1302 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, .. } } => {
1303 assert!(update_add_htlcs.is_empty());
1304 assert!(update_fail_htlcs.is_empty());
1305 assert_eq!(update_fulfill_htlcs.len(), 1);
1306 assert!(update_fail_malformed_htlcs.is_empty());
1307 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1309 _ => panic!("Unexpected event"),
1314 fn do_channel_reserve_test(test_recv: bool) {
1315 use ln::msgs::LightningError;
1317 let mut nodes = create_network(3, &[None, None, None]);
1318 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, LocalFeatures::new(), LocalFeatures::new());
1319 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, LocalFeatures::new(), LocalFeatures::new());
1321 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1322 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1324 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1325 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1327 macro_rules! get_route_and_payment_hash {
1328 ($recv_value: expr) => {{
1329 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1330 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1331 (route, payment_hash, payment_preimage)
1335 macro_rules! expect_forward {
1337 let mut events = $node.node.get_and_clear_pending_msg_events();
1338 assert_eq!(events.len(), 1);
1339 check_added_monitors!($node, 1);
1340 let payment_event = SendEvent::from_event(events.remove(0));
1345 let feemsat = 239; // somehow we know?
1346 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1348 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1350 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1352 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1353 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1354 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
1356 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"),
1357 _ => panic!("Unknown error variants"),
1361 let mut htlc_id = 0;
1362 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1363 // nodes[0]'s wealth
1365 let amt_msat = recv_value_0 + total_fee_msat;
1366 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1369 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1372 let (stat01_, stat11_, stat12_, stat22_) = (
1373 get_channel_value_stat!(nodes[0], chan_1.2),
1374 get_channel_value_stat!(nodes[1], chan_1.2),
1375 get_channel_value_stat!(nodes[1], chan_2.2),
1376 get_channel_value_stat!(nodes[2], chan_2.2),
1379 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1380 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1381 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1382 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1383 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1387 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1388 // attempt to get channel_reserve violation
1389 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1390 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
1392 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1393 _ => panic!("Unknown error variants"),
1397 // adding pending output
1398 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1399 let amt_msat_1 = recv_value_1 + total_fee_msat;
1401 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1402 let payment_event_1 = {
1403 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
1404 check_added_monitors!(nodes[0], 1);
1406 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1407 assert_eq!(events.len(), 1);
1408 SendEvent::from_event(events.remove(0))
1410 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
1412 // channel reserve test with htlc pending output > 0
1413 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1415 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1416 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1417 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1418 _ => panic!("Unknown error variants"),
1423 // test channel_reserve test on nodes[1] side
1424 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1426 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1427 let secp_ctx = Secp256k1::new();
1428 let session_priv = SecretKey::from_slice(&{
1429 let mut session_key = [0; 32];
1430 let mut rng = thread_rng();
1431 rng.fill_bytes(&mut session_key);
1433 }).expect("RNG is bad!");
1435 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1436 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1437 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
1438 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1439 let msg = msgs::UpdateAddHTLC {
1440 channel_id: chan_1.2,
1442 amount_msat: htlc_msat,
1443 payment_hash: our_payment_hash,
1444 cltv_expiry: htlc_cltv,
1445 onion_routing_packet: onion_packet,
1449 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
1451 LightningError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
1453 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1454 assert_eq!(nodes[1].node.list_channels().len(), 1);
1455 assert_eq!(nodes[1].node.list_channels().len(), 1);
1456 check_closed_broadcast!(nodes[1]);
1461 // split the rest to test holding cell
1462 let recv_value_21 = recv_value_2/2;
1463 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1465 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1466 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);
1469 // now see if they go through on both sides
1470 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1471 // but this will stuck in the holding cell
1472 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
1473 check_added_monitors!(nodes[0], 0);
1474 let events = nodes[0].node.get_and_clear_pending_events();
1475 assert_eq!(events.len(), 0);
1477 // test with outbound holding cell amount > 0
1479 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1480 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1481 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over their reserve value"),
1482 _ => panic!("Unknown error variants"),
1486 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1487 // this will also stuck in the holding cell
1488 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
1489 check_added_monitors!(nodes[0], 0);
1490 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1491 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1493 // flush the pending htlc
1494 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
1495 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1496 check_added_monitors!(nodes[1], 1);
1498 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1499 check_added_monitors!(nodes[0], 1);
1500 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1502 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
1503 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1504 // No commitment_signed so get_event_msg's assert(len == 1) passes
1505 check_added_monitors!(nodes[0], 1);
1507 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1508 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1509 check_added_monitors!(nodes[1], 1);
1511 expect_pending_htlcs_forwardable!(nodes[1]);
1513 let ref payment_event_11 = expect_forward!(nodes[1]);
1514 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
1515 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1517 expect_pending_htlcs_forwardable!(nodes[2]);
1518 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1520 // flush the htlcs in the holding cell
1521 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1522 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
1523 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
1524 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1525 expect_pending_htlcs_forwardable!(nodes[1]);
1527 let ref payment_event_3 = expect_forward!(nodes[1]);
1528 assert_eq!(payment_event_3.msgs.len(), 2);
1529 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
1530 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
1532 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1533 expect_pending_htlcs_forwardable!(nodes[2]);
1535 let events = nodes[2].node.get_and_clear_pending_events();
1536 assert_eq!(events.len(), 2);
1538 Event::PaymentReceived { ref payment_hash, amt } => {
1539 assert_eq!(our_payment_hash_21, *payment_hash);
1540 assert_eq!(recv_value_21, amt);
1542 _ => panic!("Unexpected event"),
1545 Event::PaymentReceived { ref payment_hash, amt } => {
1546 assert_eq!(our_payment_hash_22, *payment_hash);
1547 assert_eq!(recv_value_22, amt);
1549 _ => panic!("Unexpected event"),
1552 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1553 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1554 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1556 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);
1557 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1558 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1559 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1561 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1562 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1566 fn channel_reserve_test() {
1567 do_channel_reserve_test(false);
1568 do_channel_reserve_test(true);
1572 fn channel_reserve_in_flight_removes() {
1573 // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1574 // can send to its counterparty, but due to update ordering, the other side may not yet have
1575 // considered those HTLCs fully removed.
1576 // This tests that we don't count HTLCs which will not be included in the next remote
1577 // commitment transaction towards the reserve value (as it implies no commitment transaction
1578 // will be generated which violates the remote reserve value).
1579 // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1581 // * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1582 // you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1583 // you only consider the value of the first HTLC, it may not),
1584 // * start routing a third HTLC from A to B,
1585 // * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1586 // the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1587 // * deliver the first fulfill from B
1588 // * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1590 // * deliver A's response CS and RAA.
1591 // This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1592 // removed it fully. B now has the push_msat plus the first two HTLCs in value.
1593 // * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1594 // of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1595 let mut nodes = create_network(2, &[None, None]);
1596 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1598 let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1599 // Route the first two HTLCs.
1600 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1601 let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1603 // Start routing the third HTLC (this is just used to get everyone in the right state).
1604 let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1606 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
1607 nodes[0].node.send_payment(route, payment_hash_3).unwrap();
1608 check_added_monitors!(nodes[0], 1);
1609 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1610 assert_eq!(events.len(), 1);
1611 SendEvent::from_event(events.remove(0))
1614 // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1615 // initial fulfill/CS.
1616 assert!(nodes[1].node.claim_funds(payment_preimage_1, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1617 check_added_monitors!(nodes[1], 1);
1618 let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1620 // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1621 // remove the second HTLC when we send the HTLC back from B to A.
1622 assert!(nodes[1].node.claim_funds(payment_preimage_2, 20000));
1623 check_added_monitors!(nodes[1], 1);
1624 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1626 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]).unwrap();
1627 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed).unwrap();
1628 check_added_monitors!(nodes[0], 1);
1629 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1630 expect_payment_sent!(nodes[0], payment_preimage_1);
1632 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]).unwrap();
1633 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg).unwrap();
1634 check_added_monitors!(nodes[1], 1);
1635 // B is already AwaitingRAA, so cant generate a CS here
1636 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1638 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1639 check_added_monitors!(nodes[1], 1);
1640 let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1642 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1643 check_added_monitors!(nodes[0], 1);
1644 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1646 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1647 check_added_monitors!(nodes[1], 1);
1648 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1650 // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1651 // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1652 // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1653 // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1654 // on-chain as necessary).
1655 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]).unwrap();
1656 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed).unwrap();
1657 check_added_monitors!(nodes[0], 1);
1658 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1659 expect_payment_sent!(nodes[0], payment_preimage_2);
1661 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1662 check_added_monitors!(nodes[1], 1);
1663 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1665 expect_pending_htlcs_forwardable!(nodes[1]);
1666 expect_payment_received!(nodes[1], payment_hash_3, 100000);
1668 // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1669 // resolve the second HTLC from A's point of view.
1670 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1671 check_added_monitors!(nodes[0], 1);
1672 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1674 // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1675 // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1676 let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1678 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV).unwrap();
1679 nodes[1].node.send_payment(route, payment_hash_4).unwrap();
1680 check_added_monitors!(nodes[1], 1);
1681 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1682 assert_eq!(events.len(), 1);
1683 SendEvent::from_event(events.remove(0))
1686 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]).unwrap();
1687 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg).unwrap();
1688 check_added_monitors!(nodes[0], 1);
1689 let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1691 // Now just resolve all the outstanding messages/HTLCs for completeness...
1693 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1694 check_added_monitors!(nodes[1], 1);
1695 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1697 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa).unwrap();
1698 check_added_monitors!(nodes[1], 1);
1700 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1701 check_added_monitors!(nodes[0], 1);
1702 let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1704 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed).unwrap();
1705 check_added_monitors!(nodes[1], 1);
1706 let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1708 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa).unwrap();
1709 check_added_monitors!(nodes[0], 1);
1711 expect_pending_htlcs_forwardable!(nodes[0]);
1712 expect_payment_received!(nodes[0], payment_hash_4, 10000);
1714 claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1715 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1719 fn channel_monitor_network_test() {
1720 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1721 // tests that ChannelMonitor is able to recover from various states.
1722 let nodes = create_network(5, &[None, None, None, None, None]);
1724 // Create some initial channels
1725 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1726 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
1727 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
1728 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
1730 // Rebalance the network a bit by relaying one payment through all the channels...
1731 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1732 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1733 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1734 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1736 // Simple case with no pending HTLCs:
1737 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1739 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1740 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1741 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1742 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1744 get_announce_close_broadcast_events(&nodes, 0, 1);
1745 assert_eq!(nodes[0].node.list_channels().len(), 0);
1746 assert_eq!(nodes[1].node.list_channels().len(), 1);
1748 // One pending HTLC is discarded by the force-close:
1749 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1751 // Simple case of one pending HTLC to HTLC-Timeout
1752 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1754 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1755 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1756 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1757 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1759 get_announce_close_broadcast_events(&nodes, 1, 2);
1760 assert_eq!(nodes[1].node.list_channels().len(), 0);
1761 assert_eq!(nodes[2].node.list_channels().len(), 1);
1763 macro_rules! claim_funds {
1764 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1766 assert!($node.node.claim_funds($preimage, $amount));
1767 check_added_monitors!($node, 1);
1769 let events = $node.node.get_and_clear_pending_msg_events();
1770 assert_eq!(events.len(), 1);
1772 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1773 assert!(update_add_htlcs.is_empty());
1774 assert!(update_fail_htlcs.is_empty());
1775 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
1777 _ => panic!("Unexpected event"),
1783 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
1784 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
1785 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
1787 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
1789 // Claim the payment on nodes[3], giving it knowledge of the preimage
1790 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
1792 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1793 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
1795 check_preimage_claim(&nodes[3], &node_txn);
1797 get_announce_close_broadcast_events(&nodes, 2, 3);
1798 assert_eq!(nodes[2].node.list_channels().len(), 0);
1799 assert_eq!(nodes[3].node.list_channels().len(), 1);
1801 { // Cheat and reset nodes[4]'s height to 1
1802 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1803 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
1806 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
1807 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
1808 // One pending HTLC to time out:
1809 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
1810 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
1814 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1815 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1816 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
1817 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1818 nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1821 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
1823 // Claim the payment on nodes[4], giving it knowledge of the preimage
1824 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
1826 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1828 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1829 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
1830 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1831 nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1834 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
1836 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1837 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
1839 check_preimage_claim(&nodes[4], &node_txn);
1841 get_announce_close_broadcast_events(&nodes, 3, 4);
1842 assert_eq!(nodes[3].node.list_channels().len(), 0);
1843 assert_eq!(nodes[4].node.list_channels().len(), 0);
1847 fn test_justice_tx() {
1848 // Test justice txn built on revoked HTLC-Success tx, against both sides
1849 let mut alice_config = UserConfig::default();
1850 alice_config.channel_options.announced_channel = true;
1851 alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
1852 alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
1853 let mut bob_config = UserConfig::default();
1854 bob_config.channel_options.announced_channel = true;
1855 bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
1856 bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
1857 let cfgs = [Some(alice_config), Some(bob_config)];
1858 let nodes = create_network(2, &cfgs);
1859 // Create some new channels:
1860 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1862 // A pending HTLC which will be revoked:
1863 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1864 // Get the will-be-revoked local txn from nodes[0]
1865 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1866 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
1867 assert_eq!(revoked_local_txn[0].input.len(), 1);
1868 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
1869 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
1870 assert_eq!(revoked_local_txn[1].input.len(), 1);
1871 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1872 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1873 // Revoke the old state
1874 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
1877 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1878 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1880 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1881 assert_eq!(node_txn.len(), 3);
1882 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1883 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
1885 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1886 node_txn.swap_remove(0);
1887 node_txn.truncate(1);
1889 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
1891 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1892 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
1893 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1894 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1895 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
1897 get_announce_close_broadcast_events(&nodes, 0, 1);
1899 assert_eq!(nodes[0].node.list_channels().len(), 0);
1900 assert_eq!(nodes[1].node.list_channels().len(), 0);
1902 // We test justice_tx build by A on B's revoked HTLC-Success tx
1903 // Create some new channels:
1904 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1906 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1910 // A pending HTLC which will be revoked:
1911 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1912 // Get the will-be-revoked local txn from B
1913 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1914 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
1915 assert_eq!(revoked_local_txn[0].input.len(), 1);
1916 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
1917 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
1918 // Revoke the old state
1919 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
1921 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1922 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1924 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
1925 assert_eq!(node_txn.len(), 3);
1926 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1927 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
1929 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1930 node_txn.swap_remove(0);
1932 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
1934 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1935 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
1936 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1937 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1938 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
1940 get_announce_close_broadcast_events(&nodes, 0, 1);
1941 assert_eq!(nodes[0].node.list_channels().len(), 0);
1942 assert_eq!(nodes[1].node.list_channels().len(), 0);
1946 fn revoked_output_claim() {
1947 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
1948 // transaction is broadcast by its counterparty
1949 let nodes = create_network(2, &[None, None]);
1950 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1951 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
1952 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1953 assert_eq!(revoked_local_txn.len(), 1);
1954 // Only output is the full channel value back to nodes[0]:
1955 assert_eq!(revoked_local_txn[0].output.len(), 1);
1956 // Send a payment through, updating everyone's latest commitment txn
1957 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
1959 // Inform nodes[1] that nodes[0] broadcast a stale tx
1960 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1961 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1962 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1963 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
1965 assert_eq!(node_txn[0], node_txn[2]);
1967 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1968 check_spends!(node_txn[1], chan_1.3.clone());
1970 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
1971 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1972 get_announce_close_broadcast_events(&nodes, 0, 1);
1976 fn claim_htlc_outputs_shared_tx() {
1977 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
1978 let nodes = create_network(2, &[None, None]);
1980 // Create some new channel:
1981 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
1983 // Rebalance the network to generate htlc in the two directions
1984 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1985 // 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
1986 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1987 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
1989 // Get the will-be-revoked local txn from node[0]
1990 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1991 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
1992 assert_eq!(revoked_local_txn[0].input.len(), 1);
1993 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
1994 assert_eq!(revoked_local_txn[1].input.len(), 1);
1995 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1996 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1997 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
1999 //Revoke the old state
2000 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2003 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2004 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2005 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2006 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2008 let events = nodes[1].node.get_and_clear_pending_events();
2009 assert_eq!(events.len(), 1);
2011 Event::PaymentFailed { payment_hash, .. } => {
2012 assert_eq!(payment_hash, payment_hash_2);
2014 _ => panic!("Unexpected event"),
2017 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2018 assert_eq!(node_txn.len(), 4);
2020 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2021 check_spends!(node_txn[0], revoked_local_txn[0].clone());
2023 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
2025 let mut witness_lens = BTreeSet::new();
2026 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2027 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2028 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2029 assert_eq!(witness_lens.len(), 3);
2030 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2031 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2032 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2034 // Next nodes[1] broadcasts its current local tx state:
2035 assert_eq!(node_txn[1].input.len(), 1);
2036 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2038 assert_eq!(node_txn[2].input.len(), 1);
2039 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2040 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2041 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2042 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2043 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2045 get_announce_close_broadcast_events(&nodes, 0, 1);
2046 assert_eq!(nodes[0].node.list_channels().len(), 0);
2047 assert_eq!(nodes[1].node.list_channels().len(), 0);
2051 fn claim_htlc_outputs_single_tx() {
2052 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2053 let nodes = create_network(2, &[None, None]);
2055 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2057 // Rebalance the network to generate htlc in the two directions
2058 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2059 // 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
2060 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2061 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2062 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2064 // Get the will-be-revoked local txn from node[0]
2065 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2067 //Revoke the old state
2068 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2071 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2072 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2073 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2074 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2076 let events = nodes[1].node.get_and_clear_pending_events();
2077 assert_eq!(events.len(), 1);
2079 Event::PaymentFailed { payment_hash, .. } => {
2080 assert_eq!(payment_hash, payment_hash_2);
2082 _ => panic!("Unexpected event"),
2085 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2086 assert_eq!(node_txn.len(), 29); // 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)
2088 assert_eq!(node_txn[0], node_txn[7]);
2089 assert_eq!(node_txn[1], node_txn[8]);
2090 assert_eq!(node_txn[2], node_txn[9]);
2091 assert_eq!(node_txn[3], node_txn[10]);
2092 assert_eq!(node_txn[4], node_txn[11]);
2093 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcasted by ChannelManger
2094 assert_eq!(node_txn[4], node_txn[6]);
2096 assert_eq!(node_txn[0].input.len(), 1);
2097 assert_eq!(node_txn[1].input.len(), 1);
2098 assert_eq!(node_txn[2].input.len(), 1);
2100 fn get_txout(out_point: &BitcoinOutPoint, tx: &Transaction) -> Option<TxOut> {
2101 if out_point.txid == tx.txid() {
2102 tx.output.get(out_point.vout as usize).cloned()
2107 node_txn[0].verify(|out|get_txout(out, &revoked_local_txn[0])).unwrap();
2108 node_txn[1].verify(|out|get_txout(out, &revoked_local_txn[0])).unwrap();
2109 node_txn[2].verify(|out|get_txout(out, &revoked_local_txn[0])).unwrap();
2111 let mut witness_lens = BTreeSet::new();
2112 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2113 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2114 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
2115 assert_eq!(witness_lens.len(), 3);
2116 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2117 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2118 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2120 assert_eq!(node_txn[3].input.len(), 1);
2121 check_spends!(node_txn[3], chan_1.3.clone());
2123 assert_eq!(node_txn[4].input.len(), 1);
2124 let witness_script = node_txn[4].input[0].witness.last().unwrap();
2125 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2126 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
2127 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2128 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
2130 get_announce_close_broadcast_events(&nodes, 0, 1);
2131 assert_eq!(nodes[0].node.list_channels().len(), 0);
2132 assert_eq!(nodes[1].node.list_channels().len(), 0);
2136 fn test_htlc_on_chain_success() {
2137 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2138 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2139 // broadcasting the right event to other nodes in payment path.
2140 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2141 // A --------------------> B ----------------------> C (preimage)
2142 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2143 // commitment transaction was broadcast.
2144 // Then, B should learn the preimage from said transactions, attempting to claim backwards
2146 // B should be able to claim via preimage if A then broadcasts its local tx.
2147 // Finally, when A sees B's latest local commitment transaction it should be able to claim
2148 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2149 // PaymentSent event).
2151 let nodes = create_network(3, &[None, None, None]);
2153 // Create some initial channels
2154 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2155 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2157 // Rebalance the network a bit by relaying one payment through all the channels...
2158 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2159 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2161 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2162 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2163 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2165 // Broadcast legit commitment tx from C on B's chain
2166 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2167 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2168 assert_eq!(commitment_tx.len(), 1);
2169 check_spends!(commitment_tx[0], chan_2.3.clone());
2170 nodes[2].node.claim_funds(our_payment_preimage, 3_000_000);
2171 nodes[2].node.claim_funds(our_payment_preimage_2, 3_000_000);
2172 check_added_monitors!(nodes[2], 2);
2173 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2174 assert!(updates.update_add_htlcs.is_empty());
2175 assert!(updates.update_fail_htlcs.is_empty());
2176 assert!(updates.update_fail_malformed_htlcs.is_empty());
2177 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2179 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2180 check_closed_broadcast!(nodes[2]);
2181 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
2182 assert_eq!(node_txn.len(), 5);
2183 assert_eq!(node_txn[0], node_txn[3]);
2184 assert_eq!(node_txn[1], node_txn[4]);
2185 assert_eq!(node_txn[2], commitment_tx[0]);
2186 check_spends!(node_txn[0], commitment_tx[0].clone());
2187 check_spends!(node_txn[1], commitment_tx[0].clone());
2188 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2189 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2190 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2191 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2192 assert_eq!(node_txn[0].lock_time, 0);
2193 assert_eq!(node_txn[1].lock_time, 0);
2195 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2196 nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2197 let events = nodes[1].node.get_and_clear_pending_msg_events();
2199 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2200 assert_eq!(added_monitors.len(), 2);
2201 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2202 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2203 added_monitors.clear();
2205 assert_eq!(events.len(), 2);
2207 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2208 _ => panic!("Unexpected event"),
2211 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, .. } } => {
2212 assert!(update_add_htlcs.is_empty());
2213 assert!(update_fail_htlcs.is_empty());
2214 assert_eq!(update_fulfill_htlcs.len(), 1);
2215 assert!(update_fail_malformed_htlcs.is_empty());
2216 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2218 _ => panic!("Unexpected event"),
2220 macro_rules! check_tx_local_broadcast {
2221 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2222 // ChannelManager : 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 (block-rescan)
2223 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2224 assert_eq!(node_txn.len(), 7);
2225 assert_eq!(node_txn[0], node_txn[5]);
2226 assert_eq!(node_txn[1], node_txn[6]);
2227 check_spends!(node_txn[0], $commitment_tx.clone());
2228 check_spends!(node_txn[1], $commitment_tx.clone());
2229 assert_ne!(node_txn[0].lock_time, 0);
2230 assert_ne!(node_txn[1].lock_time, 0);
2232 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2233 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2234 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2235 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2237 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2238 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2239 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2240 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2242 check_spends!(node_txn[2], $chan_tx.clone());
2243 check_spends!(node_txn[3], node_txn[2].clone());
2244 check_spends!(node_txn[4], node_txn[2].clone());
2245 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2246 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2247 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2248 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2249 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2250 assert_ne!(node_txn[3].lock_time, 0);
2251 assert_ne!(node_txn[4].lock_time, 0);
2255 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2256 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2257 // timeout-claim of the output that nodes[2] just claimed via success.
2258 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2260 // Broadcast legit commitment tx from A on B's chain
2261 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
2262 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2263 check_spends!(commitment_tx[0], chan_1.3.clone());
2264 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2265 check_closed_broadcast!(nodes[1]);
2266 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
2267 assert_eq!(node_txn.len(), 3);
2268 assert_eq!(node_txn[0], node_txn[2]);
2269 check_spends!(node_txn[0], commitment_tx[0].clone());
2270 assert_eq!(node_txn[0].input.len(), 2);
2271 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2272 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2273 assert_eq!(node_txn[0].lock_time, 0);
2274 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2275 check_spends!(node_txn[1], chan_1.3.clone());
2276 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2277 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2278 // we already checked the same situation with A.
2280 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2281 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2282 check_closed_broadcast!(nodes[0]);
2283 let events = nodes[0].node.get_and_clear_pending_events();
2284 assert_eq!(events.len(), 2);
2285 let mut first_claimed = false;
2286 for event in events {
2288 Event::PaymentSent { payment_preimage } => {
2289 if payment_preimage == our_payment_preimage {
2290 assert!(!first_claimed);
2291 first_claimed = true;
2293 assert_eq!(payment_preimage, our_payment_preimage_2);
2296 _ => panic!("Unexpected event"),
2299 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2303 fn test_htlc_on_chain_timeout() {
2304 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2305 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2306 // broadcasting the right event to other nodes in payment path.
2307 // A ------------------> B ----------------------> C (timeout)
2308 // B's commitment tx C's commitment tx
2310 // B's HTLC timeout tx B's timeout tx
2312 let nodes = create_network(3, &[None, None, None]);
2314 // Create some intial channels
2315 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2316 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2318 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2319 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2320 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2322 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2323 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2325 // Broadcast legit commitment tx from C on B's chain
2326 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2327 check_spends!(commitment_tx[0], chan_2.3.clone());
2328 nodes[2].node.fail_htlc_backwards(&payment_hash);
2329 check_added_monitors!(nodes[2], 0);
2330 expect_pending_htlcs_forwardable!(nodes[2]);
2331 check_added_monitors!(nodes[2], 1);
2333 let events = nodes[2].node.get_and_clear_pending_msg_events();
2334 assert_eq!(events.len(), 1);
2336 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, .. } } => {
2337 assert!(update_add_htlcs.is_empty());
2338 assert!(!update_fail_htlcs.is_empty());
2339 assert!(update_fulfill_htlcs.is_empty());
2340 assert!(update_fail_malformed_htlcs.is_empty());
2341 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2343 _ => panic!("Unexpected event"),
2345 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2346 check_closed_broadcast!(nodes[2]);
2347 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2348 assert_eq!(node_txn.len(), 1);
2349 check_spends!(node_txn[0], chan_2.3.clone());
2350 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2352 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2353 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2354 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2357 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2358 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)
2359 assert_eq!(node_txn[0], node_txn[5]);
2360 assert_eq!(node_txn[1], node_txn[6]);
2361 assert_eq!(node_txn[2], node_txn[7]);
2362 check_spends!(node_txn[0], commitment_tx[0].clone());
2363 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2364 check_spends!(node_txn[1], chan_2.3.clone());
2365 check_spends!(node_txn[2], node_txn[1].clone());
2366 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2367 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2368 check_spends!(node_txn[3], chan_2.3.clone());
2369 check_spends!(node_txn[4], node_txn[3].clone());
2370 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2371 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2372 timeout_tx = node_txn[0].clone();
2376 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2377 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2378 check_added_monitors!(nodes[1], 0);
2379 check_closed_broadcast!(nodes[1]);
2381 expect_pending_htlcs_forwardable!(nodes[1]);
2382 check_added_monitors!(nodes[1], 1);
2383 let events = nodes[1].node.get_and_clear_pending_msg_events();
2384 assert_eq!(events.len(), 1);
2386 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, .. } } => {
2387 assert!(update_add_htlcs.is_empty());
2388 assert!(!update_fail_htlcs.is_empty());
2389 assert!(update_fulfill_htlcs.is_empty());
2390 assert!(update_fail_malformed_htlcs.is_empty());
2391 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2393 _ => panic!("Unexpected event"),
2395 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
2396 assert_eq!(node_txn.len(), 0);
2398 // Broadcast legit commitment tx from B on A's chain
2399 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2400 check_spends!(commitment_tx[0], chan_1.3.clone());
2402 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2403 check_closed_broadcast!(nodes[0]);
2404 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
2405 assert_eq!(node_txn.len(), 4);
2406 assert_eq!(node_txn[0], node_txn[3]);
2407 check_spends!(node_txn[0], commitment_tx[0].clone());
2408 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2409 check_spends!(node_txn[1], chan_1.3.clone());
2410 check_spends!(node_txn[2], node_txn[1].clone());
2411 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2412 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2416 fn test_simple_commitment_revoked_fail_backward() {
2417 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2418 // and fail backward accordingly.
2420 let nodes = create_network(3, &[None, None, None]);
2422 // Create some initial channels
2423 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2424 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2426 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2427 // Get the will-be-revoked local txn from nodes[2]
2428 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2429 // Revoke the old state
2430 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2432 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2434 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2435 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2436 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2437 check_added_monitors!(nodes[1], 0);
2438 check_closed_broadcast!(nodes[1]);
2440 expect_pending_htlcs_forwardable!(nodes[1]);
2441 check_added_monitors!(nodes[1], 1);
2442 let events = nodes[1].node.get_and_clear_pending_msg_events();
2443 assert_eq!(events.len(), 1);
2445 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, .. } } => {
2446 assert!(update_add_htlcs.is_empty());
2447 assert_eq!(update_fail_htlcs.len(), 1);
2448 assert!(update_fulfill_htlcs.is_empty());
2449 assert!(update_fail_malformed_htlcs.is_empty());
2450 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2452 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2453 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2455 let events = nodes[0].node.get_and_clear_pending_msg_events();
2456 assert_eq!(events.len(), 1);
2458 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2459 _ => panic!("Unexpected event"),
2461 let events = nodes[0].node.get_and_clear_pending_events();
2462 assert_eq!(events.len(), 1);
2464 Event::PaymentFailed { .. } => {},
2465 _ => panic!("Unexpected event"),
2468 _ => panic!("Unexpected event"),
2472 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2473 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2474 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2475 // commitment transaction anymore.
2476 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2477 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2478 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2479 // technically disallowed and we should probably handle it reasonably.
2480 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2481 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2483 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2484 // commitment_signed (implying it will be in the latest remote commitment transaction).
2485 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2486 // and once they revoke the previous commitment transaction (allowing us to send a new
2487 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2488 let mut nodes = create_network(3, &[None, None, None]);
2490 // Create some initial channels
2491 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2492 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2494 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2495 // Get the will-be-revoked local txn from nodes[2]
2496 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2497 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2498 // Revoke the old state
2499 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2501 let value = if use_dust {
2502 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2503 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2504 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2507 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2508 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2509 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2511 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2512 expect_pending_htlcs_forwardable!(nodes[2]);
2513 check_added_monitors!(nodes[2], 1);
2514 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2515 assert!(updates.update_add_htlcs.is_empty());
2516 assert!(updates.update_fulfill_htlcs.is_empty());
2517 assert!(updates.update_fail_malformed_htlcs.is_empty());
2518 assert_eq!(updates.update_fail_htlcs.len(), 1);
2519 assert!(updates.update_fee.is_none());
2520 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2521 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2522 // Drop the last RAA from 3 -> 2
2524 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2525 expect_pending_htlcs_forwardable!(nodes[2]);
2526 check_added_monitors!(nodes[2], 1);
2527 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2528 assert!(updates.update_add_htlcs.is_empty());
2529 assert!(updates.update_fulfill_htlcs.is_empty());
2530 assert!(updates.update_fail_malformed_htlcs.is_empty());
2531 assert_eq!(updates.update_fail_htlcs.len(), 1);
2532 assert!(updates.update_fee.is_none());
2533 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2534 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2535 check_added_monitors!(nodes[1], 1);
2536 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2537 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2538 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2539 check_added_monitors!(nodes[2], 1);
2541 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2542 expect_pending_htlcs_forwardable!(nodes[2]);
2543 check_added_monitors!(nodes[2], 1);
2544 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2545 assert!(updates.update_add_htlcs.is_empty());
2546 assert!(updates.update_fulfill_htlcs.is_empty());
2547 assert!(updates.update_fail_malformed_htlcs.is_empty());
2548 assert_eq!(updates.update_fail_htlcs.len(), 1);
2549 assert!(updates.update_fee.is_none());
2550 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2551 // At this point first_payment_hash has dropped out of the latest two commitment
2552 // transactions that nodes[1] is tracking...
2553 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2554 check_added_monitors!(nodes[1], 1);
2555 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2556 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2557 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2558 check_added_monitors!(nodes[2], 1);
2560 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2561 // on nodes[2]'s RAA.
2562 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2563 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2564 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
2565 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2566 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2567 check_added_monitors!(nodes[1], 0);
2570 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
2571 // One monitor for the new revocation preimage, no second on as we won't generate a new
2572 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2573 check_added_monitors!(nodes[1], 1);
2574 let events = nodes[1].node.get_and_clear_pending_events();
2575 assert_eq!(events.len(), 1);
2577 Event::PendingHTLCsForwardable { .. } => { },
2578 _ => panic!("Unexpected event"),
2580 // Deliberately don't process the pending fail-back so they all fail back at once after
2581 // block connection just like the !deliver_bs_raa case
2584 let mut failed_htlcs = HashSet::new();
2585 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2587 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2588 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2589 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2591 let events = nodes[1].node.get_and_clear_pending_events();
2592 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2594 Event::PaymentFailed { ref payment_hash, .. } => {
2595 assert_eq!(*payment_hash, fourth_payment_hash);
2597 _ => panic!("Unexpected event"),
2599 if !deliver_bs_raa {
2601 Event::PendingHTLCsForwardable { .. } => { },
2602 _ => panic!("Unexpected event"),
2605 nodes[1].node.process_pending_htlc_forwards();
2606 check_added_monitors!(nodes[1], 1);
2608 let events = nodes[1].node.get_and_clear_pending_msg_events();
2609 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2610 match events[if deliver_bs_raa { 1 } else { 0 }] {
2611 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2612 _ => panic!("Unexpected event"),
2616 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, .. } } => {
2617 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2618 assert_eq!(update_add_htlcs.len(), 1);
2619 assert!(update_fulfill_htlcs.is_empty());
2620 assert!(update_fail_htlcs.is_empty());
2621 assert!(update_fail_malformed_htlcs.is_empty());
2623 _ => panic!("Unexpected event"),
2626 match events[if deliver_bs_raa { 2 } else { 1 }] {
2627 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, .. } } => {
2628 assert!(update_add_htlcs.is_empty());
2629 assert_eq!(update_fail_htlcs.len(), 3);
2630 assert!(update_fulfill_htlcs.is_empty());
2631 assert!(update_fail_malformed_htlcs.is_empty());
2632 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2634 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2635 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]).unwrap();
2636 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]).unwrap();
2638 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2640 let events = nodes[0].node.get_and_clear_pending_msg_events();
2641 // If we delivered B's RAA we got an unknown preimage error, not something
2642 // that we should update our routing table for.
2643 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2644 for event in events {
2646 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2647 _ => panic!("Unexpected event"),
2650 let events = nodes[0].node.get_and_clear_pending_events();
2651 assert_eq!(events.len(), 3);
2653 Event::PaymentFailed { ref payment_hash, .. } => {
2654 assert!(failed_htlcs.insert(payment_hash.0));
2656 _ => panic!("Unexpected event"),
2659 Event::PaymentFailed { ref payment_hash, .. } => {
2660 assert!(failed_htlcs.insert(payment_hash.0));
2662 _ => panic!("Unexpected event"),
2665 Event::PaymentFailed { ref payment_hash, .. } => {
2666 assert!(failed_htlcs.insert(payment_hash.0));
2668 _ => panic!("Unexpected event"),
2671 _ => panic!("Unexpected event"),
2674 assert!(failed_htlcs.contains(&first_payment_hash.0));
2675 assert!(failed_htlcs.contains(&second_payment_hash.0));
2676 assert!(failed_htlcs.contains(&third_payment_hash.0));
2680 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2681 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2682 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2683 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2684 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2688 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2689 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2690 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2691 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2692 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2696 fn test_htlc_ignore_latest_remote_commitment() {
2697 // Test that HTLC transactions spending the latest remote commitment transaction are simply
2698 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2699 let nodes = create_network(2, &[None, None]);
2700 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2702 route_payment(&nodes[0], &[&nodes[1]], 10000000);
2703 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
2704 check_closed_broadcast!(nodes[0]);
2706 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2707 assert_eq!(node_txn.len(), 2);
2709 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2710 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
2711 check_closed_broadcast!(nodes[1]);
2713 // Duplicate the block_connected call since this may happen due to other listeners
2714 // registering new transactions
2715 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
2719 fn test_force_close_fail_back() {
2720 // Check which HTLCs are failed-backwards on channel force-closure
2721 let mut nodes = create_network(3, &[None, None, None]);
2722 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2723 create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2725 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
2727 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2729 let mut payment_event = {
2730 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
2731 check_added_monitors!(nodes[0], 1);
2733 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2734 assert_eq!(events.len(), 1);
2735 SendEvent::from_event(events.remove(0))
2738 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2739 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2741 expect_pending_htlcs_forwardable!(nodes[1]);
2743 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
2744 assert_eq!(events_2.len(), 1);
2745 payment_event = SendEvent::from_event(events_2.remove(0));
2746 assert_eq!(payment_event.msgs.len(), 1);
2748 check_added_monitors!(nodes[1], 1);
2749 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2750 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2751 check_added_monitors!(nodes[2], 1);
2752 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2754 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
2755 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
2756 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
2758 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
2759 check_closed_broadcast!(nodes[2]);
2761 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2762 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
2763 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
2764 // back to nodes[1] upon timeout otherwise.
2765 assert_eq!(node_txn.len(), 1);
2769 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2770 nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
2772 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
2773 check_closed_broadcast!(nodes[1]);
2775 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
2777 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
2778 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
2779 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
2781 nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
2782 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2783 assert_eq!(node_txn.len(), 1);
2784 assert_eq!(node_txn[0].input.len(), 1);
2785 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
2786 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
2787 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
2789 check_spends!(node_txn[0], tx);
2793 fn test_unconf_chan() {
2794 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
2795 let nodes = create_network(2, &[None, None]);
2796 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2798 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2799 assert_eq!(channel_state.by_id.len(), 1);
2800 assert_eq!(channel_state.short_to_id.len(), 1);
2801 mem::drop(channel_state);
2803 let mut headers = Vec::new();
2804 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2805 headers.push(header.clone());
2807 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2808 headers.push(header.clone());
2810 let mut height = 99;
2811 while !headers.is_empty() {
2812 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
2815 check_closed_broadcast!(nodes[0]);
2816 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2817 assert_eq!(channel_state.by_id.len(), 0);
2818 assert_eq!(channel_state.short_to_id.len(), 0);
2822 fn test_simple_peer_disconnect() {
2823 // Test that we can reconnect when there are no lost messages
2824 let nodes = create_network(3, &[None, None, None]);
2825 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2826 create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
2828 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2829 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2830 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2832 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2833 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2834 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
2835 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
2837 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2838 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2839 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2841 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2842 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2843 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2844 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2846 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2847 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2849 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
2850 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
2852 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
2854 let events = nodes[0].node.get_and_clear_pending_events();
2855 assert_eq!(events.len(), 2);
2857 Event::PaymentSent { payment_preimage } => {
2858 assert_eq!(payment_preimage, payment_preimage_3);
2860 _ => panic!("Unexpected event"),
2863 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
2864 assert_eq!(payment_hash, payment_hash_5);
2865 assert!(rejected_by_dest);
2867 _ => panic!("Unexpected event"),
2871 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
2872 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
2875 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
2876 // Test that we can reconnect when in-flight HTLC updates get dropped
2877 let mut nodes = create_network(2, &[None, None]);
2878 if messages_delivered == 0 {
2879 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
2880 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
2882 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
2885 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();
2886 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
2888 let payment_event = {
2889 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
2890 check_added_monitors!(nodes[0], 1);
2892 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2893 assert_eq!(events.len(), 1);
2894 SendEvent::from_event(events.remove(0))
2896 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
2898 if messages_delivered < 2 {
2899 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
2901 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2902 if messages_delivered >= 3 {
2903 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2904 check_added_monitors!(nodes[1], 1);
2905 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2907 if messages_delivered >= 4 {
2908 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2909 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2910 check_added_monitors!(nodes[0], 1);
2912 if messages_delivered >= 5 {
2913 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
2914 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2915 // No commitment_signed so get_event_msg's assert(len == 1) passes
2916 check_added_monitors!(nodes[0], 1);
2918 if messages_delivered >= 6 {
2919 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2920 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2921 check_added_monitors!(nodes[1], 1);
2928 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2929 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2930 if messages_delivered < 3 {
2931 // Even if the funding_locked messages get exchanged, as long as nothing further was
2932 // received on either side, both sides will need to resend them.
2933 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
2934 } else if messages_delivered == 3 {
2935 // nodes[0] still wants its RAA + commitment_signed
2936 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
2937 } else if messages_delivered == 4 {
2938 // nodes[0] still wants its commitment_signed
2939 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
2940 } else if messages_delivered == 5 {
2941 // nodes[1] still wants its final RAA
2942 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
2943 } else if messages_delivered == 6 {
2944 // Everything was delivered...
2945 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2948 let events_1 = nodes[1].node.get_and_clear_pending_events();
2949 assert_eq!(events_1.len(), 1);
2951 Event::PendingHTLCsForwardable { .. } => { },
2952 _ => panic!("Unexpected event"),
2955 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2956 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2957 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2959 nodes[1].node.process_pending_htlc_forwards();
2961 let events_2 = nodes[1].node.get_and_clear_pending_events();
2962 assert_eq!(events_2.len(), 1);
2964 Event::PaymentReceived { ref payment_hash, amt } => {
2965 assert_eq!(payment_hash_1, *payment_hash);
2966 assert_eq!(amt, 1000000);
2968 _ => panic!("Unexpected event"),
2971 nodes[1].node.claim_funds(payment_preimage_1, 1_000_000);
2972 check_added_monitors!(nodes[1], 1);
2974 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
2975 assert_eq!(events_3.len(), 1);
2976 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
2977 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2978 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2979 assert!(updates.update_add_htlcs.is_empty());
2980 assert!(updates.update_fail_htlcs.is_empty());
2981 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2982 assert!(updates.update_fail_malformed_htlcs.is_empty());
2983 assert!(updates.update_fee.is_none());
2984 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
2986 _ => panic!("Unexpected event"),
2989 if messages_delivered >= 1 {
2990 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
2992 let events_4 = nodes[0].node.get_and_clear_pending_events();
2993 assert_eq!(events_4.len(), 1);
2995 Event::PaymentSent { ref payment_preimage } => {
2996 assert_eq!(payment_preimage_1, *payment_preimage);
2998 _ => panic!("Unexpected event"),
3001 if messages_delivered >= 2 {
3002 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
3003 check_added_monitors!(nodes[0], 1);
3004 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3006 if messages_delivered >= 3 {
3007 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3008 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3009 check_added_monitors!(nodes[1], 1);
3011 if messages_delivered >= 4 {
3012 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
3013 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3014 // No commitment_signed so get_event_msg's assert(len == 1) passes
3015 check_added_monitors!(nodes[1], 1);
3017 if messages_delivered >= 5 {
3018 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3019 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3020 check_added_monitors!(nodes[0], 1);
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);
3029 if messages_delivered < 2 {
3030 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3031 //TODO: Deduplicate PaymentSent events, then enable this if:
3032 //if messages_delivered < 1 {
3033 let events_4 = nodes[0].node.get_and_clear_pending_events();
3034 assert_eq!(events_4.len(), 1);
3036 Event::PaymentSent { ref payment_preimage } => {
3037 assert_eq!(payment_preimage_1, *payment_preimage);
3039 _ => panic!("Unexpected event"),
3042 } else if messages_delivered == 2 {
3043 // nodes[0] still wants its RAA + commitment_signed
3044 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3045 } else if messages_delivered == 3 {
3046 // nodes[0] still wants its commitment_signed
3047 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3048 } else if messages_delivered == 4 {
3049 // nodes[1] still wants its final RAA
3050 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3051 } else if messages_delivered == 5 {
3052 // Everything was delivered...
3053 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3056 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3057 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3058 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3060 // Channel should still work fine...
3061 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3062 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3066 fn test_drop_messages_peer_disconnect_a() {
3067 do_test_drop_messages_peer_disconnect(0);
3068 do_test_drop_messages_peer_disconnect(1);
3069 do_test_drop_messages_peer_disconnect(2);
3070 do_test_drop_messages_peer_disconnect(3);
3074 fn test_drop_messages_peer_disconnect_b() {
3075 do_test_drop_messages_peer_disconnect(4);
3076 do_test_drop_messages_peer_disconnect(5);
3077 do_test_drop_messages_peer_disconnect(6);
3081 fn test_funding_peer_disconnect() {
3082 // Test that we can lock in our funding tx while disconnected
3083 let nodes = create_network(2, &[None, None]);
3084 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
3086 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3087 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3089 confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3090 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3091 assert_eq!(events_1.len(), 1);
3093 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3094 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3096 _ => panic!("Unexpected event"),
3099 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3101 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3102 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3104 confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3105 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3106 assert_eq!(events_2.len(), 2);
3107 let funding_locked = match events_2[0] {
3108 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3109 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3112 _ => panic!("Unexpected event"),
3114 let bs_announcement_sigs = match events_2[1] {
3115 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3116 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3119 _ => panic!("Unexpected event"),
3122 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3124 nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked).unwrap();
3125 nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs).unwrap();
3126 let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3127 assert_eq!(events_3.len(), 2);
3128 let as_announcement_sigs = match events_3[0] {
3129 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3130 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3133 _ => panic!("Unexpected event"),
3135 let (as_announcement, as_update) = match events_3[1] {
3136 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3137 (msg.clone(), update_msg.clone())
3139 _ => panic!("Unexpected event"),
3142 nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs).unwrap();
3143 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3144 assert_eq!(events_4.len(), 1);
3145 let (_, bs_update) = match events_4[0] {
3146 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3147 (msg.clone(), update_msg.clone())
3149 _ => panic!("Unexpected event"),
3152 nodes[0].router.handle_channel_announcement(&as_announcement).unwrap();
3153 nodes[0].router.handle_channel_update(&bs_update).unwrap();
3154 nodes[0].router.handle_channel_update(&as_update).unwrap();
3156 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3157 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3158 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3162 fn test_drop_messages_peer_disconnect_dual_htlc() {
3163 // Test that we can handle reconnecting when both sides of a channel have pending
3164 // commitment_updates when we disconnect.
3165 let mut nodes = create_network(2, &[None, None]);
3166 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3168 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3170 // Now try to send a second payment which will fail to send
3171 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3172 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3174 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
3175 check_added_monitors!(nodes[0], 1);
3177 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3178 assert_eq!(events_1.len(), 1);
3180 MessageSendEvent::UpdateHTLCs { .. } => {},
3181 _ => panic!("Unexpected event"),
3184 assert!(nodes[1].node.claim_funds(payment_preimage_1, 1_000_000));
3185 check_added_monitors!(nodes[1], 1);
3187 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3188 assert_eq!(events_2.len(), 1);
3190 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 } } => {
3191 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3192 assert!(update_add_htlcs.is_empty());
3193 assert_eq!(update_fulfill_htlcs.len(), 1);
3194 assert!(update_fail_htlcs.is_empty());
3195 assert!(update_fail_malformed_htlcs.is_empty());
3196 assert!(update_fee.is_none());
3198 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
3199 let events_3 = nodes[0].node.get_and_clear_pending_events();
3200 assert_eq!(events_3.len(), 1);
3202 Event::PaymentSent { ref payment_preimage } => {
3203 assert_eq!(*payment_preimage, payment_preimage_1);
3205 _ => panic!("Unexpected event"),
3208 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
3209 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3210 // No commitment_signed so get_event_msg's assert(len == 1) passes
3211 check_added_monitors!(nodes[0], 1);
3213 _ => panic!("Unexpected event"),
3216 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3217 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3219 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3220 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3221 assert_eq!(reestablish_1.len(), 1);
3222 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3223 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3224 assert_eq!(reestablish_2.len(), 1);
3226 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3227 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3228 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3229 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3231 assert!(as_resp.0.is_none());
3232 assert!(bs_resp.0.is_none());
3234 assert!(bs_resp.1.is_none());
3235 assert!(bs_resp.2.is_none());
3237 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3239 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3240 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3241 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3242 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3243 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3244 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();
3245 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
3246 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3247 // No commitment_signed so get_event_msg's assert(len == 1) passes
3248 check_added_monitors!(nodes[1], 1);
3250 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
3251 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3252 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3253 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3254 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3255 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3256 assert!(bs_second_commitment_signed.update_fee.is_none());
3257 check_added_monitors!(nodes[1], 1);
3259 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
3260 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3261 assert!(as_commitment_signed.update_add_htlcs.is_empty());
3262 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3263 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3264 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3265 assert!(as_commitment_signed.update_fee.is_none());
3266 check_added_monitors!(nodes[0], 1);
3268 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
3269 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3270 // No commitment_signed so get_event_msg's assert(len == 1) passes
3271 check_added_monitors!(nodes[0], 1);
3273 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
3274 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3275 // No commitment_signed so get_event_msg's assert(len == 1) passes
3276 check_added_monitors!(nodes[1], 1);
3278 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
3279 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3280 check_added_monitors!(nodes[1], 1);
3282 expect_pending_htlcs_forwardable!(nodes[1]);
3284 let events_5 = nodes[1].node.get_and_clear_pending_events();
3285 assert_eq!(events_5.len(), 1);
3287 Event::PaymentReceived { ref payment_hash, amt: _ } => {
3288 assert_eq!(payment_hash_2, *payment_hash);
3290 _ => panic!("Unexpected event"),
3293 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
3294 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3295 check_added_monitors!(nodes[0], 1);
3297 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3301 fn test_invalid_channel_announcement() {
3302 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3303 let secp_ctx = Secp256k1::new();
3304 let nodes = create_network(2, &[None, None]);
3306 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], LocalFeatures::new(), LocalFeatures::new());
3308 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3309 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3310 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3311 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3313 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 } );
3315 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
3316 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
3318 let as_network_key = nodes[0].node.get_our_node_id();
3319 let bs_network_key = nodes[1].node.get_our_node_id();
3321 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3323 let mut chan_announcement;
3325 macro_rules! dummy_unsigned_msg {
3327 msgs::UnsignedChannelAnnouncement {
3328 features: msgs::GlobalFeatures::new(),
3329 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3330 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3331 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3332 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3333 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3334 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3335 excess_data: Vec::new(),
3340 macro_rules! sign_msg {
3341 ($unsigned_msg: expr) => {
3342 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3343 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
3344 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
3345 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3346 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3347 chan_announcement = msgs::ChannelAnnouncement {
3348 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3349 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3350 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3351 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3352 contents: $unsigned_msg
3357 let unsigned_msg = dummy_unsigned_msg!();
3358 sign_msg!(unsigned_msg);
3359 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3360 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 } );
3362 // Configured with Network::Testnet
3363 let mut unsigned_msg = dummy_unsigned_msg!();
3364 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3365 sign_msg!(unsigned_msg);
3366 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3368 let mut unsigned_msg = dummy_unsigned_msg!();
3369 unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3370 sign_msg!(unsigned_msg);
3371 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3375 fn test_no_txn_manager_serialize_deserialize() {
3376 let mut nodes = create_network(2, &[None, None]);
3378 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, LocalFeatures::new(), LocalFeatures::new());
3380 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3382 let nodes_0_serialized = nodes[0].node.encode();
3383 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3384 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3386 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 })));
3387 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3388 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3389 assert!(chan_0_monitor_read.is_empty());
3391 let mut nodes_0_read = &nodes_0_serialized[..];
3392 let config = UserConfig::default();
3393 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3394 let (_, nodes_0_deserialized) = {
3395 let mut channel_monitors = HashMap::new();
3396 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3397 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3398 default_config: config,
3400 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3401 monitor: nodes[0].chan_monitor.clone(),
3402 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3403 logger: Arc::new(test_utils::TestLogger::new()),
3404 channel_monitors: &channel_monitors,
3407 assert!(nodes_0_read.is_empty());
3409 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3410 nodes[0].node = Arc::new(nodes_0_deserialized);
3411 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
3412 nodes[0].block_notifier.register_listener(Arc::downgrade(&nodes_0_as_listener));
3413 assert_eq!(nodes[0].node.list_channels().len(), 1);
3414 check_added_monitors!(nodes[0], 1);
3416 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3417 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3418 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3419 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3421 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3422 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3423 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3424 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3426 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3427 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3428 for node in nodes.iter() {
3429 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3430 node.router.handle_channel_update(&as_update).unwrap();
3431 node.router.handle_channel_update(&bs_update).unwrap();
3434 send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3438 fn test_simple_manager_serialize_deserialize() {
3439 let mut nodes = create_network(2, &[None, None]);
3440 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3442 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3443 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3445 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3447 let nodes_0_serialized = nodes[0].node.encode();
3448 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3449 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3451 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 })));
3452 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3453 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3454 assert!(chan_0_monitor_read.is_empty());
3456 let mut nodes_0_read = &nodes_0_serialized[..];
3457 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3458 let (_, nodes_0_deserialized) = {
3459 let mut channel_monitors = HashMap::new();
3460 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3461 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3462 default_config: UserConfig::default(),
3464 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3465 monitor: nodes[0].chan_monitor.clone(),
3466 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3467 logger: Arc::new(test_utils::TestLogger::new()),
3468 channel_monitors: &channel_monitors,
3471 assert!(nodes_0_read.is_empty());
3473 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3474 nodes[0].node = Arc::new(nodes_0_deserialized);
3475 check_added_monitors!(nodes[0], 1);
3477 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3479 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3480 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
3484 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3485 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3486 let mut nodes = create_network(4, &[None, None, None, None]);
3487 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3488 create_announced_chan_between_nodes(&nodes, 2, 0, LocalFeatures::new(), LocalFeatures::new());
3489 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, LocalFeatures::new(), LocalFeatures::new());
3491 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3493 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3494 let nodes_0_serialized = nodes[0].node.encode();
3496 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3497 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3498 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3499 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3501 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3503 let mut node_0_monitors_serialized = Vec::new();
3504 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3505 let mut writer = test_utils::TestVecWriter(Vec::new());
3506 monitor.1.write_for_disk(&mut writer).unwrap();
3507 node_0_monitors_serialized.push(writer.0);
3510 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 })));
3511 let mut node_0_monitors = Vec::new();
3512 for serialized in node_0_monitors_serialized.iter() {
3513 let mut read = &serialized[..];
3514 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3515 assert!(read.is_empty());
3516 node_0_monitors.push(monitor);
3519 let mut nodes_0_read = &nodes_0_serialized[..];
3520 let keys_manager = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3521 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3522 default_config: UserConfig::default(),
3524 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3525 monitor: nodes[0].chan_monitor.clone(),
3526 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3527 logger: Arc::new(test_utils::TestLogger::new()),
3528 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
3530 assert!(nodes_0_read.is_empty());
3532 { // Channel close should result in a commitment tx and an HTLC tx
3533 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3534 assert_eq!(txn.len(), 2);
3535 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3536 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3539 for monitor in node_0_monitors.drain(..) {
3540 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
3541 check_added_monitors!(nodes[0], 1);
3543 nodes[0].node = Arc::new(nodes_0_deserialized);
3545 // nodes[1] and nodes[2] have no lost state with nodes[0]...
3546 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3547 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3548 //... and we can even still claim the payment!
3549 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
3551 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
3552 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3553 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
3554 if let Err(msgs::LightningError { action: msgs::ErrorAction::SendErrorMessage { msg }, .. }) = nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish) {
3555 assert_eq!(msg.channel_id, channel_id);
3556 } else { panic!("Unexpected result"); }
3559 macro_rules! check_spendable_outputs {
3560 ($node: expr, $der_idx: expr) => {
3562 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3563 let mut txn = Vec::new();
3564 for event in events {
3566 Event::SpendableOutputs { ref outputs } => {
3567 for outp in outputs {
3569 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
3571 previous_output: outpoint.clone(),
3572 script_sig: Script::new(),
3574 witness: Vec::new(),
3577 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3578 value: output.value,
3580 let mut spend_tx = Transaction {
3586 let secp_ctx = Secp256k1::new();
3587 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
3588 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
3589 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3590 let remotesig = secp_ctx.sign(&sighash, key);
3591 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
3592 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3593 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
3596 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
3598 previous_output: outpoint.clone(),
3599 script_sig: Script::new(),
3600 sequence: *to_self_delay as u32,
3601 witness: Vec::new(),
3604 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3605 value: output.value,
3607 let mut spend_tx = Transaction {
3613 let secp_ctx = Secp256k1::new();
3614 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
3615 let local_delaysig = secp_ctx.sign(&sighash, key);
3616 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
3617 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3618 spend_tx.input[0].witness.push(vec!(0));
3619 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
3622 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
3623 let secp_ctx = Secp256k1::new();
3625 previous_output: outpoint.clone(),
3626 script_sig: Script::new(),
3628 witness: Vec::new(),
3631 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3632 value: output.value,
3634 let mut spend_tx = Transaction {
3638 output: vec![outp.clone()],
3641 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
3643 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
3645 Err(_) => panic!("Your RNG is busted"),
3648 Err(_) => panic!("Your rng is busted"),
3651 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
3652 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
3653 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3654 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
3655 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
3656 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3657 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
3663 _ => panic!("Unexpected event"),
3672 fn test_claim_sizeable_push_msat() {
3673 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
3674 let nodes = create_network(2, &[None, None]);
3676 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, LocalFeatures::new(), LocalFeatures::new());
3677 nodes[1].node.force_close_channel(&chan.2);
3678 check_closed_broadcast!(nodes[1]);
3679 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3680 assert_eq!(node_txn.len(), 1);
3681 check_spends!(node_txn[0], chan.3.clone());
3682 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
3684 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3685 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3686 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3687 assert_eq!(spend_txn.len(), 1);
3688 check_spends!(spend_txn[0], node_txn[0].clone());
3692 fn test_claim_on_remote_sizeable_push_msat() {
3693 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3694 // to_remote output is encumbered by a P2WPKH
3695 let nodes = create_network(2, &[None, None]);
3697 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, LocalFeatures::new(), LocalFeatures::new());
3698 nodes[0].node.force_close_channel(&chan.2);
3699 check_closed_broadcast!(nodes[0]);
3701 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3702 assert_eq!(node_txn.len(), 1);
3703 check_spends!(node_txn[0], chan.3.clone());
3704 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
3706 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3707 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3708 check_closed_broadcast!(nodes[1]);
3709 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3710 assert_eq!(spend_txn.len(), 2);
3711 assert_eq!(spend_txn[0], spend_txn[1]);
3712 check_spends!(spend_txn[0], node_txn[0].clone());
3716 fn test_claim_on_remote_revoked_sizeable_push_msat() {
3717 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3718 // to_remote output is encumbered by a P2WPKH
3720 let nodes = create_network(2, &[None, None]);
3722 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, LocalFeatures::new(), LocalFeatures::new());
3723 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3724 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
3725 assert_eq!(revoked_local_txn[0].input.len(), 1);
3726 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
3728 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
3729 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3730 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3731 check_closed_broadcast!(nodes[1]);
3733 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3734 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3735 assert_eq!(spend_txn.len(), 4);
3736 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
3737 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
3738 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
3739 check_spends!(spend_txn[1], node_txn[0].clone());
3743 fn test_static_spendable_outputs_preimage_tx() {
3744 let nodes = create_network(2, &[None, None]);
3746 // Create some initial channels
3747 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3749 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3751 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3752 assert_eq!(commitment_tx[0].input.len(), 1);
3753 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
3755 // Settle A's commitment tx on B's chain
3756 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3757 assert!(nodes[1].node.claim_funds(payment_preimage, 3_000_000));
3758 check_added_monitors!(nodes[1], 1);
3759 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
3760 let events = nodes[1].node.get_and_clear_pending_msg_events();
3762 MessageSendEvent::UpdateHTLCs { .. } => {},
3763 _ => panic!("Unexpected event"),
3766 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3767 _ => panic!("Unexepected event"),
3770 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
3771 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
3772 check_spends!(node_txn[0], commitment_tx[0].clone());
3773 assert_eq!(node_txn[0], node_txn[2]);
3774 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3775 check_spends!(node_txn[1], chan_1.3.clone());
3777 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
3778 assert_eq!(spend_txn.len(), 2);
3779 assert_eq!(spend_txn[0], spend_txn[1]);
3780 check_spends!(spend_txn[0], node_txn[0].clone());
3784 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
3785 let nodes = create_network(2, &[None, None]);
3787 // Create some initial channels
3788 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3790 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3791 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
3792 assert_eq!(revoked_local_txn[0].input.len(), 1);
3793 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3795 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
3797 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3798 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3799 check_closed_broadcast!(nodes[1]);
3801 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3802 assert_eq!(node_txn.len(), 3);
3803 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
3804 assert_eq!(node_txn[0].input.len(), 2);
3805 check_spends!(node_txn[0], revoked_local_txn[0].clone());
3807 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3808 assert_eq!(spend_txn.len(), 2);
3809 assert_eq!(spend_txn[0], spend_txn[1]);
3810 check_spends!(spend_txn[0], node_txn[0].clone());
3814 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
3815 let nodes = create_network(2, &[None, None]);
3817 // Create some initial channels
3818 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3820 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3821 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3822 assert_eq!(revoked_local_txn[0].input.len(), 1);
3823 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3825 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
3827 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3828 // A will generate HTLC-Timeout from revoked commitment tx
3829 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3830 check_closed_broadcast!(nodes[0]);
3832 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3833 assert_eq!(revoked_htlc_txn.len(), 3);
3834 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3835 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3836 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3837 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3838 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
3840 // B will generate justice tx from A's revoked commitment/HTLC tx
3841 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3842 check_closed_broadcast!(nodes[1]);
3844 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3845 assert_eq!(node_txn.len(), 4);
3846 assert_eq!(node_txn[3].input.len(), 1);
3847 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3849 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
3850 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3851 assert_eq!(spend_txn.len(), 3);
3852 assert_eq!(spend_txn[0], spend_txn[1]);
3853 check_spends!(spend_txn[0], node_txn[0].clone());
3854 check_spends!(spend_txn[2], node_txn[3].clone());
3858 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
3859 let nodes = create_network(2, &[None, None]);
3861 // Create some initial channels
3862 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3864 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3865 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3866 assert_eq!(revoked_local_txn[0].input.len(), 1);
3867 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3869 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
3871 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3872 // B will generate HTLC-Success from revoked commitment tx
3873 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3874 check_closed_broadcast!(nodes[1]);
3875 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3877 assert_eq!(revoked_htlc_txn.len(), 3);
3878 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3879 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3880 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3881 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3883 // A will generate justice tx from B's revoked commitment/HTLC tx
3884 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3885 check_closed_broadcast!(nodes[0]);
3887 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3888 assert_eq!(node_txn.len(), 4);
3889 assert_eq!(node_txn[3].input.len(), 1);
3890 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3892 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
3893 let spend_txn = check_spendable_outputs!(nodes[0], 1);
3894 assert_eq!(spend_txn.len(), 5);
3895 assert_eq!(spend_txn[0], spend_txn[2]);
3896 assert_eq!(spend_txn[1], spend_txn[3]);
3897 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
3898 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
3899 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
3903 fn test_onchain_to_onchain_claim() {
3904 // Test that in case of channel closure, we detect the state of output thanks to
3905 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
3906 // First, have C claim an HTLC against its own latest commitment transaction.
3907 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
3909 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
3912 let nodes = create_network(3, &[None, None, None]);
3914 // Create some initial channels
3915 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
3916 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
3918 // Rebalance the network a bit by relaying one payment through all the channels ...
3919 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
3920 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
3922 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3923 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3924 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3925 check_spends!(commitment_tx[0], chan_2.3.clone());
3926 nodes[2].node.claim_funds(payment_preimage, 3_000_000);
3927 check_added_monitors!(nodes[2], 1);
3928 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3929 assert!(updates.update_add_htlcs.is_empty());
3930 assert!(updates.update_fail_htlcs.is_empty());
3931 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3932 assert!(updates.update_fail_malformed_htlcs.is_empty());
3934 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3935 check_closed_broadcast!(nodes[2]);
3937 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
3938 assert_eq!(c_txn.len(), 3);
3939 assert_eq!(c_txn[0], c_txn[2]);
3940 assert_eq!(commitment_tx[0], c_txn[1]);
3941 check_spends!(c_txn[1], chan_2.3.clone());
3942 check_spends!(c_txn[2], c_txn[1].clone());
3943 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
3944 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3945 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3946 assert_eq!(c_txn[0].lock_time, 0); // Success tx
3948 // 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
3949 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
3951 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3952 assert_eq!(b_txn.len(), 4);
3953 assert_eq!(b_txn[0], b_txn[3]);
3954 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
3955 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
3956 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3957 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3958 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3959 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
3960 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3961 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3962 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3965 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
3966 check_added_monitors!(nodes[1], 1);
3967 match msg_events[0] {
3968 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3969 _ => panic!("Unexpected event"),
3971 match msg_events[1] {
3972 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, .. } } => {
3973 assert!(update_add_htlcs.is_empty());
3974 assert!(update_fail_htlcs.is_empty());
3975 assert_eq!(update_fulfill_htlcs.len(), 1);
3976 assert!(update_fail_malformed_htlcs.is_empty());
3977 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3979 _ => panic!("Unexpected event"),
3981 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
3982 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3983 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3984 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3985 assert_eq!(b_txn.len(), 3);
3986 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
3987 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
3988 check_spends!(b_txn[0], commitment_tx[0].clone());
3989 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3990 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3991 assert_eq!(b_txn[2].lock_time, 0); // Success tx
3993 check_closed_broadcast!(nodes[1]);
3997 fn test_duplicate_payment_hash_one_failure_one_success() {
3998 // Topology : A --> B --> C
3999 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4000 let mut nodes = create_network(3, &[None, None, None]);
4002 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4003 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
4005 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4006 *nodes[0].network_payment_count.borrow_mut() -= 1;
4007 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4009 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
4010 assert_eq!(commitment_txn[0].input.len(), 1);
4011 check_spends!(commitment_txn[0], chan_2.3.clone());
4013 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4014 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4015 check_closed_broadcast!(nodes[1]);
4017 let htlc_timeout_tx;
4018 { // Extract one of the two HTLC-Timeout transaction
4019 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4020 assert_eq!(node_txn.len(), 7);
4021 assert_eq!(node_txn[0], node_txn[5]);
4022 assert_eq!(node_txn[1], node_txn[6]);
4023 check_spends!(node_txn[0], commitment_txn[0].clone());
4024 assert_eq!(node_txn[0].input.len(), 1);
4025 check_spends!(node_txn[1], commitment_txn[0].clone());
4026 assert_eq!(node_txn[1].input.len(), 1);
4027 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4028 check_spends!(node_txn[2], chan_2.3.clone());
4029 check_spends!(node_txn[3], node_txn[2].clone());
4030 check_spends!(node_txn[4], node_txn[2].clone());
4031 htlc_timeout_tx = node_txn[1].clone();
4034 nodes[2].node.claim_funds(our_payment_preimage, 900_000);
4035 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4036 check_added_monitors!(nodes[2], 2);
4037 let events = nodes[2].node.get_and_clear_pending_msg_events();
4039 MessageSendEvent::UpdateHTLCs { .. } => {},
4040 _ => panic!("Unexpected event"),
4043 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4044 _ => panic!("Unexepected event"),
4046 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4047 assert_eq!(htlc_success_txn.len(), 5);
4048 check_spends!(htlc_success_txn[2], chan_2.3.clone());
4049 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
4050 assert_eq!(htlc_success_txn[0].input.len(), 1);
4051 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4052 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4053 assert_eq!(htlc_success_txn[1].input.len(), 1);
4054 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4055 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4056 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
4057 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
4059 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4060 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4061 expect_pending_htlcs_forwardable!(nodes[1]);
4062 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4063 assert!(htlc_updates.update_add_htlcs.is_empty());
4064 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4065 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4066 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4067 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4068 check_added_monitors!(nodes[1], 1);
4070 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
4071 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4073 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4074 let events = nodes[0].node.get_and_clear_pending_msg_events();
4075 assert_eq!(events.len(), 1);
4077 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
4079 _ => { panic!("Unexpected event"); }
4082 let events = nodes[0].node.get_and_clear_pending_events();
4084 Event::PaymentFailed { ref payment_hash, .. } => {
4085 assert_eq!(*payment_hash, duplicate_payment_hash);
4087 _ => panic!("Unexpected event"),
4090 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4091 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4092 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4093 assert!(updates.update_add_htlcs.is_empty());
4094 assert!(updates.update_fail_htlcs.is_empty());
4095 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4096 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4097 assert!(updates.update_fail_malformed_htlcs.is_empty());
4098 check_added_monitors!(nodes[1], 1);
4100 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
4101 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4103 let events = nodes[0].node.get_and_clear_pending_events();
4105 Event::PaymentSent { ref payment_preimage } => {
4106 assert_eq!(*payment_preimage, our_payment_preimage);
4108 _ => panic!("Unexpected event"),
4113 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4114 let nodes = create_network(2, &[None, None]);
4116 // Create some initial channels
4117 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4119 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4120 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4121 assert_eq!(local_txn[0].input.len(), 1);
4122 check_spends!(local_txn[0], chan_1.3.clone());
4124 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4125 nodes[1].node.claim_funds(payment_preimage, 9_000_000);
4126 check_added_monitors!(nodes[1], 1);
4127 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4128 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4129 let events = nodes[1].node.get_and_clear_pending_msg_events();
4131 MessageSendEvent::UpdateHTLCs { .. } => {},
4132 _ => panic!("Unexpected event"),
4135 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4136 _ => panic!("Unexepected event"),
4138 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4139 assert_eq!(node_txn[0].input.len(), 1);
4140 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4141 check_spends!(node_txn[0], local_txn[0].clone());
4143 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4144 let spend_txn = check_spendable_outputs!(nodes[1], 1);
4145 assert_eq!(spend_txn.len(), 2);
4146 check_spends!(spend_txn[0], node_txn[0].clone());
4147 check_spends!(spend_txn[1], node_txn[2].clone());
4150 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4151 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4152 // unrevoked commitment transaction.
4153 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4154 // a remote RAA before they could be failed backwards (and combinations thereof).
4155 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4156 // use the same payment hashes.
4157 // Thus, we use a six-node network:
4162 // And test where C fails back to A/B when D announces its latest commitment transaction
4163 let nodes = create_network(6, &[None, None, None, None, None, None]);
4165 create_announced_chan_between_nodes(&nodes, 0, 2, LocalFeatures::new(), LocalFeatures::new());
4166 create_announced_chan_between_nodes(&nodes, 1, 2, LocalFeatures::new(), LocalFeatures::new());
4167 let chan = create_announced_chan_between_nodes(&nodes, 2, 3, LocalFeatures::new(), LocalFeatures::new());
4168 create_announced_chan_between_nodes(&nodes, 3, 4, LocalFeatures::new(), LocalFeatures::new());
4169 create_announced_chan_between_nodes(&nodes, 3, 5, LocalFeatures::new(), LocalFeatures::new());
4171 // Rebalance and check output sanity...
4172 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
4173 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
4174 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 2);
4176 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
4178 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
4180 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
4181 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();
4183 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
4185 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
4187 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4189 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4190 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4192 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
4194 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
4197 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
4199 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();
4200 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
4203 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
4205 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
4206 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
4208 // Double-check that six of the new HTLC were added
4209 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
4210 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
4211 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.len(), 1);
4212 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 8);
4214 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
4215 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
4216 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
4217 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
4218 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
4219 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
4220 check_added_monitors!(nodes[4], 0);
4221 expect_pending_htlcs_forwardable!(nodes[4]);
4222 check_added_monitors!(nodes[4], 1);
4224 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
4225 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]).unwrap();
4226 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]).unwrap();
4227 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]).unwrap();
4228 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]).unwrap();
4229 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
4231 // Fail 3rd below-dust and 7th above-dust HTLCs
4232 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
4233 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
4234 check_added_monitors!(nodes[5], 0);
4235 expect_pending_htlcs_forwardable!(nodes[5]);
4236 check_added_monitors!(nodes[5], 1);
4238 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
4239 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]).unwrap();
4240 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]).unwrap();
4241 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
4243 let ds_prev_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
4245 expect_pending_htlcs_forwardable!(nodes[3]);
4246 check_added_monitors!(nodes[3], 1);
4247 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
4248 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]).unwrap();
4249 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]).unwrap();
4250 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]).unwrap();
4251 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]).unwrap();
4252 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]).unwrap();
4253 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]).unwrap();
4254 if deliver_last_raa {
4255 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
4257 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
4260 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
4261 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
4262 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
4263 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
4265 // We now broadcast the latest commitment transaction, which *should* result in failures for
4266 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
4267 // the non-broadcast above-dust HTLCs.
4269 // Alternatively, we may broadcast the previous commitment transaction, which should only
4270 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
4271 let ds_last_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
4273 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4274 if announce_latest {
4275 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
4277 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
4279 connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4280 check_closed_broadcast!(nodes[2]);
4281 expect_pending_htlcs_forwardable!(nodes[2]);
4282 check_added_monitors!(nodes[2], 2);
4284 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
4285 assert_eq!(cs_msgs.len(), 2);
4286 let mut a_done = false;
4287 for msg in cs_msgs {
4289 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
4290 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
4291 // should be failed-backwards here.
4292 let target = if *node_id == nodes[0].node.get_our_node_id() {
4293 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
4294 for htlc in &updates.update_fail_htlcs {
4295 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 });
4297 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
4302 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
4303 for htlc in &updates.update_fail_htlcs {
4304 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
4306 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
4307 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
4310 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
4311 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
4312 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]).unwrap();
4313 if announce_latest {
4314 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]).unwrap();
4315 if *node_id == nodes[0].node.get_our_node_id() {
4316 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]).unwrap();
4319 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4321 _ => panic!("Unexpected event"),
4325 let as_events = nodes[0].node.get_and_clear_pending_events();
4326 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4327 let mut as_failds = HashSet::new();
4328 for event in as_events.iter() {
4329 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4330 assert!(as_failds.insert(*payment_hash));
4331 if *payment_hash != payment_hash_2 {
4332 assert_eq!(*rejected_by_dest, deliver_last_raa);
4334 assert!(!rejected_by_dest);
4336 } else { panic!("Unexpected event"); }
4338 assert!(as_failds.contains(&payment_hash_1));
4339 assert!(as_failds.contains(&payment_hash_2));
4340 if announce_latest {
4341 assert!(as_failds.contains(&payment_hash_3));
4342 assert!(as_failds.contains(&payment_hash_5));
4344 assert!(as_failds.contains(&payment_hash_6));
4346 let bs_events = nodes[1].node.get_and_clear_pending_events();
4347 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4348 let mut bs_failds = HashSet::new();
4349 for event in bs_events.iter() {
4350 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4351 assert!(bs_failds.insert(*payment_hash));
4352 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4353 assert_eq!(*rejected_by_dest, deliver_last_raa);
4355 assert!(!rejected_by_dest);
4357 } else { panic!("Unexpected event"); }
4359 assert!(bs_failds.contains(&payment_hash_1));
4360 assert!(bs_failds.contains(&payment_hash_2));
4361 if announce_latest {
4362 assert!(bs_failds.contains(&payment_hash_4));
4364 assert!(bs_failds.contains(&payment_hash_5));
4366 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4367 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4368 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4369 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4370 // PaymentFailureNetworkUpdates.
4371 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4372 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4373 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4374 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4375 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4377 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4378 _ => panic!("Unexpected event"),
4384 fn test_fail_backwards_latest_remote_announce_a() {
4385 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4389 fn test_fail_backwards_latest_remote_announce_b() {
4390 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4394 fn test_fail_backwards_previous_remote_announce() {
4395 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4396 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4397 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4401 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4402 let nodes = create_network(2, &[None, None]);
4404 // Create some initial channels
4405 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4407 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4408 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4409 assert_eq!(local_txn[0].input.len(), 1);
4410 check_spends!(local_txn[0], chan_1.3.clone());
4412 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4413 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4414 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4415 check_closed_broadcast!(nodes[0]);
4417 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4418 assert_eq!(node_txn[0].input.len(), 1);
4419 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4420 check_spends!(node_txn[0], local_txn[0].clone());
4422 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4423 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4424 assert_eq!(spend_txn.len(), 8);
4425 assert_eq!(spend_txn[0], spend_txn[2]);
4426 assert_eq!(spend_txn[0], spend_txn[4]);
4427 assert_eq!(spend_txn[0], spend_txn[6]);
4428 assert_eq!(spend_txn[1], spend_txn[3]);
4429 assert_eq!(spend_txn[1], spend_txn[5]);
4430 assert_eq!(spend_txn[1], spend_txn[7]);
4431 check_spends!(spend_txn[0], local_txn[0].clone());
4432 check_spends!(spend_txn[1], node_txn[0].clone());
4436 fn test_static_output_closing_tx() {
4437 let nodes = create_network(2, &[None, None]);
4439 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4441 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4442 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4444 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4445 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4446 let spend_txn = check_spendable_outputs!(nodes[0], 2);
4447 assert_eq!(spend_txn.len(), 1);
4448 check_spends!(spend_txn[0], closing_tx.clone());
4450 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4451 let spend_txn = check_spendable_outputs!(nodes[1], 2);
4452 assert_eq!(spend_txn.len(), 1);
4453 check_spends!(spend_txn[0], closing_tx);
4456 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4457 let nodes = create_network(2, &[None, None]);
4458 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4460 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4462 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4463 // present in B's local commitment transaction, but none of A's commitment transactions.
4464 assert!(nodes[1].node.claim_funds(our_payment_preimage, if use_dust { 50_000 } else { 3_000_000 }));
4465 check_added_monitors!(nodes[1], 1);
4467 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4468 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]).unwrap();
4469 let events = nodes[0].node.get_and_clear_pending_events();
4470 assert_eq!(events.len(), 1);
4472 Event::PaymentSent { payment_preimage } => {
4473 assert_eq!(payment_preimage, our_payment_preimage);
4475 _ => panic!("Unexpected event"),
4478 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4479 check_added_monitors!(nodes[0], 1);
4480 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4481 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4482 check_added_monitors!(nodes[1], 1);
4484 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4485 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4486 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4487 header.prev_blockhash = header.bitcoin_hash();
4489 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4490 check_closed_broadcast!(nodes[1]);
4493 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4494 let mut nodes = create_network(2, &[None, None]);
4495 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4497 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();
4498 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4499 nodes[0].node.send_payment(route, payment_hash).unwrap();
4500 check_added_monitors!(nodes[0], 1);
4502 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4504 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4505 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4506 // to "time out" the HTLC.
4508 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4510 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4511 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
4512 header.prev_blockhash = header.bitcoin_hash();
4514 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4515 check_closed_broadcast!(nodes[0]);
4518 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4519 let nodes = create_network(3, &[None, None, None]);
4520 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
4522 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4523 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4524 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4525 // actually revoked.
4526 let htlc_value = if use_dust { 50000 } else { 3000000 };
4527 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4528 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4529 expect_pending_htlcs_forwardable!(nodes[1]);
4530 check_added_monitors!(nodes[1], 1);
4532 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4533 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]).unwrap();
4534 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4535 check_added_monitors!(nodes[0], 1);
4536 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4537 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4538 check_added_monitors!(nodes[1], 1);
4539 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1).unwrap();
4540 check_added_monitors!(nodes[1], 1);
4541 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4543 if check_revoke_no_close {
4544 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4545 check_added_monitors!(nodes[0], 1);
4548 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4549 for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4550 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4551 header.prev_blockhash = header.bitcoin_hash();
4553 if !check_revoke_no_close {
4554 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4555 check_closed_broadcast!(nodes[0]);
4557 let events = nodes[0].node.get_and_clear_pending_events();
4558 assert_eq!(events.len(), 1);
4560 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4561 assert_eq!(payment_hash, our_payment_hash);
4562 assert!(rejected_by_dest);
4564 _ => panic!("Unexpected event"),
4569 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
4570 // There are only a few cases to test here:
4571 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
4572 // broadcastable commitment transactions result in channel closure,
4573 // * its included in an unrevoked-but-previous remote commitment transaction,
4574 // * its included in the latest remote or local commitment transactions.
4575 // We test each of the three possible commitment transactions individually and use both dust and
4577 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
4578 // assume they are handled the same across all six cases, as both outbound and inbound failures are
4579 // tested for at least one of the cases in other tests.
4581 fn htlc_claim_single_commitment_only_a() {
4582 do_htlc_claim_local_commitment_only(true);
4583 do_htlc_claim_local_commitment_only(false);
4585 do_htlc_claim_current_remote_commitment_only(true);
4586 do_htlc_claim_current_remote_commitment_only(false);
4590 fn htlc_claim_single_commitment_only_b() {
4591 do_htlc_claim_previous_remote_commitment_only(true, false);
4592 do_htlc_claim_previous_remote_commitment_only(false, false);
4593 do_htlc_claim_previous_remote_commitment_only(true, true);
4594 do_htlc_claim_previous_remote_commitment_only(false, true);
4597 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>)
4598 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4601 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);
4605 // 0: node1 fails backward
4606 // 1: final node fails backward
4607 // 2: payment completed but the user rejects the payment
4608 // 3: final node fails backward (but tamper onion payloads from node0)
4609 // 100: trigger error in the intermediate node and tamper returning fail_htlc
4610 // 200: trigger error in the final node and tamper returning fail_htlc
4611 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>)
4612 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4613 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
4617 // reset block height
4618 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4619 for ix in 0..nodes.len() {
4620 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
4623 macro_rules! expect_event {
4624 ($node: expr, $event_type: path) => {{
4625 let events = $node.node.get_and_clear_pending_events();
4626 assert_eq!(events.len(), 1);
4628 $event_type { .. } => {},
4629 _ => panic!("Unexpected event"),
4634 macro_rules! expect_htlc_forward {
4636 expect_event!($node, Event::PendingHTLCsForwardable);
4637 $node.node.process_pending_htlc_forwards();
4641 // 0 ~~> 2 send payment
4642 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
4643 check_added_monitors!(nodes[0], 1);
4644 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4645 // temper update_add (0 => 1)
4646 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
4647 if test_case == 0 || test_case == 3 || test_case == 100 {
4648 callback_msg(&mut update_add_0);
4651 // 0 => 1 update_add & CS
4652 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
4653 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
4655 let update_1_0 = match test_case {
4656 0|100 => { // intermediate node failure; fail backward to 0
4657 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4658 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));
4661 1|2|3|200 => { // final node failure; forwarding to 2
4662 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4664 if test_case != 200 {
4667 expect_htlc_forward!(&nodes[1]);
4669 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
4670 check_added_monitors!(&nodes[1], 1);
4671 assert_eq!(update_1.update_add_htlcs.len(), 1);
4672 // tamper update_add (1 => 2)
4673 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
4674 if test_case != 3 && test_case != 200 {
4675 callback_msg(&mut update_add_1);
4679 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
4680 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
4682 if test_case == 2 || test_case == 200 {
4683 expect_htlc_forward!(&nodes[2]);
4684 expect_event!(&nodes[2], Event::PaymentReceived);
4686 expect_pending_htlcs_forwardable!(nodes[2]);
4689 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4690 if test_case == 2 || test_case == 200 {
4691 check_added_monitors!(&nodes[2], 1);
4693 assert!(update_2_1.update_fail_htlcs.len() == 1);
4695 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
4696 if test_case == 200 {
4697 callback_fail(&mut fail_msg);
4701 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
4702 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
4704 // backward fail on 1
4705 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4706 assert!(update_1_0.update_fail_htlcs.len() == 1);
4709 _ => unreachable!(),
4712 // 1 => 0 commitment_signed_dance
4713 if update_1_0.update_fail_htlcs.len() > 0 {
4714 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
4715 if test_case == 100 {
4716 callback_fail(&mut fail_msg);
4718 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
4720 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
4723 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
4725 let events = nodes[0].node.get_and_clear_pending_events();
4726 assert_eq!(events.len(), 1);
4727 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
4728 assert_eq!(*rejected_by_dest, !expected_retryable);
4729 assert_eq!(*error_code, expected_error_code);
4731 panic!("Uexpected event");
4734 let events = nodes[0].node.get_and_clear_pending_msg_events();
4735 if expected_channel_update.is_some() {
4736 assert_eq!(events.len(), 1);
4738 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
4740 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
4741 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
4742 panic!("channel_update not found!");
4745 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
4746 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4747 assert!(*short_channel_id == *expected_short_channel_id);
4748 assert!(*is_permanent == *expected_is_permanent);
4750 panic!("Unexpected message event");
4753 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
4754 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4755 assert!(*node_id == *expected_node_id);
4756 assert!(*is_permanent == *expected_is_permanent);
4758 panic!("Unexpected message event");
4763 _ => panic!("Unexpected message event"),
4766 assert_eq!(events.len(), 0);
4770 impl msgs::ChannelUpdate {
4771 fn dummy() -> msgs::ChannelUpdate {
4772 use secp256k1::ffi::Signature as FFISignature;
4773 use secp256k1::Signature;
4774 msgs::ChannelUpdate {
4775 signature: Signature::from(FFISignature::new()),
4776 contents: msgs::UnsignedChannelUpdate {
4777 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
4778 short_channel_id: 0,
4781 cltv_expiry_delta: 0,
4782 htlc_minimum_msat: 0,
4784 fee_proportional_millionths: 0,
4785 excess_data: vec![],
4792 fn test_onion_failure() {
4793 use ln::msgs::ChannelUpdate;
4794 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
4797 const BADONION: u16 = 0x8000;
4798 const PERM: u16 = 0x4000;
4799 const NODE: u16 = 0x2000;
4800 const UPDATE: u16 = 0x1000;
4802 let mut nodes = create_network(3, &[None, None, None]);
4803 for node in nodes.iter() {
4804 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
4806 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())];
4807 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4808 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
4810 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
4812 // intermediate node failure
4813 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
4814 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4815 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4816 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4817 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4818 onion_payloads[0].realm = 3;
4819 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
4820 }, ||{}, 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
4822 // final node failure
4823 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
4824 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4825 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4826 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4827 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4828 onion_payloads[1].realm = 3;
4829 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
4830 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4832 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
4833 // receiving simulated fail messages
4834 // intermediate node failure
4835 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4837 msg.amount_msat -= 1;
4839 // and tamper returning error message
4840 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4841 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4842 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
4843 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
4845 // final node failure
4846 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4847 // and tamper returning error message
4848 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4849 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4850 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
4852 nodes[2].node.fail_htlc_backwards(&payment_hash);
4853 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
4855 // intermediate node failure
4856 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4857 msg.amount_msat -= 1;
4859 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4860 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4861 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
4862 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4864 // final node failure
4865 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4866 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4867 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4868 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
4870 nodes[2].node.fail_htlc_backwards(&payment_hash);
4871 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4873 // intermediate node failure
4874 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4875 msg.amount_msat -= 1;
4877 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4878 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4879 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
4881 nodes[2].node.fail_htlc_backwards(&payment_hash);
4882 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4884 // final node failure
4885 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4886 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4887 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4888 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
4890 nodes[2].node.fail_htlc_backwards(&payment_hash);
4891 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4893 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
4894 Some(BADONION|PERM|4), None);
4896 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
4897 Some(BADONION|PERM|5), None);
4899 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
4900 Some(BADONION|PERM|6), None);
4902 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4903 msg.amount_msat -= 1;
4905 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4906 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4907 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
4908 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4910 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4911 msg.amount_msat -= 1;
4913 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4914 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4915 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
4916 // short_channel_id from the processing node
4917 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4919 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4920 msg.amount_msat -= 1;
4922 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4923 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4924 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
4925 // short_channel_id from the processing node
4926 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4928 let mut bogus_route = route.clone();
4929 bogus_route.hops[1].short_channel_id -= 1;
4930 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
4931 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
4933 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
4934 let mut bogus_route = route.clone();
4935 let route_len = bogus_route.hops.len();
4936 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
4937 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4939 //TODO: with new config API, we will be able to generate both valid and
4940 //invalid channel_update cases.
4941 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
4942 msg.amount_msat -= 1;
4943 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4945 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
4946 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
4947 msg.cltv_expiry -= 1;
4948 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4950 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
4951 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
4952 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4954 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
4955 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4957 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
4958 nodes[2].node.fail_htlc_backwards(&payment_hash);
4959 }, false, Some(PERM|15), None);
4961 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
4962 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
4963 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4965 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
4966 }, || {}, true, Some(17), None);
4968 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
4969 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4970 for f in pending_forwards.iter_mut() {
4972 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4973 forward_info.outgoing_cltv_value += 1,
4978 }, true, Some(18), None);
4980 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
4981 // violate amt_to_forward > msg.amount_msat
4982 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4983 for f in pending_forwards.iter_mut() {
4985 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4986 forward_info.amt_to_forward -= 1,
4991 }, true, Some(19), None);
4993 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
4994 // disconnect event to the channel between nodes[1] ~ nodes[2]
4995 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
4996 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4997 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4998 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5000 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5001 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5002 let mut route = route.clone();
5004 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
5005 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
5006 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
5007 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5008 msg.cltv_expiry = htlc_cltv;
5009 msg.onion_routing_packet = onion_packet;
5010 }, ||{}, true, Some(21), None);
5015 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5016 let nodes = create_network(2, &[None, None]);
5017 //Force duplicate channel ids
5018 for node in nodes.iter() {
5019 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5022 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5023 let channel_value_satoshis=10000;
5024 let push_msat=10001;
5025 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).unwrap();
5026 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5027 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), LocalFeatures::new(), &node0_to_1_send_open_channel).unwrap();
5029 //Create a second channel with a channel_id collision
5030 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
5034 fn bolt2_open_channel_sending_node_checks_part2() {
5035 let nodes = create_network(2, &[None, None]);
5037 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5038 let channel_value_satoshis=2^24;
5039 let push_msat=10001;
5040 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
5042 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5043 let channel_value_satoshis=10000;
5044 // Test when push_msat is equal to 1000 * funding_satoshis.
5045 let push_msat=1000*channel_value_satoshis+1;
5046 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
5048 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5049 let channel_value_satoshis=10000;
5050 let push_msat=10001;
5051 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
5052 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5053 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5055 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5056 // 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
5057 assert!(node0_to_1_send_open_channel.channel_flags<=1);
5059 // 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.
5060 assert!(BREAKDOWN_TIMEOUT>0);
5061 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5063 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5064 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5065 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5067 // 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.
5068 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5069 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5070 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5071 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
5072 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5075 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5076 // 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.
5077 //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.
5080 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5081 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
5082 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5083 let mut nodes = create_network(2, &[None, None]);
5084 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5085 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5086 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5088 route.hops[0].fee_msat = 0;
5090 let err = nodes[0].node.send_payment(route, our_payment_hash);
5092 if let Err(APIError::ChannelUnavailable{err}) = err {
5093 assert_eq!(err, "Cannot send less than their minimum HTLC value");
5100 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
5101 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
5102 //It is enforced when constructing a route.
5103 let mut nodes = create_network(2, &[None, None]);
5104 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, LocalFeatures::new(), LocalFeatures::new());
5105 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
5106 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5108 let err = nodes[0].node.send_payment(route, our_payment_hash);
5110 if let Err(APIError::RouteError{err}) = err {
5111 assert_eq!(err, "Channel CLTV overflowed?!");
5118 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
5119 //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.
5120 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
5121 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
5122 let mut nodes = create_network(2, &[None, None]);
5123 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, LocalFeatures::new(), LocalFeatures::new());
5124 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
5126 for i in 0..max_accepted_htlcs {
5127 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5128 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5129 let payment_event = {
5130 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5131 check_added_monitors!(nodes[0], 1);
5133 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5134 assert_eq!(events.len(), 1);
5135 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
5136 assert_eq!(htlcs[0].htlc_id, i);
5140 SendEvent::from_event(events.remove(0))
5142 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5143 check_added_monitors!(nodes[1], 0);
5144 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5146 expect_pending_htlcs_forwardable!(nodes[1]);
5147 expect_payment_received!(nodes[1], our_payment_hash, 100000);
5149 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
5150 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5151 let err = nodes[0].node.send_payment(route, our_payment_hash);
5153 if let Err(APIError::ChannelUnavailable{err}) = err {
5154 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
5161 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
5162 //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.
5163 let mut nodes = create_network(2, &[None, None]);
5164 let channel_value = 100000;
5165 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, LocalFeatures::new(), LocalFeatures::new());
5166 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
5168 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
5170 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
5171 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5172 let err = nodes[0].node.send_payment(route, our_payment_hash);
5174 if let Err(APIError::ChannelUnavailable{err}) = err {
5175 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept");
5180 send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
5183 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
5185 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
5186 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
5187 let mut nodes = create_network(2, &[None, None]);
5188 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5189 let htlc_minimum_msat: u64;
5191 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
5192 let channel = chan_lock.by_id.get(&chan.2).unwrap();
5193 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
5195 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
5196 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5197 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5198 check_added_monitors!(nodes[0], 1);
5199 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5200 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
5201 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5202 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5203 assert_eq!(err, "Remote side tried to send less than our minimum HTLC value");
5207 assert!(nodes[1].node.list_channels().is_empty());
5208 check_closed_broadcast!(nodes[1]);
5212 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
5213 //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
5214 let mut nodes = create_network(2, &[None, None]);
5215 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5217 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
5219 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
5220 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5221 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5222 check_added_monitors!(nodes[0], 1);
5223 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5225 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
5226 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5228 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5229 assert_eq!(err, "Remote HTLC add would put them over their reserve value");
5234 assert!(nodes[1].node.list_channels().is_empty());
5235 check_closed_broadcast!(nodes[1]);
5239 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
5240 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
5241 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
5242 let mut nodes = create_network(2, &[None, None]);
5243 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5244 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
5245 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5247 let session_priv = SecretKey::from_slice(&{
5248 let mut session_key = [0; 32];
5249 let mut rng = thread_rng();
5250 rng.fill_bytes(&mut session_key);
5252 }).expect("RNG is bad!");
5254 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5255 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
5256 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
5257 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
5259 let mut msg = msgs::UpdateAddHTLC {
5263 payment_hash: our_payment_hash,
5264 cltv_expiry: htlc_cltv,
5265 onion_routing_packet: onion_packet.clone(),
5268 for i in 0..super::channel::OUR_MAX_HTLCS {
5269 msg.htlc_id = i as u64;
5270 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).unwrap();
5272 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
5273 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
5275 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5276 assert_eq!(err, "Remote tried to push more than our max accepted HTLCs");
5281 assert!(nodes[1].node.list_channels().is_empty());
5282 check_closed_broadcast!(nodes[1]);
5286 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
5287 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
5288 let mut nodes = create_network(2, &[None, None]);
5289 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5290 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5291 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5292 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5293 check_added_monitors!(nodes[0], 1);
5294 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5295 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
5296 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5298 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5299 assert_eq!(err,"Remote HTLC add would put them over our max HTLC value");
5304 assert!(nodes[1].node.list_channels().is_empty());
5305 check_closed_broadcast!(nodes[1]);
5309 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
5310 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
5311 let mut nodes = create_network(2, &[None, None]);
5312 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, LocalFeatures::new(), LocalFeatures::new());
5313 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, 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 mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5318 updates.update_add_htlcs[0].cltv_expiry = 500000000;
5319 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5321 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5322 assert_eq!(err,"Remote provided CLTV expiry in seconds instead of block height");
5327 assert!(nodes[1].node.list_channels().is_empty());
5328 check_closed_broadcast!(nodes[1]);
5332 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5333 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5334 // We test this by first testing that that repeated HTLCs pass commitment signature checks
5335 // after disconnect and that non-sequential htlc_ids result in a channel failure.
5336 let mut nodes = create_network(2, &[None, None]);
5337 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5338 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5339 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5340 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5341 check_added_monitors!(nodes[0], 1);
5342 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5343 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5345 //Disconnect and Reconnect
5346 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5347 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5348 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5349 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5350 assert_eq!(reestablish_1.len(), 1);
5351 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5352 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5353 assert_eq!(reestablish_2.len(), 1);
5354 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
5355 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5356 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
5357 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5360 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5361 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5362 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5363 check_added_monitors!(nodes[1], 1);
5364 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5366 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5367 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5368 assert_eq!(err, "Remote skipped HTLC ID");
5373 assert!(nodes[1].node.list_channels().is_empty());
5374 check_closed_broadcast!(nodes[1]);
5378 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5379 //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.
5381 let mut nodes = create_network(2, &[None, None]);
5382 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5384 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5385 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5386 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5387 check_added_monitors!(nodes[0], 1);
5388 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5389 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5391 let update_msg = msgs::UpdateFulfillHTLC{
5394 payment_preimage: our_payment_preimage,
5397 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5399 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5400 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5405 assert!(nodes[0].node.list_channels().is_empty());
5406 check_closed_broadcast!(nodes[0]);
5410 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5411 //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.
5413 let mut nodes = create_network(2, &[None, None]);
5414 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5416 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5417 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5418 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5419 check_added_monitors!(nodes[0], 1);
5420 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5421 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5423 let update_msg = msgs::UpdateFailHTLC{
5426 reason: msgs::OnionErrorPacket { data: Vec::new()},
5429 let err = nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5431 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5432 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5437 assert!(nodes[0].node.list_channels().is_empty());
5438 check_closed_broadcast!(nodes[0]);
5442 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5443 //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.
5445 let mut nodes = create_network(2, &[None, None]);
5446 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5448 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5449 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5450 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5451 check_added_monitors!(nodes[0], 1);
5452 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5453 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5455 let update_msg = msgs::UpdateFailMalformedHTLC{
5458 sha256_of_onion: [1; 32],
5459 failure_code: 0x8000,
5462 let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5464 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5465 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5470 assert!(nodes[0].node.list_channels().is_empty());
5471 check_closed_broadcast!(nodes[0]);
5475 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
5476 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
5478 let nodes = create_network(2, &[None, None]);
5479 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5481 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5483 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
5484 check_added_monitors!(nodes[1], 1);
5486 let events = nodes[1].node.get_and_clear_pending_msg_events();
5487 assert_eq!(events.len(), 1);
5488 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5490 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, .. } } => {
5491 assert!(update_add_htlcs.is_empty());
5492 assert_eq!(update_fulfill_htlcs.len(), 1);
5493 assert!(update_fail_htlcs.is_empty());
5494 assert!(update_fail_malformed_htlcs.is_empty());
5495 assert!(update_fee.is_none());
5496 update_fulfill_htlcs[0].clone()
5498 _ => panic!("Unexpected event"),
5502 update_fulfill_msg.htlc_id = 1;
5504 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5505 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5506 assert_eq!(err, "Remote tried to fulfill/fail an HTLC we couldn't find");
5511 assert!(nodes[0].node.list_channels().is_empty());
5512 check_closed_broadcast!(nodes[0]);
5516 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
5517 //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.
5519 let nodes = create_network(2, &[None, None]);
5520 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5522 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5524 nodes[1].node.claim_funds(our_payment_preimage, 100_000);
5525 check_added_monitors!(nodes[1], 1);
5527 let events = nodes[1].node.get_and_clear_pending_msg_events();
5528 assert_eq!(events.len(), 1);
5529 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5531 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, .. } } => {
5532 assert!(update_add_htlcs.is_empty());
5533 assert_eq!(update_fulfill_htlcs.len(), 1);
5534 assert!(update_fail_htlcs.is_empty());
5535 assert!(update_fail_malformed_htlcs.is_empty());
5536 assert!(update_fee.is_none());
5537 update_fulfill_htlcs[0].clone()
5539 _ => panic!("Unexpected event"),
5543 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
5545 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5546 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5547 assert_eq!(err, "Remote tried to fulfill HTLC with an incorrect preimage");
5552 assert!(nodes[0].node.list_channels().is_empty());
5553 check_closed_broadcast!(nodes[0]);
5558 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
5559 //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.
5561 let mut nodes = create_network(2, &[None, None]);
5562 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5563 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5564 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5565 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5566 check_added_monitors!(nodes[0], 1);
5568 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5569 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5571 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5572 check_added_monitors!(nodes[1], 0);
5573 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
5575 let events = nodes[1].node.get_and_clear_pending_msg_events();
5577 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
5579 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, .. } } => {
5580 assert!(update_add_htlcs.is_empty());
5581 assert!(update_fulfill_htlcs.is_empty());
5582 assert!(update_fail_htlcs.is_empty());
5583 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5584 assert!(update_fee.is_none());
5585 update_fail_malformed_htlcs[0].clone()
5587 _ => panic!("Unexpected event"),
5590 update_msg.failure_code &= !0x8000;
5591 let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5592 if let Err(msgs::LightningError{err, action: msgs::ErrorAction::SendErrorMessage {..}}) = err {
5593 assert_eq!(err, "Got update_fail_malformed_htlc with BADONION not set");
5598 assert!(nodes[0].node.list_channels().is_empty());
5599 check_closed_broadcast!(nodes[0]);
5603 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
5604 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
5605 // * 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.
5607 let mut nodes = create_network(3, &[None, None, None]);
5608 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5609 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
5611 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
5612 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5615 let mut payment_event = {
5616 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5617 check_added_monitors!(nodes[0], 1);
5618 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5619 assert_eq!(events.len(), 1);
5620 SendEvent::from_event(events.remove(0))
5622 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5623 check_added_monitors!(nodes[1], 0);
5624 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5625 expect_pending_htlcs_forwardable!(nodes[1]);
5626 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
5627 assert_eq!(events_2.len(), 1);
5628 check_added_monitors!(nodes[1], 1);
5629 payment_event = SendEvent::from_event(events_2.remove(0));
5630 assert_eq!(payment_event.msgs.len(), 1);
5633 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5634 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5635 check_added_monitors!(nodes[2], 0);
5636 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
5638 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
5639 assert_eq!(events_3.len(), 1);
5640 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
5642 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 } } => {
5643 assert!(update_add_htlcs.is_empty());
5644 assert!(update_fulfill_htlcs.is_empty());
5645 assert!(update_fail_htlcs.is_empty());
5646 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5647 assert!(update_fee.is_none());
5648 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
5650 _ => panic!("Unexpected event"),
5654 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0).unwrap();
5656 check_added_monitors!(nodes[1], 0);
5657 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
5658 expect_pending_htlcs_forwardable!(nodes[1]);
5659 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
5660 assert_eq!(events_4.len(), 1);
5662 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
5664 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, .. } } => {
5665 assert!(update_add_htlcs.is_empty());
5666 assert!(update_fulfill_htlcs.is_empty());
5667 assert_eq!(update_fail_htlcs.len(), 1);
5668 assert!(update_fail_malformed_htlcs.is_empty());
5669 assert!(update_fee.is_none());
5671 _ => panic!("Unexpected event"),
5674 check_added_monitors!(nodes[1], 1);
5677 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
5678 // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
5679 // 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
5680 // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
5682 let nodes = create_network(2, &[None, None]);
5683 let chan =create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5685 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5687 // We route 2 dust-HTLCs between A and B
5688 let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5689 let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5690 route_payment(&nodes[0], &[&nodes[1]], 1000000);
5692 // Cache one local commitment tx as previous
5693 let as_prev_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5695 // Fail one HTLC to prune it in the will-be-latest-local commitment tx
5696 assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2));
5697 check_added_monitors!(nodes[1], 0);
5698 expect_pending_htlcs_forwardable!(nodes[1]);
5699 check_added_monitors!(nodes[1], 1);
5701 let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5702 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]).unwrap();
5703 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed).unwrap();
5704 check_added_monitors!(nodes[0], 1);
5706 // Cache one local commitment tx as lastest
5707 let as_last_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5709 let events = nodes[0].node.get_and_clear_pending_msg_events();
5711 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
5712 assert_eq!(node_id, nodes[1].node.get_our_node_id());
5714 _ => panic!("Unexpected event"),
5717 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
5718 assert_eq!(node_id, nodes[1].node.get_our_node_id());
5720 _ => panic!("Unexpected event"),
5723 assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
5724 // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
5725 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5727 if announce_latest {
5728 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
5730 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
5733 let events = nodes[0].node.get_and_clear_pending_msg_events();
5734 assert_eq!(events.len(), 1);
5736 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5737 _ => panic!("Unexpected event"),
5740 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5741 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
5742 let events = nodes[0].node.get_and_clear_pending_events();
5743 // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
5744 assert_eq!(events.len(), 2);
5745 let mut first_failed = false;
5746 for event in events {
5748 Event::PaymentFailed { payment_hash, .. } => {
5749 if payment_hash == payment_hash_1 {
5750 assert!(!first_failed);
5751 first_failed = true;
5753 assert_eq!(payment_hash, payment_hash_2);
5756 _ => panic!("Unexpected event"),
5762 fn test_failure_delay_dust_htlc_local_commitment() {
5763 do_test_failure_delay_dust_htlc_local_commitment(true);
5764 do_test_failure_delay_dust_htlc_local_commitment(false);
5768 fn test_no_failure_dust_htlc_local_commitment() {
5769 // Transaction filters for failing back dust htlc based on local commitment txn infos has been
5770 // prone to error, we test here that a dummy transaction don't fail them.
5772 let nodes = create_network(2, &[None, None]);
5773 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5776 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5778 let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5779 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5781 // We route 2 dust-HTLCs between A and B
5782 let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5783 let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
5785 // Build a dummy invalid transaction trying to spend a commitment tx
5787 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
5788 script_sig: Script::new(),
5790 witness: Vec::new(),
5794 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
5798 let dummy_tx = Transaction {
5805 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5806 nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
5807 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5808 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5809 // We broadcast a few more block to check everything is all right
5810 connect_blocks(&nodes[0].block_notifier, 20, 1, true, header.bitcoin_hash());
5811 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5812 assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
5814 claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
5815 claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
5818 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
5819 // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
5820 // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
5821 // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
5822 // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
5823 // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
5824 // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
5826 let nodes = create_network(3, &[None, None, None]);
5827 let chan = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
5829 let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5831 let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
5832 let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5834 let as_commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5835 let bs_commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
5837 // We revoked bs_commitment_tx
5839 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
5840 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
5843 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5844 let mut timeout_tx = Vec::new();
5846 // We fail dust-HTLC 1 by broadcast of local commitment tx
5847 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
5848 let events = nodes[0].node.get_and_clear_pending_msg_events();
5849 assert_eq!(events.len(), 1);
5851 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5852 _ => panic!("Unexpected event"),
5854 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5855 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5856 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5857 let events = nodes[0].node.get_and_clear_pending_events();
5858 assert_eq!(events.len(), 1);
5860 Event::PaymentFailed { payment_hash, .. } => {
5861 assert_eq!(payment_hash, dust_hash);
5863 _ => panic!("Unexpected event"),
5865 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5866 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
5867 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5868 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5869 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
5870 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5871 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5872 let events = nodes[0].node.get_and_clear_pending_events();
5873 assert_eq!(events.len(), 1);
5875 Event::PaymentFailed { payment_hash, .. } => {
5876 assert_eq!(payment_hash, non_dust_hash);
5878 _ => panic!("Unexpected event"),
5881 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
5882 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
5883 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5884 let events = nodes[0].node.get_and_clear_pending_msg_events();
5885 assert_eq!(events.len(), 1);
5887 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5888 _ => panic!("Unexpected event"),
5890 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
5891 let parent_hash = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
5892 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5894 let events = nodes[0].node.get_and_clear_pending_events();
5895 assert_eq!(events.len(), 1);
5897 Event::PaymentFailed { payment_hash, .. } => {
5898 assert_eq!(payment_hash, dust_hash);
5900 _ => panic!("Unexpected event"),
5902 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
5903 // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
5904 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
5905 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
5906 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5907 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
5908 let events = nodes[0].node.get_and_clear_pending_events();
5909 assert_eq!(events.len(), 1);
5911 Event::PaymentFailed { payment_hash, .. } => {
5912 assert_eq!(payment_hash, non_dust_hash);
5914 _ => panic!("Unexpected event"),
5917 // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
5919 let events = nodes[0].node.get_and_clear_pending_events();
5920 assert_eq!(events.len(), 2);
5923 Event::PaymentFailed { payment_hash, .. } => {
5924 if payment_hash == dust_hash { first = true; }
5925 else { first = false; }
5927 _ => panic!("Unexpected event"),
5930 Event::PaymentFailed { payment_hash, .. } => {
5931 if first { assert_eq!(payment_hash, non_dust_hash); }
5932 else { assert_eq!(payment_hash, dust_hash); }
5934 _ => panic!("Unexpected event"),
5941 fn test_sweep_outbound_htlc_failure_update() {
5942 do_test_sweep_outbound_htlc_failure_update(false, true);
5943 do_test_sweep_outbound_htlc_failure_update(false, false);
5944 do_test_sweep_outbound_htlc_failure_update(true, false);
5948 fn test_upfront_shutdown_script() {
5949 // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
5950 // enforce it at shutdown message
5952 let mut config = UserConfig::default();
5953 config.channel_options.announced_channel = true;
5954 config.peer_channel_config_limits.force_announced_channel_preference = false;
5955 config.channel_options.commit_upfront_shutdown_pubkey = false;
5956 let cfgs = [None, Some(config), None];
5957 let nodes = create_network(3, &cfgs);
5959 // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
5960 let flags = LocalFeatures::new();
5961 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5962 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5963 let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5964 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
5965 // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that we disconnect peer
5966 if let Err(error) = nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown) {
5967 match error.action {
5968 ErrorAction::SendErrorMessage { msg } => {
5969 assert_eq!(msg.data,"Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
5971 _ => { assert!(false); }
5973 } else { assert!(false); }
5974 let events = nodes[2].node.get_and_clear_pending_msg_events();
5975 assert_eq!(events.len(), 1);
5977 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
5978 _ => panic!("Unexpected event"),
5981 // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
5982 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
5983 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
5984 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
5985 // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
5986 if let Ok(_) = nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown) {}
5987 else { assert!(false) }
5988 let events = nodes[2].node.get_and_clear_pending_msg_events();
5989 assert_eq!(events.len(), 1);
5991 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
5992 _ => panic!("Unexpected event"),
5995 // We test that if case of peer non-signaling we don't enforce committed script at channel opening
5996 let mut flags_no = LocalFeatures::new();
5997 flags_no.unset_upfront_shutdown_script();
5998 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
5999 nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6000 let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6001 node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6002 if let Ok(_) = nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown) {}
6003 else { assert!(false) }
6004 let events = nodes[1].node.get_and_clear_pending_msg_events();
6005 assert_eq!(events.len(), 1);
6007 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6008 _ => panic!("Unexpected event"),
6011 // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6012 // channel smoothly, opt-out is from channel initiator here
6013 let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6014 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6015 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6016 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6017 if let Ok(_) = nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown) {}
6018 else { assert!(false) }
6019 let events = nodes[0].node.get_and_clear_pending_msg_events();
6020 assert_eq!(events.len(), 1);
6022 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6023 _ => panic!("Unexpected event"),
6026 //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6027 //// channel smoothly
6028 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6029 nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6030 let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6031 node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6032 if let Ok(_) = nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown) {}
6033 else { assert!(false) }
6034 let events = nodes[0].node.get_and_clear_pending_msg_events();
6035 assert_eq!(events.len(), 2);
6037 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6038 _ => panic!("Unexpected event"),
6041 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6042 _ => panic!("Unexpected event"),
6047 fn test_user_configurable_csv_delay() {
6048 // We test our channel constructors yield errors when we pass them absurd csv delay
6050 let mut low_our_to_self_config = UserConfig::default();
6051 low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6052 let mut high_their_to_self_config = UserConfig::default();
6053 high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6054 let cfgs = [Some(high_their_to_self_config.clone()), None];
6055 let nodes = create_network(2, &cfgs);
6057 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6058 let keys_manager: Arc<KeysInterface> = Arc::new(KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new()), 10, 20));
6059 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) {
6061 APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6062 _ => panic!("Unexpected event"),
6064 } else { assert!(false) }
6066 // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
6067 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
6068 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6069 open_channel.to_self_delay = 200;
6070 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) {
6072 ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6073 _ => panic!("Unexpected event"),
6075 } else { assert!(false); }
6077 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
6078 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
6079 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();
6080 let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
6081 accept_channel.to_self_delay = 200;
6082 if let Err(error) = nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), LocalFeatures::new(), &accept_channel) {
6083 match error.action {
6084 ErrorAction::SendErrorMessage { msg } => {
6085 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
6087 _ => { assert!(false); }
6089 } else { assert!(false); }
6091 // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
6092 nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42).unwrap();
6093 let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
6094 open_channel.to_self_delay = 200;
6095 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) {
6097 ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
6098 _ => panic!("Unexpected event"),
6100 } else { assert!(false); }
6104 fn test_data_loss_protect() {
6105 // We want to be sure that :
6106 // * we don't broadcast our Local Commitment Tx in case of fallen behind
6107 // * we close channel in case of detecting other being fallen behind
6108 // * we are able to claim our own outputs thanks to remote my_current_per_commitment_point
6109 let mut nodes = create_network(2, &[None, None]);
6111 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, LocalFeatures::new(), LocalFeatures::new());
6113 // Cache node A state before any channel update
6114 let previous_node_state = nodes[0].node.encode();
6115 let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
6116 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
6118 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6119 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6121 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6122 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6124 // Restore node A from previous state
6125 let logger: Arc<Logger> = Arc::new(test_utils::TestLogger::with_id(format!("node {}", 0)));
6126 let chan_monitor = <(Sha256dHash, ChannelMonitor)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0), Arc::clone(&logger)).unwrap().1;
6127 let chain_monitor = Arc::new(ChainWatchInterfaceUtil::new(Network::Testnet, Arc::clone(&logger)));
6128 let tx_broadcaster = Arc::new(test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())});
6129 let feeest = Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 });
6130 let monitor = Arc::new(test_utils::TestChannelMonitor::new(chain_monitor.clone(), tx_broadcaster.clone(), logger.clone(), feeest.clone()));
6131 let mut channel_monitors = HashMap::new();
6132 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &chan_monitor);
6133 let node_state_0 = <(Sha256dHash, ChannelManager)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
6134 keys_manager: Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::clone(&logger), 42, 21)),
6135 fee_estimator: feeest.clone(),
6136 monitor: monitor.clone(),
6137 logger: Arc::clone(&logger),
6139 default_config: UserConfig::default(),
6140 channel_monitors: &channel_monitors
6142 nodes[0].node = Arc::new(node_state_0);
6143 assert!(monitor.add_update_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor.clone()).is_ok());
6144 nodes[0].chan_monitor = monitor;
6145 nodes[0].chain_monitor = chain_monitor;
6147 let weak_res = Arc::downgrade(&nodes[0].chan_monitor.simple_monitor);
6148 nodes[0].block_notifier.register_listener(weak_res);
6149 let weak_res = Arc::downgrade(&nodes[0].node);
6150 nodes[0].block_notifier.register_listener(weak_res);
6152 check_added_monitors!(nodes[0], 1);
6154 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
6155 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
6157 let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6159 // Check we update monitor following learning of per_commitment_point from B
6160 if let Err(err) = nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]) {
6162 ErrorAction::SendErrorMessage { msg } => {
6163 assert_eq!(msg.data, "We have fallen behind - we have received proof that if we broadcast remote is going to claim our funds - we can't do any automated broadcasting");
6165 _ => panic!("Unexpected event!"),
6167 } else { assert!(false); }
6168 check_added_monitors!(nodes[0], 1);
6171 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6172 assert_eq!(node_txn.len(), 0);
6175 let mut reestablish_1 = Vec::with_capacity(1);
6176 for msg in nodes[0].node.get_and_clear_pending_msg_events() {
6177 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
6178 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
6179 reestablish_1.push(msg.clone());
6180 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
6182 panic!("Unexpected event")
6186 // Check we close channel detecting A is fallen-behind
6187 if let Err(err) = nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]) {
6189 ErrorAction::SendErrorMessage { msg } => {
6190 assert_eq!(msg.data, "Peer attempted to reestablish channel with a very old local commitment transaction"); },
6191 _ => panic!("Unexpected event!"),
6193 } else { assert!(false); }
6195 let events = nodes[1].node.get_and_clear_pending_msg_events();
6196 assert_eq!(events.len(), 1);
6198 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
6199 _ => panic!("Unexpected event"),
6202 // Check A is able to claim to_remote output
6203 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
6204 assert_eq!(node_txn.len(), 1);
6205 check_spends!(node_txn[0], chan.3.clone());
6206 assert_eq!(node_txn[0].output.len(), 2);
6207 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
6208 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 1);
6209 let spend_txn = check_spendable_outputs!(nodes[0], 1);
6210 assert_eq!(spend_txn.len(), 1);
6211 check_spends!(spend_txn[0], node_txn[0].clone());
6215 fn test_check_htlc_underpaying() {
6216 // Send payment through A -> B but A is maliciously
6217 // sending a probe payment (i.e less than expected value0
6218 // to B, B should refuse payment.
6220 let nodes = create_network(2, &[None, None, None]);
6222 // Create some initial channels
6223 create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new());
6225 let (payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
6227 // Node 3 is expecting payment of 100_000 but receive 10_000,
6228 // fail htlc like we didn't know the preimage.
6229 nodes[1].node.claim_funds(payment_preimage, 100_000);
6230 nodes[1].node.process_pending_htlc_forwards();
6232 let events = nodes[1].node.get_and_clear_pending_msg_events();
6233 assert_eq!(events.len(), 1);
6234 let (update_fail_htlc, commitment_signed) = match events[0] {
6235 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 } } => {
6236 assert!(update_add_htlcs.is_empty());
6237 assert!(update_fulfill_htlcs.is_empty());
6238 assert_eq!(update_fail_htlcs.len(), 1);
6239 assert!(update_fail_malformed_htlcs.is_empty());
6240 assert!(update_fee.is_none());
6241 (update_fail_htlcs[0].clone(), commitment_signed)
6243 _ => panic!("Unexpected event"),
6245 check_added_monitors!(nodes[1], 1);
6247 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc).unwrap();
6248 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
6250 let events = nodes[0].node.get_and_clear_pending_events();
6251 assert_eq!(events.len(), 1);
6252 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
6253 assert_eq!(*rejected_by_dest, true);
6254 assert_eq!(error_code.unwrap(), 0x4000|15);
6256 panic!("Unexpected event");
6258 nodes[1].node.get_and_clear_pending_events();
6262 fn test_announce_disable_channels() {
6263 // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
6264 // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
6266 let nodes = create_network(2, &[None, None]);
6268 let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()).0.contents.short_channel_id;
6269 let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, LocalFeatures::new(), LocalFeatures::new()).0.contents.short_channel_id;
6270 let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, LocalFeatures::new(), LocalFeatures::new()).0.contents.short_channel_id;
6273 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6274 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6276 nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
6277 nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
6278 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6279 assert_eq!(msg_events.len(), 3);
6280 for e in msg_events {
6282 MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
6283 let short_id = msg.contents.short_channel_id;
6284 // Check generated channel_update match list in PendingChannelUpdate
6285 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
6286 panic!("Generated ChannelUpdate for wrong chan!");
6289 _ => panic!("Unexpected event"),
6293 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
6294 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6295 assert_eq!(reestablish_1.len(), 3);
6296 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
6297 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6298 assert_eq!(reestablish_2.len(), 3);
6300 // Reestablish chan_1
6301 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
6302 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6303 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
6304 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6305 // Reestablish chan_2
6306 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]).unwrap();
6307 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6308 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]).unwrap();
6309 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6310 // Reestablish chan_3
6311 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]).unwrap();
6312 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6313 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]).unwrap();
6314 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6316 nodes[0].node.timer_chan_freshness_every_min();
6317 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
6318 assert_eq!(msg_events.len(), 0);