Remove SecretKey from DynamicOutputP2WSH descriptor
[rust-lightning] / lightning / src / ln / functional_tests.rs
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.
4
5 use chain::transaction::OutPoint;
6 use chain::keysinterface::{ChannelKeys, KeysInterface, SpendableOutputDescriptor};
7 use chain::chaininterface;
8 use chain::chaininterface::{ChainListener, ChainWatchInterfaceUtil, BlockNotifier};
9 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC};
10 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash, PaymentSecret, PaymentSendFailure, BREAKDOWN_TIMEOUT};
11 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ManyChannelMonitor, ANTI_REORG_DELAY};
12 use ln::channelmonitor;
13 use ln::channel::{Channel, ChannelError};
14 use ln::{chan_utils, onion_utils};
15 use routing::router::{Route, RouteHop, get_route};
16 use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
17 use ln::msgs;
18 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate, ErrorAction};
19 use util::enforcing_trait_impls::EnforcingChannelKeys;
20 use util::{byte_utils, test_utils};
21 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
22 use util::errors::APIError;
23 use util::ser::{Writeable, Writer, ReadableArgs, Readable};
24 use util::config::UserConfig;
25
26 use bitcoin::util::hash::BitcoinHash;
27 use bitcoin::hashes::sha256d::Hash as Sha256dHash;
28 use bitcoin::hash_types::{Txid, BlockHash};
29 use bitcoin::util::bip143;
30 use bitcoin::util::address::Address;
31 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
32 use bitcoin::blockdata::block::{Block, BlockHeader};
33 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType, OutPoint as BitcoinOutPoint};
34 use bitcoin::blockdata::script::{Builder, Script};
35 use bitcoin::blockdata::opcodes;
36 use bitcoin::blockdata::constants::genesis_block;
37 use bitcoin::network::constants::Network;
38
39 use bitcoin::hashes::sha256::Hash as Sha256;
40 use bitcoin::hashes::Hash;
41
42 use bitcoin::secp256k1::{Secp256k1, Message};
43 use bitcoin::secp256k1::key::{PublicKey,SecretKey};
44
45 use std::collections::{BTreeSet, HashMap, HashSet};
46 use std::default::Default;
47 use std::sync::{Arc, Mutex};
48 use std::sync::atomic::Ordering;
49 use std::{mem, io};
50
51 use rand::{thread_rng, Rng};
52
53 use ln::functional_test_utils::*;
54
55 #[test]
56 fn test_insane_channel_opens() {
57         // Stand up a network of 2 nodes
58         let chanmon_cfgs = create_chanmon_cfgs(2);
59         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
60         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
61         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
62
63         // Instantiate channel parameters where we push the maximum msats given our
64         // funding satoshis
65         let channel_value_sat = 31337; // same as funding satoshis
66         let channel_reserve_satoshis = Channel::<EnforcingChannelKeys>::get_remote_channel_reserve_satoshis(channel_value_sat);
67         let push_msat = (channel_value_sat - channel_reserve_satoshis) * 1000;
68
69         // Have node0 initiate a channel to node1 with aforementioned parameters
70         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_sat, push_msat, 42, None).unwrap();
71
72         // Extract the channel open message from node0 to node1
73         let open_channel_message = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
74
75         // Test helper that asserts we get the correct error string given a mutator
76         // that supposedly makes the channel open message insane
77         let insane_open_helper = |expected_error_str: &str, message_mutator: fn(msgs::OpenChannel) -> msgs::OpenChannel| {
78                 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &message_mutator(open_channel_message.clone()));
79                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
80                 assert_eq!(msg_events.len(), 1);
81                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
82                         match action {
83                                 &ErrorAction::SendErrorMessage { .. } => {
84                                         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), expected_error_str.to_string(), 1);
85                                 },
86                                 _ => panic!("unexpected event!"),
87                         }
88                 } else { assert!(false); }
89         };
90
91         use ln::channel::MAX_FUNDING_SATOSHIS;
92         use ln::channelmanager::MAX_LOCAL_BREAKDOWN_TIMEOUT;
93
94         // Test all mutations that would make the channel open message insane
95         insane_open_helper("funding value > 2^24", |mut msg| { msg.funding_satoshis = MAX_FUNDING_SATOSHIS; msg });
96
97         insane_open_helper("Bogus channel_reserve_satoshis", |mut msg| { msg.channel_reserve_satoshis = msg.funding_satoshis + 1; msg });
98
99         insane_open_helper("push_msat larger than funding value", |mut msg| { msg.push_msat = (msg.funding_satoshis - msg.channel_reserve_satoshis) * 1000 + 1; msg });
100
101         insane_open_helper("Peer never wants payout outputs?", |mut msg| { msg.dust_limit_satoshis = msg.funding_satoshis + 1 ; msg });
102
103         insane_open_helper("Bogus; channel reserve is less than dust limit", |mut msg| { msg.dust_limit_satoshis = msg.channel_reserve_satoshis + 1; msg });
104
105         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 });
106
107         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 });
108
109         insane_open_helper("0 max_accpted_htlcs makes for a useless channel", |mut msg| { msg.max_accepted_htlcs = 0; msg });
110
111         insane_open_helper("max_accpted_htlcs > 483", |mut msg| { msg.max_accepted_htlcs = 484; msg });
112 }
113
114 #[test]
115 fn test_async_inbound_update_fee() {
116         let chanmon_cfgs = create_chanmon_cfgs(2);
117         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
118         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
119         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
120         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
121         let logger = test_utils::TestLogger::new();
122         let channel_id = chan.2;
123
124         // balancing
125         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
126
127         // A                                        B
128         // update_fee                            ->
129         // send (1) commitment_signed            -.
130         //                                       <- update_add_htlc/commitment_signed
131         // send (2) RAA (awaiting remote revoke) -.
132         // (1) commitment_signed is delivered    ->
133         //                                       .- send (3) RAA (awaiting remote revoke)
134         // (2) RAA is delivered                  ->
135         //                                       .- send (4) commitment_signed
136         //                                       <- (3) RAA is delivered
137         // send (5) commitment_signed            -.
138         //                                       <- (4) commitment_signed is delivered
139         // send (6) RAA                          -.
140         // (5) commitment_signed is delivered    ->
141         //                                       <- RAA
142         // (6) RAA is delivered                  ->
143
144         // First nodes[0] generates an update_fee
145         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
146         check_added_monitors!(nodes[0], 1);
147
148         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
149         assert_eq!(events_0.len(), 1);
150         let (update_msg, commitment_signed) = match events_0[0] { // (1)
151                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
152                         (update_fee.as_ref(), commitment_signed)
153                 },
154                 _ => panic!("Unexpected event"),
155         };
156
157         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
158
159         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
160         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
161         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
162         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
163         check_added_monitors!(nodes[1], 1);
164
165         let payment_event = {
166                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
167                 assert_eq!(events_1.len(), 1);
168                 SendEvent::from_event(events_1.remove(0))
169         };
170         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
171         assert_eq!(payment_event.msgs.len(), 1);
172
173         // ...now when the messages get delivered everyone should be happy
174         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
175         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
176         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
177         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
178         check_added_monitors!(nodes[0], 1);
179
180         // deliver(1), generate (3):
181         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
182         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
183         // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
184         check_added_monitors!(nodes[1], 1);
185
186         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack); // deliver (2)
187         let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
188         assert!(bs_update.update_add_htlcs.is_empty()); // (4)
189         assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
190         assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
191         assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
192         assert!(bs_update.update_fee.is_none()); // (4)
193         check_added_monitors!(nodes[1], 1);
194
195         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack); // deliver (3)
196         let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
197         assert!(as_update.update_add_htlcs.is_empty()); // (5)
198         assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
199         assert!(as_update.update_fail_htlcs.is_empty()); // (5)
200         assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
201         assert!(as_update.update_fee.is_none()); // (5)
202         check_added_monitors!(nodes[0], 1);
203
204         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed); // deliver (4)
205         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
206         // only (6) so get_event_msg's assert(len == 1) passes
207         check_added_monitors!(nodes[0], 1);
208
209         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed); // deliver (5)
210         let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
211         check_added_monitors!(nodes[1], 1);
212
213         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
214         check_added_monitors!(nodes[0], 1);
215
216         let events_2 = nodes[0].node.get_and_clear_pending_events();
217         assert_eq!(events_2.len(), 1);
218         match events_2[0] {
219                 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
220                 _ => panic!("Unexpected event"),
221         }
222
223         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke); // deliver (6)
224         check_added_monitors!(nodes[1], 1);
225 }
226
227 #[test]
228 fn test_update_fee_unordered_raa() {
229         // Just the intro to the previous test followed by an out-of-order RAA (which caused a
230         // crash in an earlier version of the update_fee patch)
231         let chanmon_cfgs = create_chanmon_cfgs(2);
232         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
233         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
234         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
235         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
236         let channel_id = chan.2;
237         let logger = test_utils::TestLogger::new();
238
239         // balancing
240         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
241
242         // First nodes[0] generates an update_fee
243         nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
244         check_added_monitors!(nodes[0], 1);
245
246         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
247         assert_eq!(events_0.len(), 1);
248         let update_msg = match events_0[0] { // (1)
249                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
250                         update_fee.as_ref()
251                 },
252                 _ => panic!("Unexpected event"),
253         };
254
255         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
256
257         // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
258         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
259         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
260         nodes[1].node.send_payment(&get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap(), our_payment_hash, &None).unwrap();
261         check_added_monitors!(nodes[1], 1);
262
263         let payment_event = {
264                 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
265                 assert_eq!(events_1.len(), 1);
266                 SendEvent::from_event(events_1.remove(0))
267         };
268         assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
269         assert_eq!(payment_event.msgs.len(), 1);
270
271         // ...now when the messages get delivered everyone should be happy
272         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
273         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg); // (2)
274         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
275         // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
276         check_added_monitors!(nodes[0], 1);
277
278         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg); // deliver (2)
279         check_added_monitors!(nodes[1], 1);
280
281         // We can't continue, sadly, because our (1) now has a bogus signature
282 }
283
284 #[test]
285 fn test_multi_flight_update_fee() {
286         let chanmon_cfgs = create_chanmon_cfgs(2);
287         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
288         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
289         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
290         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
291         let channel_id = chan.2;
292
293         // A                                        B
294         // update_fee/commitment_signed          ->
295         //                                       .- send (1) RAA and (2) commitment_signed
296         // update_fee (never committed)          ->
297         // (3) update_fee                        ->
298         // We have to manually generate the above update_fee, it is allowed by the protocol but we
299         // don't track which updates correspond to which revoke_and_ack responses so we're in
300         // AwaitingRAA mode and will not generate the update_fee yet.
301         //                                       <- (1) RAA delivered
302         // (3) is generated and send (4) CS      -.
303         // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
304         // know the per_commitment_point to use for it.
305         //                                       <- (2) commitment_signed delivered
306         // revoke_and_ack                        ->
307         //                                          B should send no response here
308         // (4) commitment_signed delivered       ->
309         //                                       <- RAA/commitment_signed delivered
310         // revoke_and_ack                        ->
311
312         // First nodes[0] generates an update_fee
313         let initial_feerate = get_feerate!(nodes[0], channel_id);
314         nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
315         check_added_monitors!(nodes[0], 1);
316
317         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
318         assert_eq!(events_0.len(), 1);
319         let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
320                 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
321                         (update_fee.as_ref().unwrap(), commitment_signed)
322                 },
323                 _ => panic!("Unexpected event"),
324         };
325
326         // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
327         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1);
328         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1);
329         let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
330         check_added_monitors!(nodes[1], 1);
331
332         // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
333         // transaction:
334         nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
335         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
336         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
337
338         // Create the (3) update_fee message that nodes[0] will generate before it does...
339         let mut update_msg_2 = msgs::UpdateFee {
340                 channel_id: update_msg_1.channel_id.clone(),
341                 feerate_per_kw: (initial_feerate + 30) as u32,
342         };
343
344         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
345
346         update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
347         // Deliver (3)
348         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2);
349
350         // Deliver (1), generating (3) and (4)
351         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg);
352         let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
353         check_added_monitors!(nodes[0], 1);
354         assert!(as_second_update.update_add_htlcs.is_empty());
355         assert!(as_second_update.update_fulfill_htlcs.is_empty());
356         assert!(as_second_update.update_fail_htlcs.is_empty());
357         assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
358         // Check that the update_fee newly generated matches what we delivered:
359         assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
360         assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
361
362         // Deliver (2) commitment_signed
363         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
364         let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
365         check_added_monitors!(nodes[0], 1);
366         // No commitment_signed so get_event_msg's assert(len == 1) passes
367
368         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg);
369         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
370         check_added_monitors!(nodes[1], 1);
371
372         // Delever (4)
373         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed);
374         let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
375         check_added_monitors!(nodes[1], 1);
376
377         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke);
378         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
379         check_added_monitors!(nodes[0], 1);
380
381         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment);
382         let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
383         // No commitment_signed so get_event_msg's assert(len == 1) passes
384         check_added_monitors!(nodes[0], 1);
385
386         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke);
387         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
388         check_added_monitors!(nodes[1], 1);
389 }
390
391 #[test]
392 fn test_1_conf_open() {
393         // Previously, if the minium_depth config was set to 1, we'd never send a funding_locked. This
394         // tests that we properly send one in that case.
395         let mut alice_config = UserConfig::default();
396         alice_config.own_channel_config.minimum_depth = 1;
397         alice_config.channel_options.announced_channel = true;
398         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
399         let mut bob_config = UserConfig::default();
400         bob_config.own_channel_config.minimum_depth = 1;
401         bob_config.channel_options.announced_channel = true;
402         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
403         let chanmon_cfgs = create_chanmon_cfgs(2);
404         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
405         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[Some(alice_config), Some(bob_config)]);
406         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
407
408         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
409         assert!(nodes[0].chain_monitor.does_match_tx(&tx));
410         assert!(nodes[1].chain_monitor.does_match_tx(&tx));
411
412         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
413         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
414         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &get_event_msg!(nodes[1], MessageSendEvent::SendFundingLocked, nodes[0].node.get_our_node_id()));
415
416         nodes[0].block_notifier.block_connected_checked(&header, 1, &[&tx; 1], &[tx.version; 1]);
417         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
418         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
419
420         for node in nodes {
421                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
422                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
423                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
424         }
425 }
426
427 fn do_test_sanity_on_in_flight_opens(steps: u8) {
428         // Previously, we had issues deserializing channels when we hadn't connected the first block
429         // after creation. To catch that and similar issues, we lean on the Node::drop impl to test
430         // serialization round-trips and simply do steps towards opening a channel and then drop the
431         // Node objects.
432
433         let chanmon_cfgs = create_chanmon_cfgs(2);
434         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
435         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
436         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
437
438         if steps & 0b1000_0000 != 0{
439                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
440                 nodes[0].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
441                 nodes[1].block_notifier.block_connected_checked(&header, 1, &Vec::new(), &[0; 0]);
442         }
443
444         if steps & 0x0f == 0 { return; }
445         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 100000, 10001, 42, None).unwrap();
446         let open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
447
448         if steps & 0x0f == 1 { return; }
449         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &open_channel);
450         let accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
451
452         if steps & 0x0f == 2 { return; }
453         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
454
455         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&nodes[0], 100000, 42);
456
457         if steps & 0x0f == 3 { return; }
458         nodes[0].node.funding_transaction_generated(&temporary_channel_id, funding_output);
459         check_added_monitors!(nodes[0], 0);
460         let funding_created = get_event_msg!(nodes[0], MessageSendEvent::SendFundingCreated, nodes[1].node.get_our_node_id());
461
462         if steps & 0x0f == 4 { return; }
463         nodes[1].node.handle_funding_created(&nodes[0].node.get_our_node_id(), &funding_created);
464         {
465                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
466                 assert_eq!(added_monitors.len(), 1);
467                 assert_eq!(added_monitors[0].0, funding_output);
468                 added_monitors.clear();
469         }
470         let funding_signed = get_event_msg!(nodes[1], MessageSendEvent::SendFundingSigned, nodes[0].node.get_our_node_id());
471
472         if steps & 0x0f == 5 { return; }
473         nodes[0].node.handle_funding_signed(&nodes[1].node.get_our_node_id(), &funding_signed);
474         {
475                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
476                 assert_eq!(added_monitors.len(), 1);
477                 assert_eq!(added_monitors[0].0, funding_output);
478                 added_monitors.clear();
479         }
480
481         let events_4 = nodes[0].node.get_and_clear_pending_events();
482         assert_eq!(events_4.len(), 1);
483         match events_4[0] {
484                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
485                         assert_eq!(user_channel_id, 42);
486                         assert_eq!(*funding_txo, funding_output);
487                 },
488                 _ => panic!("Unexpected event"),
489         };
490
491         if steps & 0x0f == 6 { return; }
492         create_chan_between_nodes_with_value_confirm_first(&nodes[0], &nodes[1], &tx);
493
494         if steps & 0x0f == 7 { return; }
495         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
496         create_chan_between_nodes_with_value_confirm_second(&nodes[1], &nodes[0]);
497 }
498
499 #[test]
500 fn test_sanity_on_in_flight_opens() {
501         do_test_sanity_on_in_flight_opens(0);
502         do_test_sanity_on_in_flight_opens(0 | 0b1000_0000);
503         do_test_sanity_on_in_flight_opens(1);
504         do_test_sanity_on_in_flight_opens(1 | 0b1000_0000);
505         do_test_sanity_on_in_flight_opens(2);
506         do_test_sanity_on_in_flight_opens(2 | 0b1000_0000);
507         do_test_sanity_on_in_flight_opens(3);
508         do_test_sanity_on_in_flight_opens(3 | 0b1000_0000);
509         do_test_sanity_on_in_flight_opens(4);
510         do_test_sanity_on_in_flight_opens(4 | 0b1000_0000);
511         do_test_sanity_on_in_flight_opens(5);
512         do_test_sanity_on_in_flight_opens(5 | 0b1000_0000);
513         do_test_sanity_on_in_flight_opens(6);
514         do_test_sanity_on_in_flight_opens(6 | 0b1000_0000);
515         do_test_sanity_on_in_flight_opens(7);
516         do_test_sanity_on_in_flight_opens(7 | 0b1000_0000);
517         do_test_sanity_on_in_flight_opens(8);
518         do_test_sanity_on_in_flight_opens(8 | 0b1000_0000);
519 }
520
521 #[test]
522 fn test_update_fee_vanilla() {
523         let chanmon_cfgs = create_chanmon_cfgs(2);
524         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
525         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
526         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
527         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
528         let channel_id = chan.2;
529
530         let feerate = get_feerate!(nodes[0], channel_id);
531         nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
532         check_added_monitors!(nodes[0], 1);
533
534         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
535         assert_eq!(events_0.len(), 1);
536         let (update_msg, commitment_signed) = match events_0[0] {
537                         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 } } => {
538                         (update_fee.as_ref(), commitment_signed)
539                 },
540                 _ => panic!("Unexpected event"),
541         };
542         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
543
544         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
545         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
546         check_added_monitors!(nodes[1], 1);
547
548         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
549         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
550         check_added_monitors!(nodes[0], 1);
551
552         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
553         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
554         // No commitment_signed so get_event_msg's assert(len == 1) passes
555         check_added_monitors!(nodes[0], 1);
556
557         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
558         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
559         check_added_monitors!(nodes[1], 1);
560 }
561
562 #[test]
563 fn test_update_fee_that_funder_cannot_afford() {
564         let chanmon_cfgs = create_chanmon_cfgs(2);
565         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
566         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
567         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
568         let channel_value = 1888;
569         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000, InitFeatures::known(), InitFeatures::known());
570         let channel_id = chan.2;
571
572         let feerate = 260;
573         nodes[0].node.update_fee(channel_id, feerate).unwrap();
574         check_added_monitors!(nodes[0], 1);
575         let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
576
577         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap());
578
579         commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
580
581         //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
582         //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
583         {
584                 let commitment_tx = get_local_commitment_txn!(nodes[1], channel_id)[0].clone();
585
586                 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
587                 let num_htlcs = commitment_tx.output.len() - 2;
588                 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
589                 let mut actual_fee = commitment_tx.output.iter().fold(0, |acc, output| acc + output.value);
590                 actual_fee = channel_value - actual_fee;
591                 assert_eq!(total_fee, actual_fee);
592         }
593
594         //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
595         //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
596         nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
597         check_added_monitors!(nodes[0], 1);
598
599         let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
600
601         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap());
602
603         //While producing the commitment_signed response after handling a received update_fee request the
604         //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
605         //Should produce and error.
606         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed);
607         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Funding remote cannot afford proposed new fee".to_string(), 1);
608         check_added_monitors!(nodes[1], 1);
609         check_closed_broadcast!(nodes[1], true);
610 }
611
612 #[test]
613 fn test_update_fee_with_fundee_update_add_htlc() {
614         let chanmon_cfgs = create_chanmon_cfgs(2);
615         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
616         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
617         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
618         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
619         let channel_id = chan.2;
620         let logger = test_utils::TestLogger::new();
621
622         // balancing
623         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
624
625         let feerate = get_feerate!(nodes[0], channel_id);
626         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
627         check_added_monitors!(nodes[0], 1);
628
629         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
630         assert_eq!(events_0.len(), 1);
631         let (update_msg, commitment_signed) = match events_0[0] {
632                         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 } } => {
633                         (update_fee.as_ref(), commitment_signed)
634                 },
635                 _ => panic!("Unexpected event"),
636         };
637         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
638         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
639         let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
640         check_added_monitors!(nodes[1], 1);
641
642         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
643         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
644         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV, &logger).unwrap();
645
646         // nothing happens since node[1] is in AwaitingRemoteRevoke
647         nodes[1].node.send_payment(&route, our_payment_hash, &None).unwrap();
648         {
649                 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
650                 assert_eq!(added_monitors.len(), 0);
651                 added_monitors.clear();
652         }
653         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
654         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
655         // node[1] has nothing to do
656
657         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
658         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
659         check_added_monitors!(nodes[0], 1);
660
661         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
662         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
663         // No commitment_signed so get_event_msg's assert(len == 1) passes
664         check_added_monitors!(nodes[0], 1);
665         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
666         check_added_monitors!(nodes[1], 1);
667         // AwaitingRemoteRevoke ends here
668
669         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
670         assert_eq!(commitment_update.update_add_htlcs.len(), 1);
671         assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
672         assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
673         assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
674         assert_eq!(commitment_update.update_fee.is_none(), true);
675
676         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]);
677         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
678         check_added_monitors!(nodes[0], 1);
679         let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
680
681         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke);
682         check_added_monitors!(nodes[1], 1);
683         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
684
685         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed);
686         check_added_monitors!(nodes[1], 1);
687         let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
688         // No commitment_signed so get_event_msg's assert(len == 1) passes
689
690         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke);
691         check_added_monitors!(nodes[0], 1);
692         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
693
694         expect_pending_htlcs_forwardable!(nodes[0]);
695
696         let events = nodes[0].node.get_and_clear_pending_events();
697         assert_eq!(events.len(), 1);
698         match events[0] {
699                 Event::PaymentReceived { .. } => { },
700                 _ => panic!("Unexpected event"),
701         };
702
703         claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage, 800_000);
704
705         send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000, 800_000);
706         send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000, 800_000);
707         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
708 }
709
710 #[test]
711 fn test_update_fee() {
712         let chanmon_cfgs = create_chanmon_cfgs(2);
713         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
714         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
715         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
716         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
717         let channel_id = chan.2;
718
719         // A                                        B
720         // (1) update_fee/commitment_signed      ->
721         //                                       <- (2) revoke_and_ack
722         //                                       .- send (3) commitment_signed
723         // (4) update_fee/commitment_signed      ->
724         //                                       .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
725         //                                       <- (3) commitment_signed delivered
726         // send (6) revoke_and_ack               -.
727         //                                       <- (5) deliver revoke_and_ack
728         // (6) deliver revoke_and_ack            ->
729         //                                       .- send (7) commitment_signed in response to (4)
730         //                                       <- (7) deliver commitment_signed
731         // revoke_and_ack                        ->
732
733         // Create and deliver (1)...
734         let feerate = get_feerate!(nodes[0], channel_id);
735         nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
736         check_added_monitors!(nodes[0], 1);
737
738         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
739         assert_eq!(events_0.len(), 1);
740         let (update_msg, commitment_signed) = match events_0[0] {
741                         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 } } => {
742                         (update_fee.as_ref(), commitment_signed)
743                 },
744                 _ => panic!("Unexpected event"),
745         };
746         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
747
748         // Generate (2) and (3):
749         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
750         let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
751         check_added_monitors!(nodes[1], 1);
752
753         // Deliver (2):
754         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
755         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
756         check_added_monitors!(nodes[0], 1);
757
758         // Create and deliver (4)...
759         nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
760         check_added_monitors!(nodes[0], 1);
761         let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
762         assert_eq!(events_0.len(), 1);
763         let (update_msg, commitment_signed) = match events_0[0] {
764                         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 } } => {
765                         (update_fee.as_ref(), commitment_signed)
766                 },
767                 _ => panic!("Unexpected event"),
768         };
769
770         nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap());
771         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed);
772         check_added_monitors!(nodes[1], 1);
773         // ... creating (5)
774         let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
775         // No commitment_signed so get_event_msg's assert(len == 1) passes
776
777         // Handle (3), creating (6):
778         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0);
779         check_added_monitors!(nodes[0], 1);
780         let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
781         // No commitment_signed so get_event_msg's assert(len == 1) passes
782
783         // Deliver (5):
784         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg);
785         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
786         check_added_monitors!(nodes[0], 1);
787
788         // Deliver (6), creating (7):
789         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0);
790         let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
791         assert!(commitment_update.update_add_htlcs.is_empty());
792         assert!(commitment_update.update_fulfill_htlcs.is_empty());
793         assert!(commitment_update.update_fail_htlcs.is_empty());
794         assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
795         assert!(commitment_update.update_fee.is_none());
796         check_added_monitors!(nodes[1], 1);
797
798         // Deliver (7)
799         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed);
800         check_added_monitors!(nodes[0], 1);
801         let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
802         // No commitment_signed so get_event_msg's assert(len == 1) passes
803
804         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg);
805         check_added_monitors!(nodes[1], 1);
806         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
807
808         assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
809         assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
810         close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
811 }
812
813 #[test]
814 fn pre_funding_lock_shutdown_test() {
815         // Test sending a shutdown prior to funding_locked after funding generation
816         let chanmon_cfgs = create_chanmon_cfgs(2);
817         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
818         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
819         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
820         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0, InitFeatures::known(), InitFeatures::known());
821         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
822         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
823         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![tx.clone()]}, 1);
824
825         nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
826         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
827         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
828         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
829         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
830
831         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
832         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
833         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
834         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
835         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
836         assert!(node_0_none.is_none());
837
838         assert!(nodes[0].node.list_channels().is_empty());
839         assert!(nodes[1].node.list_channels().is_empty());
840 }
841
842 #[test]
843 fn updates_shutdown_wait() {
844         // Test sending a shutdown with outstanding updates pending
845         let chanmon_cfgs = create_chanmon_cfgs(3);
846         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
847         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
848         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
849         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
850         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
851         let logger = test_utils::TestLogger::new();
852
853         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
854
855         nodes[0].node.close_channel(&chan_1.2).unwrap();
856         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
857         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
858         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
859         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
860
861         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
862         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
863
864         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
865
866         let net_graph_msg_handler0 = &nodes[0].net_graph_msg_handler;
867         let net_graph_msg_handler1 = &nodes[1].net_graph_msg_handler;
868         let route_1 = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler0, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
869         let route_2 = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler1, &nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
870         unwrap_send_err!(nodes[0].node.send_payment(&route_1, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
871         unwrap_send_err!(nodes[1].node.send_payment(&route_2, payment_hash, &None), true, APIError::ChannelUnavailable {..}, {});
872
873         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
874         check_added_monitors!(nodes[2], 1);
875         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
876         assert!(updates.update_add_htlcs.is_empty());
877         assert!(updates.update_fail_htlcs.is_empty());
878         assert!(updates.update_fail_malformed_htlcs.is_empty());
879         assert!(updates.update_fee.is_none());
880         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
881         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
882         check_added_monitors!(nodes[1], 1);
883         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
884         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
885
886         assert!(updates_2.update_add_htlcs.is_empty());
887         assert!(updates_2.update_fail_htlcs.is_empty());
888         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
889         assert!(updates_2.update_fee.is_none());
890         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
891         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
892         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
893
894         let events = nodes[0].node.get_and_clear_pending_events();
895         assert_eq!(events.len(), 1);
896         match events[0] {
897                 Event::PaymentSent { ref payment_preimage } => {
898                         assert_eq!(our_payment_preimage, *payment_preimage);
899                 },
900                 _ => panic!("Unexpected event"),
901         }
902
903         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
904         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
905         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
906         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
907         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
908         assert!(node_0_none.is_none());
909
910         assert!(nodes[0].node.list_channels().is_empty());
911
912         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
913         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
914         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
915         assert!(nodes[1].node.list_channels().is_empty());
916         assert!(nodes[2].node.list_channels().is_empty());
917 }
918
919 #[test]
920 fn htlc_fail_async_shutdown() {
921         // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
922         let chanmon_cfgs = create_chanmon_cfgs(3);
923         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
924         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
925         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
926         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
927         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
928         let logger = test_utils::TestLogger::new();
929
930         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
931         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
932         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
933         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
934         check_added_monitors!(nodes[0], 1);
935         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
936         assert_eq!(updates.update_add_htlcs.len(), 1);
937         assert!(updates.update_fulfill_htlcs.is_empty());
938         assert!(updates.update_fail_htlcs.is_empty());
939         assert!(updates.update_fail_malformed_htlcs.is_empty());
940         assert!(updates.update_fee.is_none());
941
942         nodes[1].node.close_channel(&chan_1.2).unwrap();
943         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
944         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
945         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
946
947         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
948         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
949         check_added_monitors!(nodes[1], 1);
950         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
951         commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
952
953         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
954         assert!(updates_2.update_add_htlcs.is_empty());
955         assert!(updates_2.update_fulfill_htlcs.is_empty());
956         assert_eq!(updates_2.update_fail_htlcs.len(), 1);
957         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
958         assert!(updates_2.update_fee.is_none());
959
960         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]);
961         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
962
963         expect_payment_failed!(nodes[0], our_payment_hash, false);
964
965         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
966         assert_eq!(msg_events.len(), 2);
967         let node_0_closing_signed = match msg_events[0] {
968                 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
969                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
970                         (*msg).clone()
971                 },
972                 _ => panic!("Unexpected event"),
973         };
974         match msg_events[1] {
975                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
976                         assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
977                 },
978                 _ => panic!("Unexpected event"),
979         }
980
981         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
982         nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
983         let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
984         nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
985         let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
986         assert!(node_0_none.is_none());
987
988         assert!(nodes[0].node.list_channels().is_empty());
989
990         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
991         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
992         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
993         assert!(nodes[1].node.list_channels().is_empty());
994         assert!(nodes[2].node.list_channels().is_empty());
995 }
996
997 fn do_test_shutdown_rebroadcast(recv_count: u8) {
998         // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
999         // messages delivered prior to disconnect
1000         let chanmon_cfgs = create_chanmon_cfgs(3);
1001         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1002         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1003         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1004         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1005         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1006
1007         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
1008
1009         nodes[1].node.close_channel(&chan_1.2).unwrap();
1010         let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1011         if recv_count > 0 {
1012                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown);
1013                 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1014                 if recv_count > 1 {
1015                         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
1016                 }
1017         }
1018
1019         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1020         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1021
1022         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1023         let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1024         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1025         let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1026
1027         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish);
1028         let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1029         assert!(node_1_shutdown == node_1_2nd_shutdown);
1030
1031         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish);
1032         let node_0_2nd_shutdown = if recv_count > 0 {
1033                 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1034                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1035                 node_0_2nd_shutdown
1036         } else {
1037                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1038                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown);
1039                 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
1040         };
1041         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown);
1042
1043         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1044         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1045
1046         assert!(nodes[2].node.claim_funds(our_payment_preimage, &None, 100_000));
1047         check_added_monitors!(nodes[2], 1);
1048         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1049         assert!(updates.update_add_htlcs.is_empty());
1050         assert!(updates.update_fail_htlcs.is_empty());
1051         assert!(updates.update_fail_malformed_htlcs.is_empty());
1052         assert!(updates.update_fee.is_none());
1053         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1054         nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
1055         check_added_monitors!(nodes[1], 1);
1056         let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1057         commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
1058
1059         assert!(updates_2.update_add_htlcs.is_empty());
1060         assert!(updates_2.update_fail_htlcs.is_empty());
1061         assert!(updates_2.update_fail_malformed_htlcs.is_empty());
1062         assert!(updates_2.update_fee.is_none());
1063         assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
1064         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]);
1065         commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
1066
1067         let events = nodes[0].node.get_and_clear_pending_events();
1068         assert_eq!(events.len(), 1);
1069         match events[0] {
1070                 Event::PaymentSent { ref payment_preimage } => {
1071                         assert_eq!(our_payment_preimage, *payment_preimage);
1072                 },
1073                 _ => panic!("Unexpected event"),
1074         }
1075
1076         let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1077         if recv_count > 0 {
1078                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed);
1079                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1080                 assert!(node_1_closing_signed.is_some());
1081         }
1082
1083         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
1084         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
1085
1086         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1087         let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
1088         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
1089         if recv_count == 0 {
1090                 // If all closing_signeds weren't delivered we can just resume where we left off...
1091                 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
1092
1093                 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish);
1094                 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
1095                 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
1096
1097                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1098                 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
1099                 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
1100
1101                 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown);
1102                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1103
1104                 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown);
1105                 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
1106                 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
1107
1108                 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed);
1109                 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
1110                 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap());
1111                 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
1112                 assert!(node_0_none.is_none());
1113         } else {
1114                 // If one node, however, received + responded with an identical closing_signed we end
1115                 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
1116                 // There isn't really anything better we can do simply, but in the future we might
1117                 // explore storing a set of recently-closed channels that got disconnected during
1118                 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
1119                 // give our counterparty enough time to (potentially) broadcast a cooperative closing
1120                 // transaction.
1121                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1122
1123                 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish);
1124                 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
1125                 assert_eq!(msg_events.len(), 1);
1126                 if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
1127                         match action {
1128                                 &ErrorAction::SendErrorMessage { ref msg } => {
1129                                         nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
1130                                         assert_eq!(msg.channel_id, chan_1.2);
1131                                 },
1132                                 _ => panic!("Unexpected event!"),
1133                         }
1134                 } else { panic!("Needed SendErrorMessage close"); }
1135
1136                 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
1137                 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
1138                 // closing_signed so we do it ourselves
1139                 check_closed_broadcast!(nodes[0], false);
1140                 check_added_monitors!(nodes[0], 1);
1141         }
1142
1143         assert!(nodes[0].node.list_channels().is_empty());
1144
1145         assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
1146         nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
1147         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
1148         assert!(nodes[1].node.list_channels().is_empty());
1149         assert!(nodes[2].node.list_channels().is_empty());
1150 }
1151
1152 #[test]
1153 fn test_shutdown_rebroadcast() {
1154         do_test_shutdown_rebroadcast(0);
1155         do_test_shutdown_rebroadcast(1);
1156         do_test_shutdown_rebroadcast(2);
1157 }
1158
1159 #[test]
1160 fn fake_network_test() {
1161         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1162         // tests that payments get routed and transactions broadcast in semi-reasonable ways.
1163         let chanmon_cfgs = create_chanmon_cfgs(4);
1164         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
1165         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
1166         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
1167
1168         // Create some initial channels
1169         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1170         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1171         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1172
1173         // Rebalance the network a bit by relaying one payment through all the channels...
1174         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1175         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1176         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1177         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000, 8_000_000);
1178
1179         // Send some more payments
1180         send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000, 1_000_000);
1181         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000, 1_000_000);
1182         send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000, 1_000_000);
1183
1184         // Test failure packets
1185         let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
1186         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
1187
1188         // Add a new channel that skips 3
1189         let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1190
1191         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000, 1_000_000);
1192         send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000, 1_000_000);
1193         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1194         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1195         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1196         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1197         send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000, 8_000_000);
1198
1199         // Do some rebalance loop payments, simultaneously
1200         let mut hops = Vec::with_capacity(3);
1201         hops.push(RouteHop {
1202                 pubkey: nodes[2].node.get_our_node_id(),
1203                 node_features: NodeFeatures::empty(),
1204                 short_channel_id: chan_2.0.contents.short_channel_id,
1205                 channel_features: ChannelFeatures::empty(),
1206                 fee_msat: 0,
1207                 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
1208         });
1209         hops.push(RouteHop {
1210                 pubkey: nodes[3].node.get_our_node_id(),
1211                 node_features: NodeFeatures::empty(),
1212                 short_channel_id: chan_3.0.contents.short_channel_id,
1213                 channel_features: ChannelFeatures::empty(),
1214                 fee_msat: 0,
1215                 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
1216         });
1217         hops.push(RouteHop {
1218                 pubkey: nodes[1].node.get_our_node_id(),
1219                 node_features: NodeFeatures::empty(),
1220                 short_channel_id: chan_4.0.contents.short_channel_id,
1221                 channel_features: ChannelFeatures::empty(),
1222                 fee_msat: 1000000,
1223                 cltv_expiry_delta: TEST_FINAL_CLTV,
1224         });
1225         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;
1226         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;
1227         let payment_preimage_1 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
1228
1229         let mut hops = Vec::with_capacity(3);
1230         hops.push(RouteHop {
1231                 pubkey: nodes[3].node.get_our_node_id(),
1232                 node_features: NodeFeatures::empty(),
1233                 short_channel_id: chan_4.0.contents.short_channel_id,
1234                 channel_features: ChannelFeatures::empty(),
1235                 fee_msat: 0,
1236                 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1237         });
1238         hops.push(RouteHop {
1239                 pubkey: nodes[2].node.get_our_node_id(),
1240                 node_features: NodeFeatures::empty(),
1241                 short_channel_id: chan_3.0.contents.short_channel_id,
1242                 channel_features: ChannelFeatures::empty(),
1243                 fee_msat: 0,
1244                 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1245         });
1246         hops.push(RouteHop {
1247                 pubkey: nodes[1].node.get_our_node_id(),
1248                 node_features: NodeFeatures::empty(),
1249                 short_channel_id: chan_2.0.contents.short_channel_id,
1250                 channel_features: ChannelFeatures::empty(),
1251                 fee_msat: 1000000,
1252                 cltv_expiry_delta: TEST_FINAL_CLTV,
1253         });
1254         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;
1255         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;
1256         let payment_hash_2 = send_along_route(&nodes[1], Route { paths: vec![hops] }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1257
1258         // Claim the rebalances...
1259         fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1260         claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1, 1_000_000);
1261
1262         // Add a duplicate new channel from 2 to 4
1263         let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1264
1265         // Send some payments across both channels
1266         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1267         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1268         let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1269
1270
1271         route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1272         let events = nodes[0].node.get_and_clear_pending_msg_events();
1273         assert_eq!(events.len(), 0);
1274         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1275
1276         //TODO: Test that routes work again here as we've been notified that the channel is full
1277
1278         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3, 3_000_000);
1279         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4, 3_000_000);
1280         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5, 3_000_000);
1281
1282         // Close down the channels...
1283         close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1284         close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1285         close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1286         close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1287         close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1288 }
1289
1290 #[test]
1291 fn holding_cell_htlc_counting() {
1292         // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1293         // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1294         // commitment dance rounds.
1295         let chanmon_cfgs = create_chanmon_cfgs(3);
1296         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1297         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1298         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1299         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1300         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1301         let logger = test_utils::TestLogger::new();
1302
1303         let mut payments = Vec::new();
1304         for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1305                 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1306                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1307                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1308                 nodes[1].node.send_payment(&route, payment_hash, &None).unwrap();
1309                 payments.push((payment_preimage, payment_hash));
1310         }
1311         check_added_monitors!(nodes[1], 1);
1312
1313         let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1314         assert_eq!(events.len(), 1);
1315         let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1316         assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1317
1318         // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1319         // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1320         // another HTLC.
1321         let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1322         {
1323                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1324                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1325                 unwrap_send_err!(nodes[1].node.send_payment(&route, payment_hash_1, &None), true, APIError::ChannelUnavailable { err },
1326                         assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
1327                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1328                 nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
1329         }
1330
1331         // This should also be true if we try to forward a payment.
1332         let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1333         {
1334                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1335                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
1336                 nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
1337                 check_added_monitors!(nodes[0], 1);
1338         }
1339
1340         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1341         assert_eq!(events.len(), 1);
1342         let payment_event = SendEvent::from_event(events.pop().unwrap());
1343         assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1344
1345         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
1346         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1347         // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1348         // fails), the second will process the resulting failure and fail the HTLC backward.
1349         expect_pending_htlcs_forwardable!(nodes[1]);
1350         expect_pending_htlcs_forwardable!(nodes[1]);
1351         check_added_monitors!(nodes[1], 1);
1352
1353         let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1354         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]);
1355         commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1356
1357         let events = nodes[0].node.get_and_clear_pending_msg_events();
1358         assert_eq!(events.len(), 1);
1359         match events[0] {
1360                 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1361                         assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1362                 },
1363                 _ => panic!("Unexpected event"),
1364         }
1365
1366         expect_payment_failed!(nodes[0], payment_hash_2, false);
1367
1368         // Now forward all the pending HTLCs and claim them back
1369         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]);
1370         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg);
1371         check_added_monitors!(nodes[2], 1);
1372
1373         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1374         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1375         check_added_monitors!(nodes[1], 1);
1376         let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1377
1378         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1379         check_added_monitors!(nodes[1], 1);
1380         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1381
1382         for ref update in as_updates.update_add_htlcs.iter() {
1383                 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update);
1384         }
1385         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed);
1386         check_added_monitors!(nodes[2], 1);
1387         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
1388         check_added_monitors!(nodes[2], 1);
1389         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1390
1391         nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack);
1392         check_added_monitors!(nodes[1], 1);
1393         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed);
1394         check_added_monitors!(nodes[1], 1);
1395         let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1396
1397         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa);
1398         check_added_monitors!(nodes[2], 1);
1399
1400         expect_pending_htlcs_forwardable!(nodes[2]);
1401
1402         let events = nodes[2].node.get_and_clear_pending_events();
1403         assert_eq!(events.len(), payments.len());
1404         for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1405                 match event {
1406                         &Event::PaymentReceived { ref payment_hash, .. } => {
1407                                 assert_eq!(*payment_hash, *hash);
1408                         },
1409                         _ => panic!("Unexpected event"),
1410                 };
1411         }
1412
1413         for (preimage, _) in payments.drain(..) {
1414                 claim_payment(&nodes[1], &[&nodes[2]], preimage, 100_000);
1415         }
1416
1417         send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000, 1_000_000);
1418 }
1419
1420 #[test]
1421 fn duplicate_htlc_test() {
1422         // Test that we accept duplicate payment_hash HTLCs across the network and that
1423         // claiming/failing them are all separate and don't affect each other
1424         let chanmon_cfgs = create_chanmon_cfgs(6);
1425         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
1426         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
1427         let mut nodes = create_network(6, &node_cfgs, &node_chanmgrs);
1428
1429         // Create some initial channels to route via 3 to 4/5 from 0/1/2
1430         create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
1431         create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known());
1432         create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1433         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1434         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
1435
1436         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1437
1438         *nodes[0].network_payment_count.borrow_mut() -= 1;
1439         assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1440
1441         *nodes[0].network_payment_count.borrow_mut() -= 1;
1442         assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1443
1444         claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage, 1_000_000);
1445         fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1446         claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage, 1_000_000);
1447 }
1448
1449 #[test]
1450 fn test_duplicate_htlc_different_direction_onchain() {
1451         // Test that ChannelMonitor doesn't generate 2 preimage txn
1452         // when we have 2 HTLCs with same preimage that go across a node
1453         // in opposite directions.
1454         let chanmon_cfgs = create_chanmon_cfgs(2);
1455         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1456         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1457         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1458
1459         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1460         let logger = test_utils::TestLogger::new();
1461
1462         // balancing
1463         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
1464
1465         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 900_000);
1466
1467         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1468         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 800_000, TEST_FINAL_CLTV, &logger).unwrap();
1469         send_along_route_with_hash(&nodes[1], route, &vec!(&nodes[0])[..], 800_000, payment_hash);
1470
1471         // Provide preimage to node 0 by claiming payment
1472         nodes[0].node.claim_funds(payment_preimage, &None, 800_000);
1473         check_added_monitors!(nodes[0], 1);
1474
1475         // Broadcast node 1 commitment txn
1476         let remote_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
1477
1478         assert_eq!(remote_txn[0].output.len(), 4); // 1 local, 1 remote, 1 htlc inbound, 1 htlc outbound
1479         let mut has_both_htlcs = 0; // check htlcs match ones committed
1480         for outp in remote_txn[0].output.iter() {
1481                 if outp.value == 800_000 / 1000 {
1482                         has_both_htlcs += 1;
1483                 } else if outp.value == 900_000 / 1000 {
1484                         has_both_htlcs += 1;
1485                 }
1486         }
1487         assert_eq!(has_both_htlcs, 2);
1488
1489         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1490         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
1491         check_added_monitors!(nodes[0], 1);
1492
1493         // Check we only broadcast 1 timeout tx
1494         let claim_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
1495         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()) };
1496         assert_eq!(claim_txn.len(), 5);
1497         check_spends!(claim_txn[2], chan_1.3);
1498         check_spends!(claim_txn[3], claim_txn[2]);
1499         assert_eq!(htlc_pair.0.input.len(), 1);
1500         assert_eq!(htlc_pair.0.input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC 1 <--> 0, preimage tx
1501         check_spends!(htlc_pair.0, remote_txn[0]);
1502         assert_eq!(htlc_pair.1.input.len(), 1);
1503         assert_eq!(htlc_pair.1.input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // HTLC 0 <--> 1, timeout tx
1504         check_spends!(htlc_pair.1, remote_txn[0]);
1505
1506         let events = nodes[0].node.get_and_clear_pending_msg_events();
1507         assert_eq!(events.len(), 2);
1508         for e in events {
1509                 match e {
1510                         MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1511                         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, .. } } => {
1512                                 assert!(update_add_htlcs.is_empty());
1513                                 assert!(update_fail_htlcs.is_empty());
1514                                 assert_eq!(update_fulfill_htlcs.len(), 1);
1515                                 assert!(update_fail_malformed_htlcs.is_empty());
1516                                 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
1517                         },
1518                         _ => panic!("Unexpected event"),
1519                 }
1520         }
1521 }
1522
1523 fn do_channel_reserve_test(test_recv: bool) {
1524
1525         let chanmon_cfgs = create_chanmon_cfgs(3);
1526         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
1527         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
1528         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
1529         let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1530         let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001, InitFeatures::known(), InitFeatures::known());
1531         let logger = test_utils::TestLogger::new();
1532
1533         let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1534         let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1535
1536         let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1537         let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1538
1539         macro_rules! get_route_and_payment_hash {
1540                 ($recv_value: expr) => {{
1541                         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1542                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1543                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV, &logger).unwrap();
1544                         (route, payment_hash, payment_preimage)
1545                 }}
1546         };
1547
1548         macro_rules! expect_forward {
1549                 ($node: expr) => {{
1550                         let mut events = $node.node.get_and_clear_pending_msg_events();
1551                         assert_eq!(events.len(), 1);
1552                         check_added_monitors!($node, 1);
1553                         let payment_event = SendEvent::from_event(events.remove(0));
1554                         payment_event
1555                 }}
1556         }
1557
1558         let feemsat = 239; // somehow we know?
1559         let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1560
1561         let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1562
1563         // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1564         {
1565                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1566                 assert!(route.paths[0].iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1567                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1568                         assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
1569                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1570                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
1571         }
1572
1573         let mut htlc_id = 0;
1574         // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1575         // nodes[0]'s wealth
1576         loop {
1577                 let amt_msat = recv_value_0 + total_fee_msat;
1578                 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1579                         break;
1580                 }
1581                 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0, recv_value_0);
1582                 htlc_id += 1;
1583
1584                 let (stat01_, stat11_, stat12_, stat22_) = (
1585                         get_channel_value_stat!(nodes[0], chan_1.2),
1586                         get_channel_value_stat!(nodes[1], chan_1.2),
1587                         get_channel_value_stat!(nodes[1], chan_2.2),
1588                         get_channel_value_stat!(nodes[2], chan_2.2),
1589                 );
1590
1591                 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1592                 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1593                 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1594                 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1595                 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1596         }
1597
1598         {
1599                 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1600                 // attempt to get channel_reserve violation
1601                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1602                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1603                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1604                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1605                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 1);
1606         }
1607
1608         // adding pending output
1609         let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1610         let amt_msat_1 = recv_value_1 + total_fee_msat;
1611
1612         let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1613         let payment_event_1 = {
1614                 nodes[0].node.send_payment(&route_1, our_payment_hash_1, &None).unwrap();
1615                 check_added_monitors!(nodes[0], 1);
1616
1617                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1618                 assert_eq!(events.len(), 1);
1619                 SendEvent::from_event(events.remove(0))
1620         };
1621         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]);
1622
1623         // channel reserve test with htlc pending output > 0
1624         let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1625         {
1626                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1627                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1628                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1629                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1630                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 2);
1631         }
1632
1633         {
1634                 // test channel_reserve test on nodes[1] side
1635                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1636
1637                 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1638                 let secp_ctx = Secp256k1::new();
1639                 let session_priv = SecretKey::from_slice(&{
1640                         let mut session_key = [0; 32];
1641                         let mut rng = thread_rng();
1642                         rng.fill_bytes(&mut session_key);
1643                         session_key
1644                 }).expect("RNG is bad!");
1645
1646                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1647                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
1648                 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], recv_value_2 + 1, &None, cur_height).unwrap();
1649                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
1650                 let msg = msgs::UpdateAddHTLC {
1651                         channel_id: chan_1.2,
1652                         htlc_id,
1653                         amount_msat: htlc_msat,
1654                         payment_hash: our_payment_hash,
1655                         cltv_expiry: htlc_cltv,
1656                         onion_routing_packet: onion_packet,
1657                 };
1658
1659                 if test_recv {
1660                         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
1661                         // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1662                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1663                         assert_eq!(nodes[1].node.list_channels().len(), 1);
1664                         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
1665                         assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
1666                         check_added_monitors!(nodes[1], 1);
1667                         return;
1668                 }
1669         }
1670
1671         // split the rest to test holding cell
1672         let recv_value_21 = recv_value_2/2;
1673         let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1674         {
1675                 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1676                 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);
1677         }
1678
1679         // now see if they go through on both sides
1680         let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1681         // but this will stuck in the holding cell
1682         nodes[0].node.send_payment(&route_21, our_payment_hash_21, &None).unwrap();
1683         check_added_monitors!(nodes[0], 0);
1684         let events = nodes[0].node.get_and_clear_pending_events();
1685         assert_eq!(events.len(), 0);
1686
1687         // test with outbound holding cell amount > 0
1688         {
1689                 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1690                 unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
1691                         assert_eq!(err, "Cannot send value that would put us under local channel reserve value"));
1692                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1693                 nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us under local channel reserve value".to_string(), 3);
1694         }
1695
1696         let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1697         // this will also stuck in the holding cell
1698         nodes[0].node.send_payment(&route_22, our_payment_hash_22, &None).unwrap();
1699         check_added_monitors!(nodes[0], 0);
1700         assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1701         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1702
1703         // flush the pending htlc
1704         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg);
1705         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1706         check_added_monitors!(nodes[1], 1);
1707
1708         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack);
1709         check_added_monitors!(nodes[0], 1);
1710         let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1711
1712         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed);
1713         let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1714         // No commitment_signed so get_event_msg's assert(len == 1) passes
1715         check_added_monitors!(nodes[0], 1);
1716
1717         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack);
1718         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1719         check_added_monitors!(nodes[1], 1);
1720
1721         expect_pending_htlcs_forwardable!(nodes[1]);
1722
1723         let ref payment_event_11 = expect_forward!(nodes[1]);
1724         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]);
1725         commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1726
1727         expect_pending_htlcs_forwardable!(nodes[2]);
1728         expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1729
1730         // flush the htlcs in the holding cell
1731         assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1732         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]);
1733         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]);
1734         commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1735         expect_pending_htlcs_forwardable!(nodes[1]);
1736
1737         let ref payment_event_3 = expect_forward!(nodes[1]);
1738         assert_eq!(payment_event_3.msgs.len(), 2);
1739         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]);
1740         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]);
1741
1742         commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1743         expect_pending_htlcs_forwardable!(nodes[2]);
1744
1745         let events = nodes[2].node.get_and_clear_pending_events();
1746         assert_eq!(events.len(), 2);
1747         match events[0] {
1748                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1749                         assert_eq!(our_payment_hash_21, *payment_hash);
1750                         assert_eq!(*payment_secret, None);
1751                         assert_eq!(recv_value_21, amt);
1752                 },
1753                 _ => panic!("Unexpected event"),
1754         }
1755         match events[1] {
1756                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
1757                         assert_eq!(our_payment_hash_22, *payment_hash);
1758                         assert_eq!(None, *payment_secret);
1759                         assert_eq!(recv_value_22, amt);
1760                 },
1761                 _ => panic!("Unexpected event"),
1762         }
1763
1764         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1, recv_value_1);
1765         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21, recv_value_21);
1766         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22, recv_value_22);
1767
1768         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);
1769         let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1770         assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1771         assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1772
1773         let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1774         assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1775 }
1776
1777 #[test]
1778 fn channel_reserve_test() {
1779         do_channel_reserve_test(false);
1780         do_channel_reserve_test(true);
1781 }
1782
1783 #[test]
1784 fn channel_reserve_in_flight_removes() {
1785         // In cases where one side claims an HTLC, it thinks it has additional available funds that it
1786         // can send to its counterparty, but due to update ordering, the other side may not yet have
1787         // considered those HTLCs fully removed.
1788         // This tests that we don't count HTLCs which will not be included in the next remote
1789         // commitment transaction towards the reserve value (as it implies no commitment transaction
1790         // will be generated which violates the remote reserve value).
1791         // This was broken previously, and discovered by the chanmon_fail_consistency fuzz test.
1792         // To test this we:
1793         //  * route two HTLCs from A to B (note that, at a high level, this test is checking that, when
1794         //    you consider the values of both of these HTLCs, B may not send an HTLC back to A, but if
1795         //    you only consider the value of the first HTLC, it may not),
1796         //  * start routing a third HTLC from A to B,
1797         //  * claim the first two HTLCs (though B will generate an update_fulfill for one, and put
1798         //    the other claim in its holding cell, as it immediately goes into AwaitingRAA),
1799         //  * deliver the first fulfill from B
1800         //  * deliver the update_add and an RAA from A, resulting in B freeing the second holding cell
1801         //    claim,
1802         //  * deliver A's response CS and RAA.
1803         //    This results in A having the second HTLC in AwaitingRemovedRemoteRevoke, but B having
1804         //    removed it fully. B now has the push_msat plus the first two HTLCs in value.
1805         //  * Now B happily sends another HTLC, potentially violating its reserve value from A's point
1806         //    of view (if A counts the AwaitingRemovedRemoteRevoke HTLC).
1807         let chanmon_cfgs = create_chanmon_cfgs(2);
1808         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
1809         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
1810         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
1811         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1812         let logger = test_utils::TestLogger::new();
1813
1814         let b_chan_values = get_channel_value_stat!(nodes[1], chan_1.2);
1815         // Route the first two HTLCs.
1816         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000);
1817         let (payment_preimage_2, _) = route_payment(&nodes[0], &[&nodes[1]], 20000);
1818
1819         // Start routing the third HTLC (this is just used to get everyone in the right state).
1820         let (payment_preimage_3, payment_hash_3) = get_payment_preimage_hash!(nodes[0]);
1821         let send_1 = {
1822                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
1823                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
1824                 nodes[0].node.send_payment(&route, payment_hash_3, &None).unwrap();
1825                 check_added_monitors!(nodes[0], 1);
1826                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1827                 assert_eq!(events.len(), 1);
1828                 SendEvent::from_event(events.remove(0))
1829         };
1830
1831         // Now claim both of the first two HTLCs on B's end, putting B in AwaitingRAA and generating an
1832         // initial fulfill/CS.
1833         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, b_chan_values.channel_reserve_msat - b_chan_values.value_to_self_msat - 10000));
1834         check_added_monitors!(nodes[1], 1);
1835         let bs_removes = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1836
1837         // This claim goes in B's holding cell, allowing us to have a pending B->A RAA which does not
1838         // remove the second HTLC when we send the HTLC back from B to A.
1839         assert!(nodes[1].node.claim_funds(payment_preimage_2, &None, 20000));
1840         check_added_monitors!(nodes[1], 1);
1841         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1842
1843         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_removes.update_fulfill_htlcs[0]);
1844         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_removes.commitment_signed);
1845         check_added_monitors!(nodes[0], 1);
1846         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1847         expect_payment_sent!(nodes[0], payment_preimage_1);
1848
1849         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &send_1.msgs[0]);
1850         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &send_1.commitment_msg);
1851         check_added_monitors!(nodes[1], 1);
1852         // B is already AwaitingRAA, so cant generate a CS here
1853         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1854
1855         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1856         check_added_monitors!(nodes[1], 1);
1857         let bs_cs = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1858
1859         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1860         check_added_monitors!(nodes[0], 1);
1861         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1862
1863         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1864         check_added_monitors!(nodes[1], 1);
1865         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1866
1867         // The second HTLCis removed, but as A is in AwaitingRAA it can't generate a CS here, so the
1868         // RAA that B generated above doesn't fully resolve the second HTLC from A's point of view.
1869         // However, the RAA A generates here *does* fully resolve the HTLC from B's point of view (as A
1870         // can no longer broadcast a commitment transaction with it and B has the preimage so can go
1871         // on-chain as necessary).
1872         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_cs.update_fulfill_htlcs[0]);
1873         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_cs.commitment_signed);
1874         check_added_monitors!(nodes[0], 1);
1875         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1876         expect_payment_sent!(nodes[0], payment_preimage_2);
1877
1878         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1879         check_added_monitors!(nodes[1], 1);
1880         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1881
1882         expect_pending_htlcs_forwardable!(nodes[1]);
1883         expect_payment_received!(nodes[1], payment_hash_3, 100000);
1884
1885         // Note that as this RAA was generated before the delivery of the update_fulfill it shouldn't
1886         // resolve the second HTLC from A's point of view.
1887         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1888         check_added_monitors!(nodes[0], 1);
1889         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1890
1891         // Now that B doesn't have the second RAA anymore, but A still does, send a payment from B back
1892         // to A to ensure that A doesn't count the almost-removed HTLC in update_add processing.
1893         let (payment_preimage_4, payment_hash_4) = get_payment_preimage_hash!(nodes[1]);
1894         let send_2 = {
1895                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
1896                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &[], 10000, TEST_FINAL_CLTV, &logger).unwrap();
1897                 nodes[1].node.send_payment(&route, payment_hash_4, &None).unwrap();
1898                 check_added_monitors!(nodes[1], 1);
1899                 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1900                 assert_eq!(events.len(), 1);
1901                 SendEvent::from_event(events.remove(0))
1902         };
1903
1904         nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &send_2.msgs[0]);
1905         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &send_2.commitment_msg);
1906         check_added_monitors!(nodes[0], 1);
1907         let as_raa = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1908
1909         // Now just resolve all the outstanding messages/HTLCs for completeness...
1910
1911         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1912         check_added_monitors!(nodes[1], 1);
1913         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1914
1915         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_raa);
1916         check_added_monitors!(nodes[1], 1);
1917
1918         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1919         check_added_monitors!(nodes[0], 1);
1920         let as_cs = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1921
1922         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_cs.commitment_signed);
1923         check_added_monitors!(nodes[1], 1);
1924         let bs_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
1925
1926         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_raa);
1927         check_added_monitors!(nodes[0], 1);
1928
1929         expect_pending_htlcs_forwardable!(nodes[0]);
1930         expect_payment_received!(nodes[0], payment_hash_4, 10000);
1931
1932         claim_payment(&nodes[1], &[&nodes[0]], payment_preimage_4, 10_000);
1933         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_3, 100_000);
1934 }
1935
1936 #[test]
1937 fn channel_monitor_network_test() {
1938         // Simple test which builds a network of ChannelManagers, connects them to each other, and
1939         // tests that ChannelMonitor is able to recover from various states.
1940         let chanmon_cfgs = create_chanmon_cfgs(5);
1941         let node_cfgs = create_node_cfgs(5, &chanmon_cfgs);
1942         let node_chanmgrs = create_node_chanmgrs(5, &node_cfgs, &[None, None, None, None, None]);
1943         let nodes = create_network(5, &node_cfgs, &node_chanmgrs);
1944
1945         // Create some initial channels
1946         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
1947         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
1948         let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
1949         let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
1950
1951         // Rebalance the network a bit by relaying one payment through all the channels...
1952         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1953         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1954         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1955         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000, 8_000_000);
1956
1957         // Simple case with no pending HTLCs:
1958         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1959         check_added_monitors!(nodes[1], 1);
1960         {
1961                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1962                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1963                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1964                 check_added_monitors!(nodes[0], 1);
1965                 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1966         }
1967         get_announce_close_broadcast_events(&nodes, 0, 1);
1968         assert_eq!(nodes[0].node.list_channels().len(), 0);
1969         assert_eq!(nodes[1].node.list_channels().len(), 1);
1970
1971         // One pending HTLC is discarded by the force-close:
1972         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1973
1974         // Simple case of one pending HTLC to HTLC-Timeout
1975         nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1976         check_added_monitors!(nodes[1], 1);
1977         {
1978                 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1979                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1980                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1981                 check_added_monitors!(nodes[2], 1);
1982                 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1983         }
1984         get_announce_close_broadcast_events(&nodes, 1, 2);
1985         assert_eq!(nodes[1].node.list_channels().len(), 0);
1986         assert_eq!(nodes[2].node.list_channels().len(), 1);
1987
1988         macro_rules! claim_funds {
1989                 ($node: expr, $prev_node: expr, $preimage: expr, $amount: expr) => {
1990                         {
1991                                 assert!($node.node.claim_funds($preimage, &None, $amount));
1992                                 check_added_monitors!($node, 1);
1993
1994                                 let events = $node.node.get_and_clear_pending_msg_events();
1995                                 assert_eq!(events.len(), 1);
1996                                 match events[0] {
1997                                         MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1998                                                 assert!(update_add_htlcs.is_empty());
1999                                                 assert!(update_fail_htlcs.is_empty());
2000                                                 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
2001                                         },
2002                                         _ => panic!("Unexpected event"),
2003                                 };
2004                         }
2005                 }
2006         }
2007
2008         // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
2009         // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
2010         nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
2011         check_added_monitors!(nodes[2], 1);
2012         let node2_commitment_txid;
2013         {
2014                 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
2015                 node2_commitment_txid = node_txn[0].txid();
2016
2017                 // Claim the payment on nodes[3], giving it knowledge of the preimage
2018                 claim_funds!(nodes[3], nodes[2], payment_preimage_1, 3_000_000);
2019
2020                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2021                 nodes[3].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
2022                 check_added_monitors!(nodes[3], 1);
2023
2024                 check_preimage_claim(&nodes[3], &node_txn);
2025         }
2026         get_announce_close_broadcast_events(&nodes, 2, 3);
2027         assert_eq!(nodes[2].node.list_channels().len(), 0);
2028         assert_eq!(nodes[3].node.list_channels().len(), 1);
2029
2030         { // Cheat and reset nodes[4]'s height to 1
2031                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2032                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![] }, 1);
2033         }
2034
2035         assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
2036         assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
2037         // One pending HTLC to time out:
2038         let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
2039         // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
2040         // buffer space).
2041
2042         {
2043                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2044                 nodes[3].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2045                 for i in 3..TEST_FINAL_CLTV + 2 + LATENCY_GRACE_PERIOD_BLOCKS + 1 {
2046                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2047                         nodes[3].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2048                 }
2049                 check_added_monitors!(nodes[3], 1);
2050
2051                 // Clear bumped claiming txn spending node 2 commitment tx. Bumped txn are generated after reaching some height timer.
2052                 {
2053                         let mut node_txn = nodes[3].tx_broadcaster.txn_broadcasted.lock().unwrap();
2054                         node_txn.retain(|tx| {
2055                                 if tx.input[0].previous_output.txid == node2_commitment_txid {
2056                                         false
2057                                 } else { true }
2058                         });
2059                 }
2060
2061                 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
2062
2063                 // Claim the payment on nodes[4], giving it knowledge of the preimage
2064                 claim_funds!(nodes[4], nodes[3], payment_preimage_2, 3_000_000);
2065
2066                 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2067
2068                 nodes[4].block_notifier.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
2069                 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
2070                         header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2071                         nodes[4].block_notifier.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
2072                 }
2073
2074                 check_added_monitors!(nodes[4], 1);
2075                 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
2076
2077                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2078                 nodes[4].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
2079
2080                 check_preimage_claim(&nodes[4], &node_txn);
2081         }
2082         get_announce_close_broadcast_events(&nodes, 3, 4);
2083         assert_eq!(nodes[3].node.list_channels().len(), 0);
2084         assert_eq!(nodes[4].node.list_channels().len(), 0);
2085 }
2086
2087 #[test]
2088 fn test_justice_tx() {
2089         // Test justice txn built on revoked HTLC-Success tx, against both sides
2090         let mut alice_config = UserConfig::default();
2091         alice_config.channel_options.announced_channel = true;
2092         alice_config.peer_channel_config_limits.force_announced_channel_preference = false;
2093         alice_config.own_channel_config.our_to_self_delay = 6 * 24 * 5;
2094         let mut bob_config = UserConfig::default();
2095         bob_config.channel_options.announced_channel = true;
2096         bob_config.peer_channel_config_limits.force_announced_channel_preference = false;
2097         bob_config.own_channel_config.our_to_self_delay = 6 * 24 * 3;
2098         let user_cfgs = [Some(alice_config), Some(bob_config)];
2099         let chanmon_cfgs = create_chanmon_cfgs(2);
2100         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2101         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
2102         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2103         // Create some new channels:
2104         let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2105
2106         // A pending HTLC which will be revoked:
2107         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2108         // Get the will-be-revoked local txn from nodes[0]
2109         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_5.2);
2110         assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
2111         assert_eq!(revoked_local_txn[0].input.len(), 1);
2112         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
2113         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
2114         assert_eq!(revoked_local_txn[1].input.len(), 1);
2115         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2116         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2117         // Revoke the old state
2118         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 3_000_000);
2119
2120         {
2121                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2122                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2123                 {
2124                         let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2125                         assert_eq!(node_txn.len(), 2); // ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2126                         assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
2127
2128                         check_spends!(node_txn[0], revoked_local_txn[0]);
2129                         node_txn.swap_remove(0);
2130                         node_txn.truncate(1);
2131                 }
2132                 check_added_monitors!(nodes[1], 1);
2133                 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
2134
2135                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2136                 // Verify broadcast of revoked HTLC-timeout
2137                 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
2138                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2139                 check_added_monitors!(nodes[0], 1);
2140                 // Broadcast revoked HTLC-timeout on node 1
2141                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2142                 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone(), revoked_local_txn[0].clone());
2143         }
2144         get_announce_close_broadcast_events(&nodes, 0, 1);
2145
2146         assert_eq!(nodes[0].node.list_channels().len(), 0);
2147         assert_eq!(nodes[1].node.list_channels().len(), 0);
2148
2149         // We test justice_tx build by A on B's revoked HTLC-Success tx
2150         // Create some new channels:
2151         let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2152         {
2153                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2154                 node_txn.clear();
2155         }
2156
2157         // A pending HTLC which will be revoked:
2158         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2159         // Get the will-be-revoked local txn from B
2160         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_6.2);
2161         assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
2162         assert_eq!(revoked_local_txn[0].input.len(), 1);
2163         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
2164         assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
2165         // Revoke the old state
2166         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4, 3_000_000);
2167         {
2168                 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2169                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2170                 {
2171                         let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2172                         assert_eq!(node_txn.len(), 2); //ChannelMonitor: penalty tx, ChannelManager: local commitment tx
2173                         assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
2174
2175                         check_spends!(node_txn[0], revoked_local_txn[0]);
2176                         node_txn.swap_remove(0);
2177                 }
2178                 check_added_monitors!(nodes[0], 1);
2179                 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
2180
2181                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2182                 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
2183                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2184                 check_added_monitors!(nodes[1], 1);
2185                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
2186                 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone(), revoked_local_txn[0].clone());
2187         }
2188         get_announce_close_broadcast_events(&nodes, 0, 1);
2189         assert_eq!(nodes[0].node.list_channels().len(), 0);
2190         assert_eq!(nodes[1].node.list_channels().len(), 0);
2191 }
2192
2193 #[test]
2194 fn revoked_output_claim() {
2195         // Simple test to ensure a node will claim a revoked output when a stale remote commitment
2196         // transaction is broadcast by its counterparty
2197         let chanmon_cfgs = create_chanmon_cfgs(2);
2198         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2199         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2200         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2201         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2202         // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
2203         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2204         assert_eq!(revoked_local_txn.len(), 1);
2205         // Only output is the full channel value back to nodes[0]:
2206         assert_eq!(revoked_local_txn[0].output.len(), 1);
2207         // Send a payment through, updating everyone's latest commitment txn
2208         send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000, 5_000_000);
2209
2210         // Inform nodes[1] that nodes[0] broadcast a stale tx
2211         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2212         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2213         check_added_monitors!(nodes[1], 1);
2214         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2215         assert_eq!(node_txn.len(), 2); // ChannelMonitor: justice tx against revoked to_local output, ChannelManager: local commitment tx
2216
2217         check_spends!(node_txn[0], revoked_local_txn[0]);
2218         check_spends!(node_txn[1], chan_1.3);
2219
2220         // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
2221         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2222         get_announce_close_broadcast_events(&nodes, 0, 1);
2223         check_added_monitors!(nodes[0], 1)
2224 }
2225
2226 #[test]
2227 fn claim_htlc_outputs_shared_tx() {
2228         // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
2229         let chanmon_cfgs = create_chanmon_cfgs(2);
2230         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2231         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2232         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2233
2234         // Create some new channel:
2235         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2236
2237         // Rebalance the network to generate htlc in the two directions
2238         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2239         // 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
2240         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2241         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2242
2243         // Get the will-be-revoked local txn from node[0]
2244         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2245         assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
2246         assert_eq!(revoked_local_txn[0].input.len(), 1);
2247         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
2248         assert_eq!(revoked_local_txn[1].input.len(), 1);
2249         assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
2250         assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
2251         check_spends!(revoked_local_txn[1], revoked_local_txn[0]);
2252
2253         //Revoke the old state
2254         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2255
2256         {
2257                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2258                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2259                 check_added_monitors!(nodes[0], 1);
2260                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2261                 check_added_monitors!(nodes[1], 1);
2262                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2263                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2264
2265                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2266                 assert_eq!(node_txn.len(), 3); // ChannelMonitor: penalty tx, ChannelManager: local commitment + HTLC-timeout
2267
2268                 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
2269                 check_spends!(node_txn[0], revoked_local_txn[0]);
2270
2271                 let mut witness_lens = BTreeSet::new();
2272                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2273                 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
2274                 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
2275                 assert_eq!(witness_lens.len(), 3);
2276                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2277                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2278                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2279
2280                 // Next nodes[1] broadcasts its current local tx state:
2281                 assert_eq!(node_txn[1].input.len(), 1);
2282                 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
2283
2284                 assert_eq!(node_txn[2].input.len(), 1);
2285                 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
2286                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2287                 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
2288                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
2289                 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
2290         }
2291         get_announce_close_broadcast_events(&nodes, 0, 1);
2292         assert_eq!(nodes[0].node.list_channels().len(), 0);
2293         assert_eq!(nodes[1].node.list_channels().len(), 0);
2294 }
2295
2296 #[test]
2297 fn claim_htlc_outputs_single_tx() {
2298         // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
2299         let chanmon_cfgs = create_chanmon_cfgs(2);
2300         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2301         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2302         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2303
2304         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2305
2306         // Rebalance the network to generate htlc in the two directions
2307         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
2308         // 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
2309         // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
2310         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
2311         let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
2312
2313         // Get the will-be-revoked local txn from node[0]
2314         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
2315
2316         //Revoke the old state
2317         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1, 3_000_000);
2318
2319         {
2320                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2321                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2322                 check_added_monitors!(nodes[0], 1);
2323                 nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
2324                 check_added_monitors!(nodes[1], 1);
2325                 expect_pending_htlcs_forwardable_ignore!(nodes[0]);
2326
2327                 connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
2328                 expect_payment_failed!(nodes[1], payment_hash_2, true);
2329
2330                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2331                 assert_eq!(node_txn.len(), 9);
2332                 // ChannelMonitor: justice tx revoked offered htlc, justice tx revoked received htlc, justice tx revoked to_local (3)
2333                 // ChannelManager: local commmitment + local HTLC-timeout (2)
2334                 // ChannelMonitor: bumped justice tx, after one increase, bumps on HTLC aren't generated not being substantial anymore, bump on revoked to_local isn't generated due to more room for expiration (2)
2335                 // ChannelMonitor: local commitment + local HTLC-timeout (2)
2336
2337                 // Check the pair local commitment and HTLC-timeout broadcast due to HTLC expiration
2338                 assert_eq!(node_txn[2].input.len(), 1);
2339                 check_spends!(node_txn[2], chan_1.3);
2340                 assert_eq!(node_txn[3].input.len(), 1);
2341                 let witness_script = node_txn[3].input[0].witness.last().unwrap();
2342                 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
2343                 check_spends!(node_txn[3], node_txn[2]);
2344
2345                 // Justice transactions are indices 1-2-4
2346                 assert_eq!(node_txn[0].input.len(), 1);
2347                 assert_eq!(node_txn[1].input.len(), 1);
2348                 assert_eq!(node_txn[4].input.len(), 1);
2349
2350                 check_spends!(node_txn[0], revoked_local_txn[0]);
2351                 check_spends!(node_txn[1], revoked_local_txn[0]);
2352                 check_spends!(node_txn[4], revoked_local_txn[0]);
2353
2354                 let mut witness_lens = BTreeSet::new();
2355                 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
2356                 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
2357                 witness_lens.insert(node_txn[4].input[0].witness.last().unwrap().len());
2358                 assert_eq!(witness_lens.len(), 3);
2359                 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
2360                 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
2361                 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
2362         }
2363         get_announce_close_broadcast_events(&nodes, 0, 1);
2364         assert_eq!(nodes[0].node.list_channels().len(), 0);
2365         assert_eq!(nodes[1].node.list_channels().len(), 0);
2366 }
2367
2368 #[test]
2369 fn test_htlc_on_chain_success() {
2370         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2371         // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
2372         // broadcasting the right event to other nodes in payment path.
2373         // We test with two HTLCs simultaneously as that was not handled correctly in the past.
2374         // A --------------------> B ----------------------> C (preimage)
2375         // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
2376         // commitment transaction was broadcast.
2377         // Then, B should learn the preimage from said transactions, attempting to claim backwards
2378         // towards B.
2379         // B should be able to claim via preimage if A then broadcasts its local tx.
2380         // Finally, when A sees B's latest local commitment transaction it should be able to claim
2381         // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
2382         // PaymentSent event).
2383
2384         let chanmon_cfgs = create_chanmon_cfgs(3);
2385         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2386         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2387         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2388
2389         // Create some initial channels
2390         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2391         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2392
2393         // Rebalance the network a bit by relaying one payment through all the channels...
2394         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2395         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2396
2397         let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2398         let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2399         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2400
2401         // Broadcast legit commitment tx from C on B's chain
2402         // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
2403         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2404         assert_eq!(commitment_tx.len(), 1);
2405         check_spends!(commitment_tx[0], chan_2.3);
2406         nodes[2].node.claim_funds(our_payment_preimage, &None, 3_000_000);
2407         nodes[2].node.claim_funds(our_payment_preimage_2, &None, 3_000_000);
2408         check_added_monitors!(nodes[2], 2);
2409         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2410         assert!(updates.update_add_htlcs.is_empty());
2411         assert!(updates.update_fail_htlcs.is_empty());
2412         assert!(updates.update_fail_malformed_htlcs.is_empty());
2413         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2414
2415         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2416         check_closed_broadcast!(nodes[2], false);
2417         check_added_monitors!(nodes[2], 1);
2418         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx, 2*htlc-success tx), ChannelMonitor : 2 (2 * HTLC-Success tx)
2419         assert_eq!(node_txn.len(), 5);
2420         assert_eq!(node_txn[0], node_txn[3]);
2421         assert_eq!(node_txn[1], node_txn[4]);
2422         assert_eq!(node_txn[2], commitment_tx[0]);
2423         check_spends!(node_txn[0], commitment_tx[0]);
2424         check_spends!(node_txn[1], commitment_tx[0]);
2425         assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2426         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2427         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2428         assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2429         assert_eq!(node_txn[0].lock_time, 0);
2430         assert_eq!(node_txn[1].lock_time, 0);
2431
2432         // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
2433         nodes[1].block_notifier.block_connected(&Block { header, txdata: node_txn}, 1);
2434         {
2435                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2436                 assert_eq!(added_monitors.len(), 1);
2437                 assert_eq!(added_monitors[0].0.txid, chan_2.3.txid());
2438                 added_monitors.clear();
2439         }
2440         let events = nodes[1].node.get_and_clear_pending_msg_events();
2441         {
2442                 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
2443                 assert_eq!(added_monitors.len(), 2);
2444                 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
2445                 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
2446                 added_monitors.clear();
2447         }
2448         assert_eq!(events.len(), 2);
2449         match events[0] {
2450                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
2451                 _ => panic!("Unexpected event"),
2452         }
2453         match events[1] {
2454                 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, .. } } => {
2455                         assert!(update_add_htlcs.is_empty());
2456                         assert!(update_fail_htlcs.is_empty());
2457                         assert_eq!(update_fulfill_htlcs.len(), 1);
2458                         assert!(update_fail_malformed_htlcs.is_empty());
2459                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2460                 },
2461                 _ => panic!("Unexpected event"),
2462         };
2463         macro_rules! check_tx_local_broadcast {
2464                 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
2465                         let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
2466                         assert_eq!(node_txn.len(), 5);
2467                         // Node[1]: ChannelManager: 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 (timeout tx)
2468                         // Node[0]: ChannelManager: 3 (commtiemtn tx, 2*HTLC-Timeout tx), ChannelMonitor: 2 HTLC-timeout
2469                         check_spends!(node_txn[0], $commitment_tx);
2470                         check_spends!(node_txn[1], $commitment_tx);
2471                         assert_ne!(node_txn[0].lock_time, 0);
2472                         assert_ne!(node_txn[1].lock_time, 0);
2473                         if $htlc_offered {
2474                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2475                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2476                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2477                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2478                         } else {
2479                                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2480                                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2481                                 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2482                                 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2483                         }
2484                         check_spends!(node_txn[2], $chan_tx);
2485                         check_spends!(node_txn[3], node_txn[2]);
2486                         check_spends!(node_txn[4], node_txn[2]);
2487                         assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
2488                         assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2489                         assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2490                         assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2491                         assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
2492                         assert_ne!(node_txn[3].lock_time, 0);
2493                         assert_ne!(node_txn[4].lock_time, 0);
2494                         node_txn.clear();
2495                 } }
2496         }
2497         // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
2498         // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
2499         // timeout-claim of the output that nodes[2] just claimed via success.
2500         check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
2501
2502         // Broadcast legit commitment tx from A on B's chain
2503         // Broadcast preimage tx by B on offered output from A commitment tx  on A's chain
2504         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
2505         check_spends!(commitment_tx[0], chan_1.3);
2506         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2507         check_closed_broadcast!(nodes[1], false);
2508         check_added_monitors!(nodes[1], 1);
2509         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 3 (commitment tx + HTLC-Sucess * 2), ChannelMonitor : 1 (HTLC-Success)
2510         assert_eq!(node_txn.len(), 4);
2511         check_spends!(node_txn[0], commitment_tx[0]);
2512         assert_eq!(node_txn[0].input.len(), 2);
2513         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2514         assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2515         assert_eq!(node_txn[0].lock_time, 0);
2516         assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
2517         check_spends!(node_txn[1], chan_1.3);
2518         assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
2519         check_spends!(node_txn[2], node_txn[1]);
2520         check_spends!(node_txn[3], node_txn[1]);
2521         // We don't bother to check that B can claim the HTLC output on its commitment tx here as
2522         // we already checked the same situation with A.
2523
2524         // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
2525         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
2526         check_closed_broadcast!(nodes[0], false);
2527         check_added_monitors!(nodes[0], 1);
2528         let events = nodes[0].node.get_and_clear_pending_events();
2529         assert_eq!(events.len(), 2);
2530         let mut first_claimed = false;
2531         for event in events {
2532                 match event {
2533                         Event::PaymentSent { payment_preimage } => {
2534                                 if payment_preimage == our_payment_preimage {
2535                                         assert!(!first_claimed);
2536                                         first_claimed = true;
2537                                 } else {
2538                                         assert_eq!(payment_preimage, our_payment_preimage_2);
2539                                 }
2540                         },
2541                         _ => panic!("Unexpected event"),
2542                 }
2543         }
2544         check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2545 }
2546
2547 #[test]
2548 fn test_htlc_on_chain_timeout() {
2549         // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2550         // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2551         // broadcasting the right event to other nodes in payment path.
2552         // A ------------------> B ----------------------> C (timeout)
2553         //    B's commitment tx                 C's commitment tx
2554         //            \                                  \
2555         //         B's HTLC timeout tx               B's timeout tx
2556
2557         let chanmon_cfgs = create_chanmon_cfgs(3);
2558         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2559         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2560         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2561
2562         // Create some intial channels
2563         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2564         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2565
2566         // Rebalance the network a bit by relaying one payment thorugh all the channels...
2567         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2568         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
2569
2570         let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2571         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2572
2573         // Broadcast legit commitment tx from C on B's chain
2574         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
2575         check_spends!(commitment_tx[0], chan_2.3);
2576         nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
2577         check_added_monitors!(nodes[2], 0);
2578         expect_pending_htlcs_forwardable!(nodes[2]);
2579         check_added_monitors!(nodes[2], 1);
2580
2581         let events = nodes[2].node.get_and_clear_pending_msg_events();
2582         assert_eq!(events.len(), 1);
2583         match events[0] {
2584                 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, .. } } => {
2585                         assert!(update_add_htlcs.is_empty());
2586                         assert!(!update_fail_htlcs.is_empty());
2587                         assert!(update_fulfill_htlcs.is_empty());
2588                         assert!(update_fail_malformed_htlcs.is_empty());
2589                         assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2590                 },
2591                 _ => panic!("Unexpected event"),
2592         };
2593         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2594         check_closed_broadcast!(nodes[2], false);
2595         check_added_monitors!(nodes[2], 1);
2596         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2597         assert_eq!(node_txn.len(), 1);
2598         check_spends!(node_txn[0], chan_2.3);
2599         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2600
2601         // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2602         // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2603         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2604         let timeout_tx;
2605         {
2606                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2607                 assert_eq!(node_txn.len(), 5); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (local commitment tx + HTLC-timeout), 1 timeout tx
2608                 assert_eq!(node_txn[1], node_txn[3]);
2609                 assert_eq!(node_txn[2], node_txn[4]);
2610
2611                 check_spends!(node_txn[0], commitment_tx[0]);
2612                 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2613
2614                 check_spends!(node_txn[1], chan_2.3);
2615                 check_spends!(node_txn[2], node_txn[1]);
2616                 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2617                 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2618
2619                 timeout_tx = node_txn[0].clone();
2620                 node_txn.clear();
2621         }
2622
2623         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![timeout_tx]}, 1);
2624         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2625         check_added_monitors!(nodes[1], 1);
2626         check_closed_broadcast!(nodes[1], false);
2627
2628         expect_pending_htlcs_forwardable!(nodes[1]);
2629         check_added_monitors!(nodes[1], 1);
2630         let events = nodes[1].node.get_and_clear_pending_msg_events();
2631         assert_eq!(events.len(), 1);
2632         match events[0] {
2633                 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, .. } } => {
2634                         assert!(update_add_htlcs.is_empty());
2635                         assert!(!update_fail_htlcs.is_empty());
2636                         assert!(update_fulfill_htlcs.is_empty());
2637                         assert!(update_fail_malformed_htlcs.is_empty());
2638                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2639                 },
2640                 _ => panic!("Unexpected event"),
2641         };
2642         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
2643         assert_eq!(node_txn.len(), 0);
2644
2645         // Broadcast legit commitment tx from B on A's chain
2646         let commitment_tx = get_local_commitment_txn!(nodes[1], chan_1.2);
2647         check_spends!(commitment_tx[0], chan_1.3);
2648
2649         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2650         check_closed_broadcast!(nodes[0], false);
2651         check_added_monitors!(nodes[0], 1);
2652         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 1 timeout tx
2653         assert_eq!(node_txn.len(), 3);
2654         check_spends!(node_txn[0], commitment_tx[0]);
2655         assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2656         check_spends!(node_txn[1], chan_1.3);
2657         check_spends!(node_txn[2], node_txn[1]);
2658         assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2659         assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2660 }
2661
2662 #[test]
2663 fn test_simple_commitment_revoked_fail_backward() {
2664         // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2665         // and fail backward accordingly.
2666
2667         let chanmon_cfgs = create_chanmon_cfgs(3);
2668         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2669         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2670         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2671
2672         // Create some initial channels
2673         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2674         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2675
2676         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2677         // Get the will-be-revoked local txn from nodes[2]
2678         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2679         // Revoke the old state
2680         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, 3_000_000);
2681
2682         let (_, payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2683
2684         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2685         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2686         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2687         check_added_monitors!(nodes[1], 1);
2688         check_closed_broadcast!(nodes[1], false);
2689
2690         expect_pending_htlcs_forwardable!(nodes[1]);
2691         check_added_monitors!(nodes[1], 1);
2692         let events = nodes[1].node.get_and_clear_pending_msg_events();
2693         assert_eq!(events.len(), 1);
2694         match events[0] {
2695                 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, .. } } => {
2696                         assert!(update_add_htlcs.is_empty());
2697                         assert_eq!(update_fail_htlcs.len(), 1);
2698                         assert!(update_fulfill_htlcs.is_empty());
2699                         assert!(update_fail_malformed_htlcs.is_empty());
2700                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2701
2702                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2703                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2704
2705                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2706                         assert_eq!(events.len(), 1);
2707                         match events[0] {
2708                                 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2709                                 _ => panic!("Unexpected event"),
2710                         }
2711                         expect_payment_failed!(nodes[0], payment_hash, false);
2712                 },
2713                 _ => panic!("Unexpected event"),
2714         }
2715 }
2716
2717 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2718         // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2719         // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2720         // commitment transaction anymore.
2721         // To do this, we have the peer which will broadcast a revoked commitment transaction send
2722         // a number of update_fail/commitment_signed updates without ever sending the RAA in
2723         // response to our commitment_signed. This is somewhat misbehavior-y, though not
2724         // technically disallowed and we should probably handle it reasonably.
2725         // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2726         // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2727         // transactions:
2728         // * Once we move it out of our holding cell/add it, we will immediately include it in a
2729         //   commitment_signed (implying it will be in the latest remote commitment transaction).
2730         // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2731         //   and once they revoke the previous commitment transaction (allowing us to send a new
2732         //   commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2733         let chanmon_cfgs = create_chanmon_cfgs(3);
2734         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
2735         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
2736         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
2737
2738         // Create some initial channels
2739         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
2740         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
2741
2742         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2743         // Get the will-be-revoked local txn from nodes[2]
2744         let revoked_local_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
2745         assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2746         // Revoke the old state
2747         claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage, if no_to_remote { 10_000 } else { 3_000_000});
2748
2749         let value = if use_dust {
2750                 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2751                 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2752                 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2753         } else { 3000000 };
2754
2755         let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2756         let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2757         let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2758
2759         assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash, &None));
2760         expect_pending_htlcs_forwardable!(nodes[2]);
2761         check_added_monitors!(nodes[2], 1);
2762         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2763         assert!(updates.update_add_htlcs.is_empty());
2764         assert!(updates.update_fulfill_htlcs.is_empty());
2765         assert!(updates.update_fail_malformed_htlcs.is_empty());
2766         assert_eq!(updates.update_fail_htlcs.len(), 1);
2767         assert!(updates.update_fee.is_none());
2768         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2769         let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2770         // Drop the last RAA from 3 -> 2
2771
2772         assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash, &None));
2773         expect_pending_htlcs_forwardable!(nodes[2]);
2774         check_added_monitors!(nodes[2], 1);
2775         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2776         assert!(updates.update_add_htlcs.is_empty());
2777         assert!(updates.update_fulfill_htlcs.is_empty());
2778         assert!(updates.update_fail_malformed_htlcs.is_empty());
2779         assert_eq!(updates.update_fail_htlcs.len(), 1);
2780         assert!(updates.update_fee.is_none());
2781         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2782         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2783         check_added_monitors!(nodes[1], 1);
2784         // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2785         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2786         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2787         check_added_monitors!(nodes[2], 1);
2788
2789         assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash, &None));
2790         expect_pending_htlcs_forwardable!(nodes[2]);
2791         check_added_monitors!(nodes[2], 1);
2792         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2793         assert!(updates.update_add_htlcs.is_empty());
2794         assert!(updates.update_fulfill_htlcs.is_empty());
2795         assert!(updates.update_fail_malformed_htlcs.is_empty());
2796         assert_eq!(updates.update_fail_htlcs.len(), 1);
2797         assert!(updates.update_fee.is_none());
2798         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
2799         // At this point first_payment_hash has dropped out of the latest two commitment
2800         // transactions that nodes[1] is tracking...
2801         nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed);
2802         check_added_monitors!(nodes[1], 1);
2803         // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2804         let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2805         nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa);
2806         check_added_monitors!(nodes[2], 1);
2807
2808         // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2809         // on nodes[2]'s RAA.
2810         let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2811         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2812         let logger = test_utils::TestLogger::new();
2813         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
2814         nodes[1].node.send_payment(&route, fourth_payment_hash, &None).unwrap();
2815         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2816         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2817         check_added_monitors!(nodes[1], 0);
2818
2819         if deliver_bs_raa {
2820                 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa);
2821                 // One monitor for the new revocation preimage, no second on as we won't generate a new
2822                 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2823                 check_added_monitors!(nodes[1], 1);
2824                 let events = nodes[1].node.get_and_clear_pending_events();
2825                 assert_eq!(events.len(), 1);
2826                 match events[0] {
2827                         Event::PendingHTLCsForwardable { .. } => { },
2828                         _ => panic!("Unexpected event"),
2829                 };
2830                 // Deliberately don't process the pending fail-back so they all fail back at once after
2831                 // block connection just like the !deliver_bs_raa case
2832         }
2833
2834         let mut failed_htlcs = HashSet::new();
2835         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2836
2837         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2838         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2839         check_added_monitors!(nodes[1], 1);
2840         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
2841
2842         let events = nodes[1].node.get_and_clear_pending_events();
2843         assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2844         match events[0] {
2845                 Event::PaymentFailed { ref payment_hash, .. } => {
2846                         assert_eq!(*payment_hash, fourth_payment_hash);
2847                 },
2848                 _ => panic!("Unexpected event"),
2849         }
2850         if !deliver_bs_raa {
2851                 match events[1] {
2852                         Event::PendingHTLCsForwardable { .. } => { },
2853                         _ => panic!("Unexpected event"),
2854                 };
2855         }
2856         nodes[1].node.process_pending_htlc_forwards();
2857         check_added_monitors!(nodes[1], 1);
2858
2859         let events = nodes[1].node.get_and_clear_pending_msg_events();
2860         assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2861         match events[if deliver_bs_raa { 1 } else { 0 }] {
2862                 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2863                 _ => panic!("Unexpected event"),
2864         }
2865         if deliver_bs_raa {
2866                 match events[0] {
2867                         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, .. } } => {
2868                                 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2869                                 assert_eq!(update_add_htlcs.len(), 1);
2870                                 assert!(update_fulfill_htlcs.is_empty());
2871                                 assert!(update_fail_htlcs.is_empty());
2872                                 assert!(update_fail_malformed_htlcs.is_empty());
2873                         },
2874                         _ => panic!("Unexpected event"),
2875                 }
2876         }
2877         match events[if deliver_bs_raa { 2 } else { 1 }] {
2878                 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, .. } } => {
2879                         assert!(update_add_htlcs.is_empty());
2880                         assert_eq!(update_fail_htlcs.len(), 3);
2881                         assert!(update_fulfill_htlcs.is_empty());
2882                         assert!(update_fail_malformed_htlcs.is_empty());
2883                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2884
2885                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
2886                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]);
2887                         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]);
2888
2889                         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2890
2891                         let events = nodes[0].node.get_and_clear_pending_msg_events();
2892                         // If we delivered B's RAA we got an unknown preimage error, not something
2893                         // that we should update our routing table for.
2894                         assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2895                         for event in events {
2896                                 match event {
2897                                         MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2898                                         _ => panic!("Unexpected event"),
2899                                 }
2900                         }
2901                         let events = nodes[0].node.get_and_clear_pending_events();
2902                         assert_eq!(events.len(), 3);
2903                         match events[0] {
2904                                 Event::PaymentFailed { ref payment_hash, .. } => {
2905                                         assert!(failed_htlcs.insert(payment_hash.0));
2906                                 },
2907                                 _ => panic!("Unexpected event"),
2908                         }
2909                         match events[1] {
2910                                 Event::PaymentFailed { ref payment_hash, .. } => {
2911                                         assert!(failed_htlcs.insert(payment_hash.0));
2912                                 },
2913                                 _ => panic!("Unexpected event"),
2914                         }
2915                         match events[2] {
2916                                 Event::PaymentFailed { ref payment_hash, .. } => {
2917                                         assert!(failed_htlcs.insert(payment_hash.0));
2918                                 },
2919                                 _ => panic!("Unexpected event"),
2920                         }
2921                 },
2922                 _ => panic!("Unexpected event"),
2923         }
2924
2925         assert!(failed_htlcs.contains(&first_payment_hash.0));
2926         assert!(failed_htlcs.contains(&second_payment_hash.0));
2927         assert!(failed_htlcs.contains(&third_payment_hash.0));
2928 }
2929
2930 #[test]
2931 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2932         do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2933         do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2934         do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2935         do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2936 }
2937
2938 #[test]
2939 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2940         do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2941         do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2942         do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2943         do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2944 }
2945
2946 #[test]
2947 fn fail_backward_pending_htlc_upon_channel_failure() {
2948         let chanmon_cfgs = create_chanmon_cfgs(2);
2949         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
2950         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
2951         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
2952         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 500_000_000, InitFeatures::known(), InitFeatures::known());
2953         let logger = test_utils::TestLogger::new();
2954
2955         // Alice -> Bob: Route a payment but without Bob sending revoke_and_ack.
2956         {
2957                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
2958                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2959                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
2960                 nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
2961                 check_added_monitors!(nodes[0], 1);
2962
2963                 let payment_event = {
2964                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2965                         assert_eq!(events.len(), 1);
2966                         SendEvent::from_event(events.remove(0))
2967                 };
2968                 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
2969                 assert_eq!(payment_event.msgs.len(), 1);
2970         }
2971
2972         // Alice -> Bob: Route another payment but now Alice waits for Bob's earlier revoke_and_ack.
2973         let (_, failed_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2974         {
2975                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
2976                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
2977                 nodes[0].node.send_payment(&route, failed_payment_hash, &None).unwrap();
2978                 check_added_monitors!(nodes[0], 0);
2979
2980                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2981         }
2982
2983         // Alice <- Bob: Send a malformed update_add_htlc so Alice fails the channel.
2984         {
2985                 let (_, payment_hash) = get_payment_preimage_hash!(nodes[1]);
2986
2987                 let secp_ctx = Secp256k1::new();
2988                 let session_priv = {
2989                         let mut session_key = [0; 32];
2990                         let mut rng = thread_rng();
2991                         rng.fill_bytes(&mut session_key);
2992                         SecretKey::from_slice(&session_key).expect("RNG is bad!")
2993                 };
2994
2995                 let current_height = nodes[1].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
2996                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
2997                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 50_000, TEST_FINAL_CLTV, &logger).unwrap();
2998                 let (onion_payloads, _amount_msat, cltv_expiry) = onion_utils::build_onion_payloads(&route.paths[0], 50_000, &None, current_height).unwrap();
2999                 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route.paths[0], &session_priv).unwrap();
3000                 let onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
3001
3002                 // Send a 0-msat update_add_htlc to fail the channel.
3003                 let update_add_htlc = msgs::UpdateAddHTLC {
3004                         channel_id: chan.2,
3005                         htlc_id: 0,
3006                         amount_msat: 0,
3007                         payment_hash,
3008                         cltv_expiry,
3009                         onion_routing_packet,
3010                 };
3011                 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_htlc);
3012         }
3013
3014         // Check that Alice fails backward the pending HTLC from the second payment.
3015         expect_payment_failed!(nodes[0], failed_payment_hash, true);
3016         check_closed_broadcast!(nodes[0], true);
3017         check_added_monitors!(nodes[0], 1);
3018 }
3019
3020 #[test]
3021 fn test_htlc_ignore_latest_remote_commitment() {
3022         // Test that HTLC transactions spending the latest remote commitment transaction are simply
3023         // ignored if we cannot claim them. This originally tickled an invalid unwrap().
3024         let chanmon_cfgs = create_chanmon_cfgs(2);
3025         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3026         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3027         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3028         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3029
3030         route_payment(&nodes[0], &[&nodes[1]], 10000000);
3031         nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
3032         check_closed_broadcast!(nodes[0], false);
3033         check_added_monitors!(nodes[0], 1);
3034
3035         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3036         assert_eq!(node_txn.len(), 2);
3037
3038         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3039         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3040         check_closed_broadcast!(nodes[1], false);
3041         check_added_monitors!(nodes[1], 1);
3042
3043         // Duplicate the block_connected call since this may happen due to other listeners
3044         // registering new transactions
3045         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone(), node_txn[1].clone()]}, 1);
3046 }
3047
3048 #[test]
3049 fn test_force_close_fail_back() {
3050         // Check which HTLCs are failed-backwards on channel force-closure
3051         let chanmon_cfgs = create_chanmon_cfgs(3);
3052         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3053         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3054         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3055         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3056         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3057         let logger = test_utils::TestLogger::new();
3058
3059         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3060
3061         let mut payment_event = {
3062                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3063                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42, &logger).unwrap();
3064                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
3065                 check_added_monitors!(nodes[0], 1);
3066
3067                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3068                 assert_eq!(events.len(), 1);
3069                 SendEvent::from_event(events.remove(0))
3070         };
3071
3072         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3073         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3074
3075         expect_pending_htlcs_forwardable!(nodes[1]);
3076
3077         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3078         assert_eq!(events_2.len(), 1);
3079         payment_event = SendEvent::from_event(events_2.remove(0));
3080         assert_eq!(payment_event.msgs.len(), 1);
3081
3082         check_added_monitors!(nodes[1], 1);
3083         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
3084         nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg);
3085         check_added_monitors!(nodes[2], 1);
3086         let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3087
3088         // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
3089         // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
3090         // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
3091
3092         nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
3093         check_closed_broadcast!(nodes[2], false);
3094         check_added_monitors!(nodes[2], 1);
3095         let tx = {
3096                 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3097                 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
3098                 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
3099                 // back to nodes[1] upon timeout otherwise.
3100                 assert_eq!(node_txn.len(), 1);
3101                 node_txn.remove(0)
3102         };
3103
3104         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3105         nodes[1].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3106
3107         // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
3108         check_closed_broadcast!(nodes[1], false);
3109         check_added_monitors!(nodes[1], 1);
3110
3111         // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
3112         {
3113                 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
3114                 monitors.get_mut(&OutPoint::new(Txid::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
3115                         .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
3116         }
3117         nodes[2].block_notifier.block_connected_checked(&header, 1, &[&tx], &[1]);
3118         let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
3119         assert_eq!(node_txn.len(), 1);
3120         assert_eq!(node_txn[0].input.len(), 1);
3121         assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
3122         assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
3123         assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
3124
3125         check_spends!(node_txn[0], tx);
3126 }
3127
3128 #[test]
3129 fn test_unconf_chan() {
3130         // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
3131         let chanmon_cfgs = create_chanmon_cfgs(2);
3132         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3133         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3134         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3135         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3136
3137         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3138         assert_eq!(channel_state.by_id.len(), 1);
3139         assert_eq!(channel_state.short_to_id.len(), 1);
3140         mem::drop(channel_state);
3141
3142         let mut headers = Vec::new();
3143         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3144         headers.push(header.clone());
3145         for _i in 2..100 {
3146                 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3147                 headers.push(header.clone());
3148         }
3149         let mut height = 99;
3150         while !headers.is_empty() {
3151                 nodes[0].node.block_disconnected(&headers.pop().unwrap(), height);
3152                 height -= 1;
3153         }
3154         check_closed_broadcast!(nodes[0], false);
3155         check_added_monitors!(nodes[0], 1);
3156         let channel_state = nodes[0].node.channel_state.lock().unwrap();
3157         assert_eq!(channel_state.by_id.len(), 0);
3158         assert_eq!(channel_state.short_to_id.len(), 0);
3159 }
3160
3161 #[test]
3162 fn test_simple_peer_disconnect() {
3163         // Test that we can reconnect when there are no lost messages
3164         let chanmon_cfgs = create_chanmon_cfgs(3);
3165         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3166         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3167         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3168         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3169         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3170
3171         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3172         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3173         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3174
3175         let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3176         let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3177         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
3178         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1, 1_000_000);
3179
3180         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3181         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3182         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3183
3184         let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3185         let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
3186         let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3187         let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
3188
3189         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3190         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3191
3192         claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3, 1_000_000);
3193         fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
3194
3195         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
3196         {
3197                 let events = nodes[0].node.get_and_clear_pending_events();
3198                 assert_eq!(events.len(), 2);
3199                 match events[0] {
3200                         Event::PaymentSent { payment_preimage } => {
3201                                 assert_eq!(payment_preimage, payment_preimage_3);
3202                         },
3203                         _ => panic!("Unexpected event"),
3204                 }
3205                 match events[1] {
3206                         Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
3207                                 assert_eq!(payment_hash, payment_hash_5);
3208                                 assert!(rejected_by_dest);
3209                         },
3210                         _ => panic!("Unexpected event"),
3211                 }
3212         }
3213
3214         claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4, 1_000_000);
3215         fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
3216 }
3217
3218 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
3219         // Test that we can reconnect when in-flight HTLC updates get dropped
3220         let chanmon_cfgs = create_chanmon_cfgs(2);
3221         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3222         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3223         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3224         if messages_delivered == 0 {
3225                 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3226                 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
3227         } else {
3228                 create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3229         }
3230
3231         let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
3232
3233         let logger = test_utils::TestLogger::new();
3234         let payment_event = {
3235                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3236                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3237                 nodes[0].node.send_payment(&route, payment_hash_1, &None).unwrap();
3238                 check_added_monitors!(nodes[0], 1);
3239
3240                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3241                 assert_eq!(events.len(), 1);
3242                 SendEvent::from_event(events.remove(0))
3243         };
3244         assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
3245
3246         if messages_delivered < 2 {
3247                 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
3248         } else {
3249                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3250                 if messages_delivered >= 3 {
3251                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg);
3252                         check_added_monitors!(nodes[1], 1);
3253                         let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3254
3255                         if messages_delivered >= 4 {
3256                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3257                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3258                                 check_added_monitors!(nodes[0], 1);
3259
3260                                 if messages_delivered >= 5 {
3261                                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed);
3262                                         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3263                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3264                                         check_added_monitors!(nodes[0], 1);
3265
3266                                         if messages_delivered >= 6 {
3267                                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3268                                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3269                                                 check_added_monitors!(nodes[1], 1);
3270                                         }
3271                                 }
3272                         }
3273                 }
3274         }
3275
3276         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3277         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3278         if messages_delivered < 3 {
3279                 // Even if the funding_locked messages get exchanged, as long as nothing further was
3280                 // received on either side, both sides will need to resend them.
3281                 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
3282         } else if messages_delivered == 3 {
3283                 // nodes[0] still wants its RAA + commitment_signed
3284                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
3285         } else if messages_delivered == 4 {
3286                 // nodes[0] still wants its commitment_signed
3287                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
3288         } else if messages_delivered == 5 {
3289                 // nodes[1] still wants its final RAA
3290                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
3291         } else if messages_delivered == 6 {
3292                 // Everything was delivered...
3293                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3294         }
3295
3296         let events_1 = nodes[1].node.get_and_clear_pending_events();
3297         assert_eq!(events_1.len(), 1);
3298         match events_1[0] {
3299                 Event::PendingHTLCsForwardable { .. } => { },
3300                 _ => panic!("Unexpected event"),
3301         };
3302
3303         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3304         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3305         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3306
3307         nodes[1].node.process_pending_htlc_forwards();
3308
3309         let events_2 = nodes[1].node.get_and_clear_pending_events();
3310         assert_eq!(events_2.len(), 1);
3311         match events_2[0] {
3312                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt } => {
3313                         assert_eq!(payment_hash_1, *payment_hash);
3314                         assert_eq!(*payment_secret, None);
3315                         assert_eq!(amt, 1000000);
3316                 },
3317                 _ => panic!("Unexpected event"),
3318         }
3319
3320         nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000);
3321         check_added_monitors!(nodes[1], 1);
3322
3323         let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
3324         assert_eq!(events_3.len(), 1);
3325         let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
3326                 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3327                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3328                         assert!(updates.update_add_htlcs.is_empty());
3329                         assert!(updates.update_fail_htlcs.is_empty());
3330                         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3331                         assert!(updates.update_fail_malformed_htlcs.is_empty());
3332                         assert!(updates.update_fee.is_none());
3333                         (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
3334                 },
3335                 _ => panic!("Unexpected event"),
3336         };
3337
3338         if messages_delivered >= 1 {
3339                 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc);
3340
3341                 let events_4 = nodes[0].node.get_and_clear_pending_events();
3342                 assert_eq!(events_4.len(), 1);
3343                 match events_4[0] {
3344                         Event::PaymentSent { ref payment_preimage } => {
3345                                 assert_eq!(payment_preimage_1, *payment_preimage);
3346                         },
3347                         _ => panic!("Unexpected event"),
3348                 }
3349
3350                 if messages_delivered >= 2 {
3351                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed);
3352                         check_added_monitors!(nodes[0], 1);
3353                         let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3354
3355                         if messages_delivered >= 3 {
3356                                 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3357                                 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3358                                 check_added_monitors!(nodes[1], 1);
3359
3360                                 if messages_delivered >= 4 {
3361                                         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed);
3362                                         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3363                                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3364                                         check_added_monitors!(nodes[1], 1);
3365
3366                                         if messages_delivered >= 5 {
3367                                                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3368                                                 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3369                                                 check_added_monitors!(nodes[0], 1);
3370                                         }
3371                                 }
3372                         }
3373                 }
3374         }
3375
3376         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3377         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3378         if messages_delivered < 2 {
3379                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
3380                 //TODO: Deduplicate PaymentSent events, then enable this if:
3381                 //if messages_delivered < 1 {
3382                         let events_4 = nodes[0].node.get_and_clear_pending_events();
3383                         assert_eq!(events_4.len(), 1);
3384                         match events_4[0] {
3385                                 Event::PaymentSent { ref payment_preimage } => {
3386                                         assert_eq!(payment_preimage_1, *payment_preimage);
3387                                 },
3388                                 _ => panic!("Unexpected event"),
3389                         }
3390                 //}
3391         } else if messages_delivered == 2 {
3392                 // nodes[0] still wants its RAA + commitment_signed
3393                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
3394         } else if messages_delivered == 3 {
3395                 // nodes[0] still wants its commitment_signed
3396                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
3397         } else if messages_delivered == 4 {
3398                 // nodes[1] still wants its final RAA
3399                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
3400         } else if messages_delivered == 5 {
3401                 // Everything was delivered...
3402                 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3403         }
3404
3405         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3406         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3407         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3408
3409         // Channel should still work fine...
3410         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3411         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3412         let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
3413         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3414 }
3415
3416 #[test]
3417 fn test_drop_messages_peer_disconnect_a() {
3418         do_test_drop_messages_peer_disconnect(0);
3419         do_test_drop_messages_peer_disconnect(1);
3420         do_test_drop_messages_peer_disconnect(2);
3421         do_test_drop_messages_peer_disconnect(3);
3422 }
3423
3424 #[test]
3425 fn test_drop_messages_peer_disconnect_b() {
3426         do_test_drop_messages_peer_disconnect(4);
3427         do_test_drop_messages_peer_disconnect(5);
3428         do_test_drop_messages_peer_disconnect(6);
3429 }
3430
3431 #[test]
3432 fn test_funding_peer_disconnect() {
3433         // Test that we can lock in our funding tx while disconnected
3434         let chanmon_cfgs = create_chanmon_cfgs(2);
3435         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3436         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3437         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3438         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3439
3440         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3441         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3442
3443         confirm_transaction(&nodes[0].block_notifier, &nodes[0].chain_monitor, &tx, tx.version);
3444         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3445         assert_eq!(events_1.len(), 1);
3446         match events_1[0] {
3447                 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
3448                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3449                 },
3450                 _ => panic!("Unexpected event"),
3451         }
3452
3453         reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3454
3455         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3456         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3457
3458         confirm_transaction(&nodes[1].block_notifier, &nodes[1].chain_monitor, &tx, tx.version);
3459         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3460         assert_eq!(events_2.len(), 2);
3461         let funding_locked = match events_2[0] {
3462                 MessageSendEvent::SendFundingLocked { ref node_id, ref msg } => {
3463                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3464                         msg.clone()
3465                 },
3466                 _ => panic!("Unexpected event"),
3467         };
3468         let bs_announcement_sigs = match events_2[1] {
3469                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3470                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3471                         msg.clone()
3472                 },
3473                 _ => panic!("Unexpected event"),
3474         };
3475
3476         reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3477
3478         nodes[0].node.handle_funding_locked(&nodes[1].node.get_our_node_id(), &funding_locked);
3479         nodes[0].node.handle_announcement_signatures(&nodes[1].node.get_our_node_id(), &bs_announcement_sigs);
3480         let events_3 = nodes[0].node.get_and_clear_pending_msg_events();
3481         assert_eq!(events_3.len(), 2);
3482         let as_announcement_sigs = match events_3[0] {
3483                 MessageSendEvent::SendAnnouncementSignatures { ref node_id, ref msg } => {
3484                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3485                         msg.clone()
3486                 },
3487                 _ => panic!("Unexpected event"),
3488         };
3489         let (as_announcement, as_update) = match events_3[1] {
3490                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3491                         (msg.clone(), update_msg.clone())
3492                 },
3493                 _ => panic!("Unexpected event"),
3494         };
3495
3496         nodes[1].node.handle_announcement_signatures(&nodes[0].node.get_our_node_id(), &as_announcement_sigs);
3497         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
3498         assert_eq!(events_4.len(), 1);
3499         let (_, bs_update) = match events_4[0] {
3500                 MessageSendEvent::BroadcastChannelAnnouncement { ref msg, ref update_msg } => {
3501                         (msg.clone(), update_msg.clone())
3502                 },
3503                 _ => panic!("Unexpected event"),
3504         };
3505
3506         nodes[0].net_graph_msg_handler.handle_channel_announcement(&as_announcement).unwrap();
3507         nodes[0].net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3508         nodes[0].net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3509
3510         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3511         let logger = test_utils::TestLogger::new();
3512         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3513         let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
3514         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage, 1_000_000);
3515 }
3516
3517 #[test]
3518 fn test_drop_messages_peer_disconnect_dual_htlc() {
3519         // Test that we can handle reconnecting when both sides of a channel have pending
3520         // commitment_updates when we disconnect.
3521         let chanmon_cfgs = create_chanmon_cfgs(2);
3522         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3523         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3524         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3525         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3526         let logger = test_utils::TestLogger::new();
3527
3528         let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3529
3530         // Now try to send a second payment which will fail to send
3531         let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
3532         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3533         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
3534         nodes[0].node.send_payment(&route, payment_hash_2, &None).unwrap();
3535         check_added_monitors!(nodes[0], 1);
3536
3537         let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
3538         assert_eq!(events_1.len(), 1);
3539         match events_1[0] {
3540                 MessageSendEvent::UpdateHTLCs { .. } => {},
3541                 _ => panic!("Unexpected event"),
3542         }
3543
3544         assert!(nodes[1].node.claim_funds(payment_preimage_1, &None, 1_000_000));
3545         check_added_monitors!(nodes[1], 1);
3546
3547         let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
3548         assert_eq!(events_2.len(), 1);
3549         match events_2[0] {
3550                 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 } } => {
3551                         assert_eq!(*node_id, nodes[0].node.get_our_node_id());
3552                         assert!(update_add_htlcs.is_empty());
3553                         assert_eq!(update_fulfill_htlcs.len(), 1);
3554                         assert!(update_fail_htlcs.is_empty());
3555                         assert!(update_fail_malformed_htlcs.is_empty());
3556                         assert!(update_fee.is_none());
3557
3558                         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]);
3559                         let events_3 = nodes[0].node.get_and_clear_pending_events();
3560                         assert_eq!(events_3.len(), 1);
3561                         match events_3[0] {
3562                                 Event::PaymentSent { ref payment_preimage } => {
3563                                         assert_eq!(*payment_preimage, payment_preimage_1);
3564                                 },
3565                                 _ => panic!("Unexpected event"),
3566                         }
3567
3568                         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed);
3569                         let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3570                         // No commitment_signed so get_event_msg's assert(len == 1) passes
3571                         check_added_monitors!(nodes[0], 1);
3572                 },
3573                 _ => panic!("Unexpected event"),
3574         }
3575
3576         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
3577         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3578
3579         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3580         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3581         assert_eq!(reestablish_1.len(), 1);
3582         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3583         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3584         assert_eq!(reestablish_2.len(), 1);
3585
3586         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3587         let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
3588         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3589         let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
3590
3591         assert!(as_resp.0.is_none());
3592         assert!(bs_resp.0.is_none());
3593
3594         assert!(bs_resp.1.is_none());
3595         assert!(bs_resp.2.is_none());
3596
3597         assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
3598
3599         assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
3600         assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
3601         assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
3602         assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
3603         assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
3604         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]);
3605         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed);
3606         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3607         // No commitment_signed so get_event_msg's assert(len == 1) passes
3608         check_added_monitors!(nodes[1], 1);
3609
3610         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap());
3611         let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3612         assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
3613         assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
3614         assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
3615         assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
3616         assert!(bs_second_commitment_signed.update_fee.is_none());
3617         check_added_monitors!(nodes[1], 1);
3618
3619         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
3620         let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
3621         assert!(as_commitment_signed.update_add_htlcs.is_empty());
3622         assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
3623         assert!(as_commitment_signed.update_fail_htlcs.is_empty());
3624         assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
3625         assert!(as_commitment_signed.update_fee.is_none());
3626         check_added_monitors!(nodes[0], 1);
3627
3628         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed);
3629         let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
3630         // No commitment_signed so get_event_msg's assert(len == 1) passes
3631         check_added_monitors!(nodes[0], 1);
3632
3633         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed);
3634         let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
3635         // No commitment_signed so get_event_msg's assert(len == 1) passes
3636         check_added_monitors!(nodes[1], 1);
3637
3638         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack);
3639         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3640         check_added_monitors!(nodes[1], 1);
3641
3642         expect_pending_htlcs_forwardable!(nodes[1]);
3643
3644         let events_5 = nodes[1].node.get_and_clear_pending_events();
3645         assert_eq!(events_5.len(), 1);
3646         match events_5[0] {
3647                 Event::PaymentReceived { ref payment_hash, ref payment_secret, amt: _ } => {
3648                         assert_eq!(payment_hash_2, *payment_hash);
3649                         assert_eq!(*payment_secret, None);
3650                 },
3651                 _ => panic!("Unexpected event"),
3652         }
3653
3654         nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack);
3655         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3656         check_added_monitors!(nodes[0], 1);
3657
3658         claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2, 1_000_000);
3659 }
3660
3661 fn do_test_htlc_timeout(send_partial_mpp: bool) {
3662         // If the user fails to claim/fail an HTLC within the HTLC CLTV timeout we fail it for them
3663         // to avoid our counterparty failing the channel.
3664         let chanmon_cfgs = create_chanmon_cfgs(2);
3665         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3666         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3667         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3668
3669         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3670         let logger = test_utils::TestLogger::new();
3671
3672         let our_payment_hash = if send_partial_mpp {
3673                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3674                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3675                 let (_, our_payment_hash) = get_payment_preimage_hash!(&nodes[0]);
3676                 let payment_secret = PaymentSecret([0xdb; 32]);
3677                 // Use the utility function send_payment_along_path to send the payment with MPP data which
3678                 // indicates there are more HTLCs coming.
3679                 nodes[0].node.send_payment_along_path(&route.paths[0], &our_payment_hash, &Some(payment_secret), 200000, CHAN_CONFIRM_DEPTH).unwrap();
3680                 check_added_monitors!(nodes[0], 1);
3681                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
3682                 assert_eq!(events.len(), 1);
3683                 // Now do the relevant commitment_signed/RAA dances along the path, noting that the final
3684                 // hop should *not* yet generate any PaymentReceived event(s).
3685                 pass_along_path(&nodes[0], &[&nodes[1]], 100000, our_payment_hash, Some(payment_secret), events.drain(..).next().unwrap(), false);
3686                 our_payment_hash
3687         } else {
3688                 route_payment(&nodes[0], &[&nodes[1]], 100000).1
3689         };
3690
3691         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3692         nodes[0].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3693         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3694         for i in 102..TEST_FINAL_CLTV + 100 + 1 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3695                 header.prev_blockhash = header.bitcoin_hash();
3696                 nodes[0].block_notifier.block_connected_checked(&header, i, &[], &[]);
3697                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3698         }
3699
3700         expect_pending_htlcs_forwardable!(nodes[1]);
3701
3702         check_added_monitors!(nodes[1], 1);
3703         let htlc_timeout_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3704         assert!(htlc_timeout_updates.update_add_htlcs.is_empty());
3705         assert_eq!(htlc_timeout_updates.update_fail_htlcs.len(), 1);
3706         assert!(htlc_timeout_updates.update_fail_malformed_htlcs.is_empty());
3707         assert!(htlc_timeout_updates.update_fee.is_none());
3708
3709         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_timeout_updates.update_fail_htlcs[0]);
3710         commitment_signed_dance!(nodes[0], nodes[1], htlc_timeout_updates.commitment_signed, false);
3711         // 100_000 msat as u64, followed by a height of 123 as u32
3712         let mut expected_failure_data = byte_utils::be64_to_array(100_000).to_vec();
3713         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(123));
3714         expect_payment_failed!(nodes[0], our_payment_hash, true, 0x4000 | 15, &expected_failure_data[..]);
3715 }
3716
3717 #[test]
3718 fn test_htlc_timeout() {
3719         do_test_htlc_timeout(true);
3720         do_test_htlc_timeout(false);
3721 }
3722
3723 fn do_test_holding_cell_htlc_add_timeouts(forwarded_htlc: bool) {
3724         // Tests that HTLCs in the holding cell are timed out after the requisite number of blocks.
3725         let chanmon_cfgs = create_chanmon_cfgs(3);
3726         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
3727         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
3728         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
3729         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
3730         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
3731         let logger = test_utils::TestLogger::new();
3732
3733         // Route a first payment to get the 1 -> 2 channel in awaiting_raa...
3734         let (_, first_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3735         {
3736                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3737                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3738                 nodes[1].node.send_payment(&route, first_payment_hash, &None).unwrap();
3739         }
3740         assert_eq!(nodes[1].node.get_and_clear_pending_msg_events().len(), 1);
3741         check_added_monitors!(nodes[1], 1);
3742
3743         // Now attempt to route a second payment, which should be placed in the holding cell
3744         let (_, second_payment_hash) = get_payment_preimage_hash!(nodes[0]);
3745         if forwarded_htlc {
3746                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
3747                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3748                 nodes[0].node.send_payment(&route, second_payment_hash, &None).unwrap();
3749                 check_added_monitors!(nodes[0], 1);
3750                 let payment_event = SendEvent::from_event(nodes[0].node.get_and_clear_pending_msg_events().remove(0));
3751                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
3752                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
3753                 expect_pending_htlcs_forwardable!(nodes[1]);
3754                 check_added_monitors!(nodes[1], 0);
3755         } else {
3756                 let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
3757                 let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
3758                 nodes[1].node.send_payment(&route, second_payment_hash, &None).unwrap();
3759                 check_added_monitors!(nodes[1], 0);
3760         }
3761
3762         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3763         nodes[1].block_notifier.block_connected_checked(&header, 101, &[], &[]);
3764         for i in 102..TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS {
3765                 header.prev_blockhash = header.bitcoin_hash();
3766                 nodes[1].block_notifier.block_connected_checked(&header, i, &[], &[]);
3767         }
3768
3769         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3770         assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
3771
3772         header.prev_blockhash = header.bitcoin_hash();
3773         nodes[1].block_notifier.block_connected_checked(&header, TEST_FINAL_CLTV + 100 - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS, &[], &[]);
3774
3775         if forwarded_htlc {
3776                 expect_pending_htlcs_forwardable!(nodes[1]);
3777                 check_added_monitors!(nodes[1], 1);
3778                 let fail_commit = nodes[1].node.get_and_clear_pending_msg_events();
3779                 assert_eq!(fail_commit.len(), 1);
3780                 match fail_commit[0] {
3781                         MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fail_htlcs, ref commitment_signed, .. }, .. } => {
3782                                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]);
3783                                 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, true, true);
3784                         },
3785                         _ => unreachable!(),
3786                 }
3787                 expect_payment_failed!(nodes[0], second_payment_hash, false);
3788                 if let &MessageSendEvent::PaymentFailureNetworkUpdate { ref update } = &nodes[0].node.get_and_clear_pending_msg_events()[0] {
3789                         match update {
3790                                 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {},
3791                                 _ => panic!("Unexpected event"),
3792                         }
3793                 } else {
3794                         panic!("Unexpected event");
3795                 }
3796         } else {
3797                 expect_payment_failed!(nodes[1], second_payment_hash, true);
3798         }
3799 }
3800
3801 #[test]
3802 fn test_holding_cell_htlc_add_timeouts() {
3803         do_test_holding_cell_htlc_add_timeouts(false);
3804         do_test_holding_cell_htlc_add_timeouts(true);
3805 }
3806
3807 #[test]
3808 fn test_invalid_channel_announcement() {
3809         //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
3810         let secp_ctx = Secp256k1::new();
3811         let chanmon_cfgs = create_chanmon_cfgs(2);
3812         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3813         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3814         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3815
3816         let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1], InitFeatures::known(), InitFeatures::known());
3817
3818         let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
3819         let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
3820         let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3821         let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
3822
3823         nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3824
3825         let as_bitcoin_key = as_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3826         let bs_bitcoin_key = bs_chan.get_local_keys().inner.local_channel_pubkeys.funding_pubkey;
3827
3828         let as_network_key = nodes[0].node.get_our_node_id();
3829         let bs_network_key = nodes[1].node.get_our_node_id();
3830
3831         let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3832
3833         let mut chan_announcement;
3834
3835         macro_rules! dummy_unsigned_msg {
3836                 () => {
3837                         msgs::UnsignedChannelAnnouncement {
3838                                 features: ChannelFeatures::known(),
3839                                 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3840                                 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3841                                 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3842                                 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3843                                 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3844                                 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3845                                 excess_data: Vec::new(),
3846                         };
3847                 }
3848         }
3849
3850         macro_rules! sign_msg {
3851                 ($unsigned_msg: expr) => {
3852                         let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3853                         let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().inner.funding_key());
3854                         let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().inner.funding_key());
3855                         let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3856                         let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3857                         chan_announcement = msgs::ChannelAnnouncement {
3858                                 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3859                                 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3860                                 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3861                                 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3862                                 contents: $unsigned_msg
3863                         }
3864                 }
3865         }
3866
3867         let unsigned_msg = dummy_unsigned_msg!();
3868         sign_msg!(unsigned_msg);
3869         assert_eq!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).unwrap(), true);
3870         let _ = nodes[0].net_graph_msg_handler.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3871
3872         // Configured with Network::Testnet
3873         let mut unsigned_msg = dummy_unsigned_msg!();
3874         unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3875         sign_msg!(unsigned_msg);
3876         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3877
3878         let mut unsigned_msg = dummy_unsigned_msg!();
3879         unsigned_msg.chain_hash = BlockHash::hash(&[1,2,3,4,5,6,7,8,9]);
3880         sign_msg!(unsigned_msg);
3881         assert!(nodes[0].net_graph_msg_handler.handle_channel_announcement(&chan_announcement).is_err());
3882 }
3883
3884 #[test]
3885 fn test_no_txn_manager_serialize_deserialize() {
3886         let chanmon_cfgs = create_chanmon_cfgs(2);
3887         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3888         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3889         let logger: test_utils::TestLogger;
3890         let fee_estimator: test_utils::TestFeeEstimator;
3891         let new_chan_monitor: test_utils::TestChannelMonitor;
3892         let keys_manager: test_utils::TestKeysInterface;
3893         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3894         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3895
3896         let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001, InitFeatures::known(), InitFeatures::known());
3897
3898         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3899
3900         let nodes_0_serialized = nodes[0].node.encode();
3901         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3902         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3903
3904         logger = test_utils::TestLogger::new();
3905         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
3906         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
3907         nodes[0].chan_monitor = &new_chan_monitor;
3908         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3909         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
3910         assert!(chan_0_monitor_read.is_empty());
3911
3912         let mut nodes_0_read = &nodes_0_serialized[..];
3913         let config = UserConfig::default();
3914         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
3915         let (_, nodes_0_deserialized_tmp) = {
3916                 let mut channel_monitors = HashMap::new();
3917                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
3918                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3919                         default_config: config,
3920                         keys_manager: &keys_manager,
3921                         fee_estimator: &fee_estimator,
3922                         monitor: nodes[0].chan_monitor,
3923                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3924                         logger: &logger,
3925                         channel_monitors: &mut channel_monitors,
3926                 }).unwrap()
3927         };
3928         nodes_0_deserialized = nodes_0_deserialized_tmp;
3929         assert!(nodes_0_read.is_empty());
3930
3931         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
3932         nodes[0].node = &nodes_0_deserialized;
3933         nodes[0].block_notifier.register_listener(nodes[0].node);
3934         assert_eq!(nodes[0].node.list_channels().len(), 1);
3935         check_added_monitors!(nodes[0], 1);
3936
3937         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3938         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3939         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
3940         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3941
3942         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
3943         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3944         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
3945         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3946
3947         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3948         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3949         for node in nodes.iter() {
3950                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
3951                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
3952                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
3953         }
3954
3955         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
3956 }
3957
3958 #[test]
3959 fn test_manager_serialize_deserialize_events() {
3960         // This test makes sure the events field in ChannelManager survives de/serialization
3961         let chanmon_cfgs = create_chanmon_cfgs(2);
3962         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
3963         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
3964         let fee_estimator: test_utils::TestFeeEstimator;
3965         let logger: test_utils::TestLogger;
3966         let new_chan_monitor: test_utils::TestChannelMonitor;
3967         let keys_manager: test_utils::TestKeysInterface;
3968         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
3969         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
3970
3971         // Start creating a channel, but stop right before broadcasting the event message FundingBroadcastSafe
3972         let channel_value = 100000;
3973         let push_msat = 10001;
3974         let a_flags = InitFeatures::known();
3975         let b_flags = InitFeatures::known();
3976         let node_a = nodes.pop().unwrap();
3977         let node_b = nodes.pop().unwrap();
3978         node_a.node.create_channel(node_b.node.get_our_node_id(), channel_value, push_msat, 42, None).unwrap();
3979         node_b.node.handle_open_channel(&node_a.node.get_our_node_id(), a_flags, &get_event_msg!(node_a, MessageSendEvent::SendOpenChannel, node_b.node.get_our_node_id()));
3980         node_a.node.handle_accept_channel(&node_b.node.get_our_node_id(), b_flags, &get_event_msg!(node_b, MessageSendEvent::SendAcceptChannel, node_a.node.get_our_node_id()));
3981
3982         let (temporary_channel_id, tx, funding_output) = create_funding_transaction(&node_a, channel_value, 42);
3983
3984         node_a.node.funding_transaction_generated(&temporary_channel_id, funding_output);
3985         check_added_monitors!(node_a, 0);
3986
3987         node_b.node.handle_funding_created(&node_a.node.get_our_node_id(), &get_event_msg!(node_a, MessageSendEvent::SendFundingCreated, node_b.node.get_our_node_id()));
3988         {
3989                 let mut added_monitors = node_b.chan_monitor.added_monitors.lock().unwrap();
3990                 assert_eq!(added_monitors.len(), 1);
3991                 assert_eq!(added_monitors[0].0, funding_output);
3992                 added_monitors.clear();
3993         }
3994
3995         node_a.node.handle_funding_signed(&node_b.node.get_our_node_id(), &get_event_msg!(node_b, MessageSendEvent::SendFundingSigned, node_a.node.get_our_node_id()));
3996         {
3997                 let mut added_monitors = node_a.chan_monitor.added_monitors.lock().unwrap();
3998                 assert_eq!(added_monitors.len(), 1);
3999                 assert_eq!(added_monitors[0].0, funding_output);
4000                 added_monitors.clear();
4001         }
4002         // Normally, this is where node_a would check for a FundingBroadcastSafe event, but the test de/serializes first instead
4003
4004         nodes.push(node_a);
4005         nodes.push(node_b);
4006
4007         // Start the de/seriailization process mid-channel creation to check that the channel manager will hold onto events that are serialized
4008         let nodes_0_serialized = nodes[0].node.encode();
4009         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4010         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4011
4012         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4013         logger = test_utils::TestLogger::new();
4014         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4015         nodes[0].chan_monitor = &new_chan_monitor;
4016         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4017         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4018         assert!(chan_0_monitor_read.is_empty());
4019
4020         let mut nodes_0_read = &nodes_0_serialized[..];
4021         let config = UserConfig::default();
4022         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4023         let (_, nodes_0_deserialized_tmp) = {
4024                 let mut channel_monitors = HashMap::new();
4025                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
4026                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4027                         default_config: config,
4028                         keys_manager: &keys_manager,
4029                         fee_estimator: &fee_estimator,
4030                         monitor: nodes[0].chan_monitor,
4031                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4032                         logger: &logger,
4033                         channel_monitors: &mut channel_monitors,
4034                 }).unwrap()
4035         };
4036         nodes_0_deserialized = nodes_0_deserialized_tmp;
4037         assert!(nodes_0_read.is_empty());
4038
4039         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4040
4041         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
4042         nodes[0].node = &nodes_0_deserialized;
4043
4044         // After deserializing, make sure the FundingBroadcastSafe event is still held by the channel manager
4045         let events_4 = nodes[0].node.get_and_clear_pending_events();
4046         assert_eq!(events_4.len(), 1);
4047         match events_4[0] {
4048                 Event::FundingBroadcastSafe { ref funding_txo, user_channel_id } => {
4049                         assert_eq!(user_channel_id, 42);
4050                         assert_eq!(*funding_txo, funding_output);
4051                 },
4052                 _ => panic!("Unexpected event"),
4053         };
4054
4055         // Make sure the channel is functioning as though the de/serialization never happened
4056         nodes[0].block_notifier.register_listener(nodes[0].node);
4057         assert_eq!(nodes[0].node.list_channels().len(), 1);
4058         check_added_monitors!(nodes[0], 1);
4059
4060         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4061         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
4062         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4063         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
4064
4065         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
4066         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4067         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
4068         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4069
4070         let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
4071         let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
4072         for node in nodes.iter() {
4073                 assert!(node.net_graph_msg_handler.handle_channel_announcement(&announcement).unwrap());
4074                 node.net_graph_msg_handler.handle_channel_update(&as_update).unwrap();
4075                 node.net_graph_msg_handler.handle_channel_update(&bs_update).unwrap();
4076         }
4077
4078         send_payment(&nodes[0], &[&nodes[1]], 1000000, 1_000_000);
4079 }
4080
4081 #[test]
4082 fn test_simple_manager_serialize_deserialize() {
4083         let chanmon_cfgs = create_chanmon_cfgs(2);
4084         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4085         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4086         let logger: test_utils::TestLogger;
4087         let fee_estimator: test_utils::TestFeeEstimator;
4088         let new_chan_monitor: test_utils::TestChannelMonitor;
4089         let keys_manager: test_utils::TestKeysInterface;
4090         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4091         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4092         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4093
4094         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4095         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
4096
4097         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4098
4099         let nodes_0_serialized = nodes[0].node.encode();
4100         let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
4101         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
4102
4103         logger = test_utils::TestLogger::new();
4104         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4105         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4106         nodes[0].chan_monitor = &new_chan_monitor;
4107         let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
4108         let (_, mut chan_0_monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut chan_0_monitor_read).unwrap();
4109         assert!(chan_0_monitor_read.is_empty());
4110
4111         let mut nodes_0_read = &nodes_0_serialized[..];
4112         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4113         let (_, nodes_0_deserialized_tmp) = {
4114                 let mut channel_monitors = HashMap::new();
4115                 channel_monitors.insert(chan_0_monitor.get_funding_txo(), &mut chan_0_monitor);
4116                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4117                         default_config: UserConfig::default(),
4118                         keys_manager: &keys_manager,
4119                         fee_estimator: &fee_estimator,
4120                         monitor: nodes[0].chan_monitor,
4121                         tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4122                         logger: &logger,
4123                         channel_monitors: &mut channel_monitors,
4124                 }).unwrap()
4125         };
4126         nodes_0_deserialized = nodes_0_deserialized_tmp;
4127         assert!(nodes_0_read.is_empty());
4128
4129         assert!(nodes[0].chan_monitor.add_monitor(chan_0_monitor.get_funding_txo(), chan_0_monitor).is_ok());
4130         nodes[0].node = &nodes_0_deserialized;
4131         check_added_monitors!(nodes[0], 1);
4132
4133         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4134
4135         fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
4136         claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage, 1_000_000);
4137 }
4138
4139 #[test]
4140 fn test_manager_serialize_deserialize_inconsistent_monitor() {
4141         // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
4142         let chanmon_cfgs = create_chanmon_cfgs(4);
4143         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
4144         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
4145         let logger: test_utils::TestLogger;
4146         let fee_estimator: test_utils::TestFeeEstimator;
4147         let new_chan_monitor: test_utils::TestChannelMonitor;
4148         let keys_manager: test_utils::TestKeysInterface;
4149         let nodes_0_deserialized: ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>;
4150         let mut nodes = create_network(4, &node_cfgs, &node_chanmgrs);
4151         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4152         create_announced_chan_between_nodes(&nodes, 2, 0, InitFeatures::known(), InitFeatures::known());
4153         let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3, InitFeatures::known(), InitFeatures::known());
4154
4155         let mut node_0_stale_monitors_serialized = Vec::new();
4156         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4157                 let mut writer = test_utils::TestVecWriter(Vec::new());
4158                 monitor.1.write_for_disk(&mut writer).unwrap();
4159                 node_0_stale_monitors_serialized.push(writer.0);
4160         }
4161
4162         let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
4163
4164         // Serialize the ChannelManager here, but the monitor we keep up-to-date
4165         let nodes_0_serialized = nodes[0].node.encode();
4166
4167         route_payment(&nodes[0], &[&nodes[3]], 1000000);
4168         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4169         nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4170         nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
4171
4172         // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
4173         // nodes[3])
4174         let mut node_0_monitors_serialized = Vec::new();
4175         for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
4176                 let mut writer = test_utils::TestVecWriter(Vec::new());
4177                 monitor.1.write_for_disk(&mut writer).unwrap();
4178                 node_0_monitors_serialized.push(writer.0);
4179         }
4180
4181         logger = test_utils::TestLogger::new();
4182         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
4183         new_chan_monitor = test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), &logger, &fee_estimator);
4184         nodes[0].chan_monitor = &new_chan_monitor;
4185
4186         let mut node_0_stale_monitors = Vec::new();
4187         for serialized in node_0_stale_monitors_serialized.iter() {
4188                 let mut read = &serialized[..];
4189                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4190                 assert!(read.is_empty());
4191                 node_0_stale_monitors.push(monitor);
4192         }
4193
4194         let mut node_0_monitors = Vec::new();
4195         for serialized in node_0_monitors_serialized.iter() {
4196                 let mut read = &serialized[..];
4197                 let (_, monitor) = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut read).unwrap();
4198                 assert!(read.is_empty());
4199                 node_0_monitors.push(monitor);
4200         }
4201
4202         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
4203
4204         let mut nodes_0_read = &nodes_0_serialized[..];
4205         if let Err(msgs::DecodeError::InvalidValue) =
4206                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4207                 default_config: UserConfig::default(),
4208                 keys_manager: &keys_manager,
4209                 fee_estimator: &fee_estimator,
4210                 monitor: nodes[0].chan_monitor,
4211                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4212                 logger: &logger,
4213                 channel_monitors: &mut node_0_stale_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4214         }) { } else {
4215                 panic!("If the monitor(s) are stale, this indicates a bug and we should get an Err return");
4216         };
4217
4218         let mut nodes_0_read = &nodes_0_serialized[..];
4219         let (_, nodes_0_deserialized_tmp) =
4220                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
4221                 default_config: UserConfig::default(),
4222                 keys_manager: &keys_manager,
4223                 fee_estimator: &fee_estimator,
4224                 monitor: nodes[0].chan_monitor,
4225                 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
4226                 logger: &logger,
4227                 channel_monitors: &mut node_0_monitors.iter_mut().map(|monitor| { (monitor.get_funding_txo(), monitor) }).collect(),
4228         }).unwrap();
4229         nodes_0_deserialized = nodes_0_deserialized_tmp;
4230         assert!(nodes_0_read.is_empty());
4231
4232         { // Channel close should result in a commitment tx and an HTLC tx
4233                 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4234                 assert_eq!(txn.len(), 2);
4235                 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
4236                 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
4237         }
4238
4239         for monitor in node_0_monitors.drain(..) {
4240                 assert!(nodes[0].chan_monitor.add_monitor(monitor.get_funding_txo(), monitor).is_ok());
4241                 check_added_monitors!(nodes[0], 1);
4242         }
4243         nodes[0].node = &nodes_0_deserialized;
4244
4245         // nodes[1] and nodes[2] have no lost state with nodes[0]...
4246         reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4247         reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4248         //... and we can even still claim the payment!
4249         claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage, 1_000_000);
4250
4251         nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4252         let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
4253         nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
4254         nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish);
4255         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4256         assert_eq!(msg_events.len(), 1);
4257         if let MessageSendEvent::HandleError { ref action, .. } = msg_events[0] {
4258                 match action {
4259                         &ErrorAction::SendErrorMessage { ref msg } => {
4260                                 assert_eq!(msg.channel_id, channel_id);
4261                         },
4262                         _ => panic!("Unexpected event!"),
4263                 }
4264         }
4265 }
4266
4267 macro_rules! check_spendable_outputs {
4268         ($node: expr, $der_idx: expr, $keysinterface: expr, $chan_value: expr) => {
4269                 {
4270                         let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
4271                         let mut txn = Vec::new();
4272                         for event in events {
4273                                 match event {
4274                                         Event::SpendableOutputs { ref outputs } => {
4275                                                 for outp in outputs {
4276                                                         match *outp {
4277                                                                 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
4278                                                                         let input = TxIn {
4279                                                                                 previous_output: outpoint.clone(),
4280                                                                                 script_sig: Script::new(),
4281                                                                                 sequence: 0,
4282                                                                                 witness: Vec::new(),
4283                                                                         };
4284                                                                         let outp = TxOut {
4285                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4286                                                                                 value: output.value,
4287                                                                         };
4288                                                                         let mut spend_tx = Transaction {
4289                                                                                 version: 2,
4290                                                                                 lock_time: 0,
4291                                                                                 input: vec![input],
4292                                                                                 output: vec![outp],
4293                                                                         };
4294                                                                         let secp_ctx = Secp256k1::new();
4295                                                                         let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
4296                                                                         let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
4297                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4298                                                                         let remotesig = secp_ctx.sign(&sighash, key);
4299                                                                         spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
4300                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4301                                                                         spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
4302                                                                         txn.push(spend_tx);
4303                                                                 },
4304                                                                 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref per_commitment_point, ref to_self_delay, ref output, ref key_derivation_params, ref remote_revocation_pubkey } => {
4305                                                                         let input = TxIn {
4306                                                                                 previous_output: outpoint.clone(),
4307                                                                                 script_sig: Script::new(),
4308                                                                                 sequence: *to_self_delay as u32,
4309                                                                                 witness: Vec::new(),
4310                                                                         };
4311                                                                         let outp = TxOut {
4312                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4313                                                                                 value: output.value,
4314                                                                         };
4315                                                                         let mut spend_tx = Transaction {
4316                                                                                 version: 2,
4317                                                                                 lock_time: 0,
4318                                                                                 input: vec![input],
4319                                                                                 output: vec![outp],
4320                                                                         };
4321                                                                         let secp_ctx = Secp256k1::new();
4322                                                                         let keys = $keysinterface.derive_channel_keys($chan_value, key_derivation_params.0, key_derivation_params.1);
4323                                                                         if let Ok(delayed_payment_key) = chan_utils::derive_private_key(&secp_ctx, &per_commitment_point, keys.delayed_payment_base_key()) {
4324
4325                                                                                 let delayed_payment_pubkey = PublicKey::from_secret_key(&secp_ctx, &delayed_payment_key);
4326                                                                                 let witness_script = chan_utils::get_revokeable_redeemscript(remote_revocation_pubkey, *to_self_delay, &delayed_payment_pubkey);
4327                                                                                 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4328                                                                                 let local_delayedsig = secp_ctx.sign(&sighash, &delayed_payment_key);
4329                                                                                 spend_tx.input[0].witness.push(local_delayedsig.serialize_der().to_vec());
4330                                                                                 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4331                                                                                 spend_tx.input[0].witness.push(vec!()); //MINIMALIF
4332                                                                                 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
4333                                                                         } else { panic!() }
4334                                                                         txn.push(spend_tx);
4335                                                                 },
4336                                                                 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
4337                                                                         let secp_ctx = Secp256k1::new();
4338                                                                         let input = TxIn {
4339                                                                                 previous_output: outpoint.clone(),
4340                                                                                 script_sig: Script::new(),
4341                                                                                 sequence: 0,
4342                                                                                 witness: Vec::new(),
4343                                                                         };
4344                                                                         let outp = TxOut {
4345                                                                                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
4346                                                                                 value: output.value,
4347                                                                         };
4348                                                                         let mut spend_tx = Transaction {
4349                                                                                 version: 2,
4350                                                                                 lock_time: 0,
4351                                                                                 input: vec![input],
4352                                                                                 output: vec![outp.clone()],
4353                                                                         };
4354                                                                         let secret = {
4355                                                                                 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
4356                                                                                         Ok(master_key) => {
4357                                                                                                 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
4358                                                                                                         Ok(key) => key,
4359                                                                                                         Err(_) => panic!("Your RNG is busted"),
4360                                                                                                 }
4361                                                                                         }
4362                                                                                         Err(_) => panic!("Your rng is busted"),
4363                                                                                 }
4364                                                                         };
4365                                                                         let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
4366                                                                         let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
4367                                                                         let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
4368                                                                         let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
4369                                                                         spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
4370                                                                         spend_tx.input[0].witness[0].push(SigHashType::All as u8);
4371                                                                         spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
4372                                                                         txn.push(spend_tx);
4373                                                                 },
4374                                                         }
4375                                                 }
4376                                         },
4377                                         _ => panic!("Unexpected event"),
4378                                 };
4379                         }
4380                         txn
4381                 }
4382         }
4383 }
4384
4385 #[test]
4386 fn test_claim_sizeable_push_msat() {
4387         // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
4388         let chanmon_cfgs = create_chanmon_cfgs(2);
4389         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4390         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4391         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4392
4393         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4394         nodes[1].node.force_close_channel(&chan.2);
4395         check_closed_broadcast!(nodes[1], false);
4396         check_added_monitors!(nodes[1], 1);
4397         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4398         assert_eq!(node_txn.len(), 1);
4399         check_spends!(node_txn[0], chan.3);
4400         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
4401
4402         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4403         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4404         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4405
4406         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4407         assert_eq!(spend_txn.len(), 1);
4408         check_spends!(spend_txn[0], node_txn[0]);
4409 }
4410
4411 #[test]
4412 fn test_claim_on_remote_sizeable_push_msat() {
4413         // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4414         // to_remote output is encumbered by a P2WPKH
4415         let chanmon_cfgs = create_chanmon_cfgs(2);
4416         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4417         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4418         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4419
4420         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000, InitFeatures::known(), InitFeatures::known());
4421         nodes[0].node.force_close_channel(&chan.2);
4422         check_closed_broadcast!(nodes[0], false);
4423         check_added_monitors!(nodes[0], 1);
4424
4425         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4426         assert_eq!(node_txn.len(), 1);
4427         check_spends!(node_txn[0], chan.3);
4428         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
4429
4430         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4431         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
4432         check_closed_broadcast!(nodes[1], false);
4433         check_added_monitors!(nodes[1], 1);
4434         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4435
4436         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4437         assert_eq!(spend_txn.len(), 2);
4438         assert_eq!(spend_txn[0], spend_txn[1]);
4439         check_spends!(spend_txn[0], node_txn[0]);
4440 }
4441
4442 #[test]
4443 fn test_claim_on_remote_revoked_sizeable_push_msat() {
4444         // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
4445         // to_remote output is encumbered by a P2WPKH
4446
4447         let chanmon_cfgs = create_chanmon_cfgs(2);
4448         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4449         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4450         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4451
4452         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000, InitFeatures::known(), InitFeatures::known());
4453         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4454         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan.2);
4455         assert_eq!(revoked_local_txn[0].input.len(), 1);
4456         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
4457
4458         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4459         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4460         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4461         check_closed_broadcast!(nodes[1], false);
4462         check_added_monitors!(nodes[1], 1);
4463
4464         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4465         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4466         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4467         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4468
4469         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4470         assert_eq!(spend_txn.len(), 3);
4471         assert_eq!(spend_txn[0], spend_txn[1]); // to_remote output on revoked remote commitment_tx
4472         check_spends!(spend_txn[0], revoked_local_txn[0]);
4473         check_spends!(spend_txn[2], node_txn[0]);
4474 }
4475
4476 #[test]
4477 fn test_static_spendable_outputs_preimage_tx() {
4478         let chanmon_cfgs = create_chanmon_cfgs(2);
4479         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4480         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4481         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4482
4483         // Create some initial channels
4484         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4485
4486         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4487
4488         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4489         assert_eq!(commitment_tx[0].input.len(), 1);
4490         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4491
4492         // Settle A's commitment tx on B's chain
4493         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4494         assert!(nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000));
4495         check_added_monitors!(nodes[1], 1);
4496         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
4497         check_added_monitors!(nodes[1], 1);
4498         let events = nodes[1].node.get_and_clear_pending_msg_events();
4499         match events[0] {
4500                 MessageSendEvent::UpdateHTLCs { .. } => {},
4501                 _ => panic!("Unexpected event"),
4502         }
4503         match events[1] {
4504                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4505                 _ => panic!("Unexepected event"),
4506         }
4507
4508         // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
4509         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 2 (local commitment tx + HTLC-Success), ChannelMonitor: preimage tx
4510         assert_eq!(node_txn.len(), 3);
4511         check_spends!(node_txn[0], commitment_tx[0]);
4512         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4513         check_spends!(node_txn[1], chan_1.3);
4514         check_spends!(node_txn[2], node_txn[1]);
4515
4516         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4517         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4518         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4519
4520         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4521         assert_eq!(spend_txn.len(), 1);
4522         check_spends!(spend_txn[0], node_txn[0]);
4523 }
4524
4525 #[test]
4526 fn test_static_spendable_outputs_timeout_tx() {
4527         let chanmon_cfgs = create_chanmon_cfgs(2);
4528         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4529         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4530         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4531
4532         // Create some initial channels
4533         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4534
4535         // Rebalance the network a bit by relaying one payment through all the channels ...
4536         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
4537
4538         let (_, our_payment_hash) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000);
4539
4540         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4541         assert_eq!(commitment_tx[0].input.len(), 1);
4542         assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
4543
4544         // Settle A's commitment tx on B' chain
4545         let header = BlockHeader { version: 0x2000_0000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4546         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 0);
4547         check_added_monitors!(nodes[1], 1);
4548         let events = nodes[1].node.get_and_clear_pending_msg_events();
4549         match events[0] {
4550                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4551                 _ => panic!("Unexpected event"),
4552         }
4553
4554         // Check B's monitor was able to send back output descriptor event for timeout tx on A's commitment tx
4555         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4556         assert_eq!(node_txn.len(), 3); // ChannelManager : 2 (local commitent tx + HTLC-timeout), ChannelMonitor: timeout tx
4557         check_spends!(node_txn[0],  commitment_tx[0].clone());
4558         assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4559         check_spends!(node_txn[1], chan_1.3.clone());
4560         check_spends!(node_txn[2], node_txn[1]);
4561
4562         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4563         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4564         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4565         expect_payment_failed!(nodes[1], our_payment_hash, true);
4566
4567         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4568         assert_eq!(spend_txn.len(), 3); // SpendableOutput: remote_commitment_tx.to_remote (*2), timeout_tx.output (*1)
4569         check_spends!(spend_txn[2], node_txn[0].clone());
4570 }
4571
4572 #[test]
4573 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
4574         let chanmon_cfgs = create_chanmon_cfgs(2);
4575         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4576         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4577         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4578
4579         // Create some initial channels
4580         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4581
4582         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4583         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4584         assert_eq!(revoked_local_txn[0].input.len(), 1);
4585         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4586
4587         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4588
4589         let  header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4590         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 0);
4591         check_closed_broadcast!(nodes[1], false);
4592         check_added_monitors!(nodes[1], 1);
4593
4594         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4595         assert_eq!(node_txn.len(), 2);
4596         assert_eq!(node_txn[0].input.len(), 2);
4597         check_spends!(node_txn[0], revoked_local_txn[0]);
4598
4599         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4600         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone()] }, 1);
4601         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4602
4603         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4604         assert_eq!(spend_txn.len(), 1);
4605         check_spends!(spend_txn[0], node_txn[0]);
4606 }
4607
4608 #[test]
4609 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
4610         let chanmon_cfgs = create_chanmon_cfgs(2);
4611         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4612         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4613         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4614
4615         // Create some initial channels
4616         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4617
4618         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4619         let revoked_local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
4620         assert_eq!(revoked_local_txn[0].input.len(), 1);
4621         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4622
4623         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4624
4625         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4626         // A will generate HTLC-Timeout from revoked commitment tx
4627         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4628         check_closed_broadcast!(nodes[0], false);
4629         check_added_monitors!(nodes[0], 1);
4630
4631         let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4632         assert_eq!(revoked_htlc_txn.len(), 2);
4633         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4634         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4635         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4636         check_spends!(revoked_htlc_txn[1], chan_1.3);
4637
4638         // B will generate justice tx from A's revoked commitment/HTLC tx
4639         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 0);
4640         check_closed_broadcast!(nodes[1], false);
4641         check_added_monitors!(nodes[1], 1);
4642
4643         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4644         assert_eq!(node_txn.len(), 4); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-timeout, adjusted justice tx, ChannelManager: local commitment tx
4645         assert_eq!(node_txn[0].input.len(), 2);
4646         check_spends!(node_txn[0], revoked_local_txn[0]);
4647         check_spends!(node_txn[1], chan_1.3);
4648         assert_eq!(node_txn[2].input.len(), 1);
4649         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4650         assert_eq!(node_txn[3].input.len(), 1);
4651         check_spends!(node_txn[3], revoked_local_txn[0]);
4652
4653         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4654         nodes[1].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4655         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4656
4657         // Check B's ChannelMonitor was able to generate the right spendable output descriptor
4658         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4659         assert_eq!(spend_txn.len(), 2);
4660         check_spends!(spend_txn[0], node_txn[0]);
4661         check_spends!(spend_txn[1], node_txn[2]);
4662 }
4663
4664 #[test]
4665 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
4666         let chanmon_cfgs = create_chanmon_cfgs(2);
4667         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4668         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4669         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4670
4671         // Create some initial channels
4672         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4673
4674         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
4675         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4676         assert_eq!(revoked_local_txn[0].input.len(), 1);
4677         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
4678
4679         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
4680
4681         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4682         // B will generate HTLC-Success from revoked commitment tx
4683         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
4684         check_closed_broadcast!(nodes[1], false);
4685         check_added_monitors!(nodes[1], 1);
4686         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4687
4688         assert_eq!(revoked_htlc_txn.len(), 2);
4689         assert_eq!(revoked_htlc_txn[0].input.len(), 1);
4690         assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4691         check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
4692
4693         // A will generate justice tx from B's revoked commitment/HTLC tx
4694         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
4695         check_closed_broadcast!(nodes[0], false);
4696         check_added_monitors!(nodes[0], 1);
4697
4698         let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4699         assert_eq!(node_txn.len(), 3); // ChannelMonitor: justice tx on revoked commitment, justice tx on revoked HTLC-success, ChannelManager: local commitment tx
4700         assert_eq!(node_txn[2].input.len(), 1);
4701         check_spends!(node_txn[2], revoked_htlc_txn[0]);
4702
4703         let header_1 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4704         nodes[0].block_notifier.block_connected(&Block { header: header_1, txdata: vec![node_txn[0].clone(), node_txn[2].clone()] }, 1);
4705         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true, header.bitcoin_hash());
4706
4707         // Check A's ChannelMonitor was able to generate the right spendable output descriptor
4708         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
4709         assert_eq!(spend_txn.len(), 5); // Duplicated SpendableOutput due to block rescan after revoked htlc output tracking
4710         assert_eq!(spend_txn[0], spend_txn[1]);
4711         assert_eq!(spend_txn[0], spend_txn[2]);
4712         check_spends!(spend_txn[0], revoked_local_txn[0]); // spending to_remote output from revoked local tx
4713         check_spends!(spend_txn[3], node_txn[0]); // spending justice tx output from revoked local tx htlc received output
4714         check_spends!(spend_txn[4], node_txn[2]); // spending justice tx output on htlc success tx
4715 }
4716
4717 #[test]
4718 fn test_onchain_to_onchain_claim() {
4719         // Test that in case of channel closure, we detect the state of output thanks to
4720         // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
4721         // First, have C claim an HTLC against its own latest commitment transaction.
4722         // Then, broadcast these to B, which should update the monitor downstream on the A<->B
4723         // channel.
4724         // Finally, check that B will claim the HTLC output if A's latest commitment transaction
4725         // gets broadcast.
4726
4727         let chanmon_cfgs = create_chanmon_cfgs(3);
4728         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4729         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4730         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4731
4732         // Create some initial channels
4733         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4734         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4735
4736         // Rebalance the network a bit by relaying one payment through all the channels ...
4737         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4738         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000, 8_000_000);
4739
4740         let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
4741         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
4742         let commitment_tx = get_local_commitment_txn!(nodes[2], chan_2.2);
4743         check_spends!(commitment_tx[0], chan_2.3);
4744         nodes[2].node.claim_funds(payment_preimage, &None, 3_000_000);
4745         check_added_monitors!(nodes[2], 1);
4746         let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4747         assert!(updates.update_add_htlcs.is_empty());
4748         assert!(updates.update_fail_htlcs.is_empty());
4749         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4750         assert!(updates.update_fail_malformed_htlcs.is_empty());
4751
4752         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4753         check_closed_broadcast!(nodes[2], false);
4754         check_added_monitors!(nodes[2], 1);
4755
4756         let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
4757         assert_eq!(c_txn.len(), 3);
4758         assert_eq!(c_txn[0], c_txn[2]);
4759         assert_eq!(commitment_tx[0], c_txn[1]);
4760         check_spends!(c_txn[1], chan_2.3);
4761         check_spends!(c_txn[2], c_txn[1]);
4762         assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
4763         assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4764         assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4765         assert_eq!(c_txn[0].lock_time, 0); // Success tx
4766
4767         // 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
4768         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
4769         {
4770                 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4771                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-timeout tx
4772                 assert_eq!(b_txn.len(), 3);
4773                 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
4774                 check_spends!(b_txn[2], b_txn[1]); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
4775                 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4776                 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
4777                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4778                 check_spends!(b_txn[0], c_txn[1]); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
4779                 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4780                 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4781                 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
4782                 b_txn.clear();
4783         }
4784         check_added_monitors!(nodes[1], 1);
4785         let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4786         check_added_monitors!(nodes[1], 1);
4787         match msg_events[0] {
4788                 MessageSendEvent::BroadcastChannelUpdate {  .. } => {},
4789                 _ => panic!("Unexpected event"),
4790         }
4791         match msg_events[1] {
4792                 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, .. } } => {
4793                         assert!(update_add_htlcs.is_empty());
4794                         assert!(update_fail_htlcs.is_empty());
4795                         assert_eq!(update_fulfill_htlcs.len(), 1);
4796                         assert!(update_fail_malformed_htlcs.is_empty());
4797                         assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
4798                 },
4799                 _ => panic!("Unexpected event"),
4800         };
4801         // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
4802         let commitment_tx = get_local_commitment_txn!(nodes[0], chan_1.2);
4803         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
4804         let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4805         // ChannelMonitor: HTLC-Success tx, ChannelManager: local commitment tx + HTLC-Success tx
4806         assert_eq!(b_txn.len(), 3);
4807         check_spends!(b_txn[1], chan_1.3);
4808         check_spends!(b_txn[2], b_txn[1]);
4809         check_spends!(b_txn[0], commitment_tx[0]);
4810         assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4811         assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
4812         assert_eq!(b_txn[0].lock_time, 0); // Success tx
4813
4814         check_closed_broadcast!(nodes[1], false);
4815         check_added_monitors!(nodes[1], 1);
4816 }
4817
4818 #[test]
4819 fn test_duplicate_payment_hash_one_failure_one_success() {
4820         // Topology : A --> B --> C
4821         // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
4822         let chanmon_cfgs = create_chanmon_cfgs(3);
4823         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
4824         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
4825         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
4826
4827         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4828         let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
4829
4830         let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
4831         *nodes[0].network_payment_count.borrow_mut() -= 1;
4832         assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
4833
4834         let commitment_txn = get_local_commitment_txn!(nodes[2], chan_2.2);
4835         assert_eq!(commitment_txn[0].input.len(), 1);
4836         check_spends!(commitment_txn[0], chan_2.3);
4837
4838         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4839         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4840         check_closed_broadcast!(nodes[1], false);
4841         check_added_monitors!(nodes[1], 1);
4842
4843         let htlc_timeout_tx;
4844         { // Extract one of the two HTLC-Timeout transaction
4845                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4846                 // ChannelMonitor: timeout tx * 2, ChannelManager: local commitment tx + HTLC-timeout * 2
4847                 assert_eq!(node_txn.len(), 5);
4848                 check_spends!(node_txn[0], commitment_txn[0]);
4849                 assert_eq!(node_txn[0].input.len(), 1);
4850                 check_spends!(node_txn[1], commitment_txn[0]);
4851                 assert_eq!(node_txn[1].input.len(), 1);
4852                 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
4853                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4854                 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4855                 check_spends!(node_txn[2], chan_2.3);
4856                 check_spends!(node_txn[3], node_txn[2]);
4857                 check_spends!(node_txn[4], node_txn[2]);
4858                 htlc_timeout_tx = node_txn[1].clone();
4859         }
4860
4861         nodes[2].node.claim_funds(our_payment_preimage, &None, 900_000);
4862         nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
4863         check_added_monitors!(nodes[2], 3);
4864         let events = nodes[2].node.get_and_clear_pending_msg_events();
4865         match events[0] {
4866                 MessageSendEvent::UpdateHTLCs { .. } => {},
4867                 _ => panic!("Unexpected event"),
4868         }
4869         match events[1] {
4870                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4871                 _ => panic!("Unexepected event"),
4872         }
4873         let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
4874         assert_eq!(htlc_success_txn.len(), 5); // ChannelMonitor: HTLC-Success txn (*2 due to 2-HTLC outputs), ChannelManager: local commitment tx + HTLC-Success txn (*2 due to 2-HTLC outputs)
4875         check_spends!(htlc_success_txn[2], chan_2.3);
4876         check_spends!(htlc_success_txn[3], htlc_success_txn[2]);
4877         check_spends!(htlc_success_txn[4], htlc_success_txn[2]);
4878         assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
4879         assert_eq!(htlc_success_txn[0].input.len(), 1);
4880         assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4881         assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
4882         assert_eq!(htlc_success_txn[1].input.len(), 1);
4883         assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4884         assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
4885         check_spends!(htlc_success_txn[0], commitment_txn[0]);
4886         check_spends!(htlc_success_txn[1], commitment_txn[0]);
4887
4888         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
4889         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 200, true, header.bitcoin_hash());
4890         expect_pending_htlcs_forwardable!(nodes[1]);
4891         let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4892         assert!(htlc_updates.update_add_htlcs.is_empty());
4893         assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
4894         assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
4895         assert!(htlc_updates.update_fulfill_htlcs.is_empty());
4896         assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
4897         check_added_monitors!(nodes[1], 1);
4898
4899         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]);
4900         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
4901         {
4902                 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
4903                 let events = nodes[0].node.get_and_clear_pending_msg_events();
4904                 assert_eq!(events.len(), 1);
4905                 match events[0] {
4906                         MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. }  } => {
4907                         },
4908                         _ => { panic!("Unexpected event"); }
4909                 }
4910         }
4911         expect_payment_failed!(nodes[0], duplicate_payment_hash, false);
4912
4913         // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
4914         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
4915         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4916         assert!(updates.update_add_htlcs.is_empty());
4917         assert!(updates.update_fail_htlcs.is_empty());
4918         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
4919         assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
4920         assert!(updates.update_fail_malformed_htlcs.is_empty());
4921         check_added_monitors!(nodes[1], 1);
4922
4923         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
4924         commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
4925
4926         let events = nodes[0].node.get_and_clear_pending_events();
4927         match events[0] {
4928                 Event::PaymentSent { ref payment_preimage } => {
4929                         assert_eq!(*payment_preimage, our_payment_preimage);
4930                 }
4931                 _ => panic!("Unexpected event"),
4932         }
4933 }
4934
4935 #[test]
4936 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
4937         let chanmon_cfgs = create_chanmon_cfgs(2);
4938         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
4939         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
4940         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
4941
4942         // Create some initial channels
4943         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
4944
4945         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4946         let local_txn = get_local_commitment_txn!(nodes[1], chan_1.2);
4947         assert_eq!(local_txn[0].input.len(), 1);
4948         check_spends!(local_txn[0], chan_1.3);
4949
4950         // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
4951         nodes[1].node.claim_funds(payment_preimage, &None, 9_000_000);
4952         check_added_monitors!(nodes[1], 1);
4953         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(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
4955         check_added_monitors!(nodes[1], 1);
4956         let events = nodes[1].node.get_and_clear_pending_msg_events();
4957         match events[0] {
4958                 MessageSendEvent::UpdateHTLCs { .. } => {},
4959                 _ => panic!("Unexpected event"),
4960         }
4961         match events[1] {
4962                 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
4963                 _ => panic!("Unexepected event"),
4964         }
4965         let node_txn = {
4966                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
4967                 assert_eq!(node_txn[0].input.len(), 1);
4968                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
4969                 check_spends!(node_txn[0], local_txn[0]);
4970                 vec![node_txn[0].clone(), node_txn[2].clone()]
4971         };
4972
4973         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4974         nodes[1].block_notifier.block_connected(&Block { header: header_201, txdata: node_txn.clone() }, 201);
4975         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
4976
4977         // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
4978         let spend_txn = check_spendable_outputs!(nodes[1], 1, node_cfgs[1].keys_manager, 100000);
4979         assert_eq!(spend_txn.len(), 2);
4980         check_spends!(spend_txn[0], node_txn[0]);
4981         check_spends!(spend_txn[1], node_txn[1]);
4982 }
4983
4984 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
4985         // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
4986         // unrevoked commitment transaction.
4987         // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
4988         // a remote RAA before they could be failed backwards (and combinations thereof).
4989         // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
4990         // use the same payment hashes.
4991         // Thus, we use a six-node network:
4992         //
4993         // A \         / E
4994         //    - C - D -
4995         // B /         \ F
4996         // And test where C fails back to A/B when D announces its latest commitment transaction
4997         let chanmon_cfgs = create_chanmon_cfgs(6);
4998         let node_cfgs = create_node_cfgs(6, &chanmon_cfgs);
4999         let node_chanmgrs = create_node_chanmgrs(6, &node_cfgs, &[None, None, None, None, None, None]);
5000         let nodes = create_network(6, &node_cfgs, &node_chanmgrs);
5001         let logger = test_utils::TestLogger::new();
5002
5003         create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known());
5004         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
5005         let chan = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known());
5006         create_announced_chan_between_nodes(&nodes, 3, 4, InitFeatures::known(), InitFeatures::known());
5007         create_announced_chan_between_nodes(&nodes, 3, 5, InitFeatures::known(), InitFeatures::known());
5008
5009         // Rebalance and check output sanity...
5010         send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000, 500_000);
5011         send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000, 500_000);
5012         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 2);
5013
5014         let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
5015         // 0th HTLC:
5016         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
5017         // 1st HTLC:
5018         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
5019         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
5020         let our_node_id = &nodes[1].node.get_our_node_id();
5021         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5022         // 2nd HTLC:
5023         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
5024         // 3rd HTLC:
5025         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
5026         // 4th HTLC:
5027         let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5028         // 5th HTLC:
5029         let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5030         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5031         // 6th HTLC:
5032         send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
5033         // 7th HTLC:
5034         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
5035
5036         // 8th HTLC:
5037         let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
5038         // 9th HTLC:
5039         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV, &logger).unwrap();
5040         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
5041
5042         // 10th HTLC:
5043         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
5044         // 11th HTLC:
5045         let route = get_route(our_node_id, net_graph_msg_handler, &nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV, &logger).unwrap();
5046         send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
5047
5048         // Double-check that six of the new HTLC were added
5049         // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
5050         // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
5051         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2).len(), 1);
5052         assert_eq!(get_local_commitment_txn!(nodes[3], chan.2)[0].output.len(), 8);
5053
5054         // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
5055         // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
5056         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1, &None));
5057         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3, &None));
5058         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5, &None));
5059         assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6, &None));
5060         check_added_monitors!(nodes[4], 0);
5061         expect_pending_htlcs_forwardable!(nodes[4]);
5062         check_added_monitors!(nodes[4], 1);
5063
5064         let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
5065         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]);
5066         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]);
5067         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]);
5068         nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]);
5069         commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
5070
5071         // Fail 3rd below-dust and 7th above-dust HTLCs
5072         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2, &None));
5073         assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4, &None));
5074         check_added_monitors!(nodes[5], 0);
5075         expect_pending_htlcs_forwardable!(nodes[5]);
5076         check_added_monitors!(nodes[5], 1);
5077
5078         let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
5079         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]);
5080         nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]);
5081         commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
5082
5083         let ds_prev_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5084
5085         expect_pending_htlcs_forwardable!(nodes[3]);
5086         check_added_monitors!(nodes[3], 1);
5087         let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
5088         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]);
5089         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]);
5090         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]);
5091         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]);
5092         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]);
5093         nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]);
5094         if deliver_last_raa {
5095                 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
5096         } else {
5097                 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
5098         }
5099
5100         // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
5101         // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
5102         // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
5103         // propagated back to A/B yet (and D has two unrevoked commitment transactions).
5104         //
5105         // We now broadcast the latest commitment transaction, which *should* result in failures for
5106         // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
5107         // the non-broadcast above-dust HTLCs.
5108         //
5109         // Alternatively, we may broadcast the previous commitment transaction, which should only
5110         // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
5111         let ds_last_commitment_tx = get_local_commitment_txn!(nodes[3], chan.2);
5112
5113         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5114         if announce_latest {
5115                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_last_commitment_tx[0].clone()]}, 1);
5116         } else {
5117                 nodes[2].block_notifier.block_connected(&Block { header, txdata: vec![ds_prev_commitment_tx[0].clone()]}, 1);
5118         }
5119         connect_blocks(&nodes[2].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
5120         check_closed_broadcast!(nodes[2], false);
5121         expect_pending_htlcs_forwardable!(nodes[2]);
5122         check_added_monitors!(nodes[2], 3);
5123
5124         let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
5125         assert_eq!(cs_msgs.len(), 2);
5126         let mut a_done = false;
5127         for msg in cs_msgs {
5128                 match msg {
5129                         MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
5130                                 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
5131                                 // should be failed-backwards here.
5132                                 let target = if *node_id == nodes[0].node.get_our_node_id() {
5133                                         // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
5134                                         for htlc in &updates.update_fail_htlcs {
5135                                                 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 });
5136                                         }
5137                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
5138                                         assert!(!a_done);
5139                                         a_done = true;
5140                                         &nodes[0]
5141                                 } else {
5142                                         // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
5143                                         for htlc in &updates.update_fail_htlcs {
5144                                                 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
5145                                         }
5146                                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
5147                                         assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
5148                                         &nodes[1]
5149                                 };
5150                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]);
5151                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]);
5152                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]);
5153                                 if announce_latest {
5154                                         target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]);
5155                                         if *node_id == nodes[0].node.get_our_node_id() {
5156                                                 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]);
5157                                         }
5158                                 }
5159                                 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
5160                         },
5161                         _ => panic!("Unexpected event"),
5162                 }
5163         }
5164
5165         let as_events = nodes[0].node.get_and_clear_pending_events();
5166         assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
5167         let mut as_failds = HashSet::new();
5168         for event in as_events.iter() {
5169                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5170                         assert!(as_failds.insert(*payment_hash));
5171                         if *payment_hash != payment_hash_2 {
5172                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5173                         } else {
5174                                 assert!(!rejected_by_dest);
5175                         }
5176                 } else { panic!("Unexpected event"); }
5177         }
5178         assert!(as_failds.contains(&payment_hash_1));
5179         assert!(as_failds.contains(&payment_hash_2));
5180         if announce_latest {
5181                 assert!(as_failds.contains(&payment_hash_3));
5182                 assert!(as_failds.contains(&payment_hash_5));
5183         }
5184         assert!(as_failds.contains(&payment_hash_6));
5185
5186         let bs_events = nodes[1].node.get_and_clear_pending_events();
5187         assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
5188         let mut bs_failds = HashSet::new();
5189         for event in bs_events.iter() {
5190                 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
5191                         assert!(bs_failds.insert(*payment_hash));
5192                         if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
5193                                 assert_eq!(*rejected_by_dest, deliver_last_raa);
5194                         } else {
5195                                 assert!(!rejected_by_dest);
5196                         }
5197                 } else { panic!("Unexpected event"); }
5198         }
5199         assert!(bs_failds.contains(&payment_hash_1));
5200         assert!(bs_failds.contains(&payment_hash_2));
5201         if announce_latest {
5202                 assert!(bs_failds.contains(&payment_hash_4));
5203         }
5204         assert!(bs_failds.contains(&payment_hash_5));
5205
5206         // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
5207         // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
5208         // to unknown-preimage-etc, B should have gotten 2. Thus, in the
5209         // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
5210         // PaymentFailureNetworkUpdates.
5211         let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
5212         assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
5213         let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
5214         assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
5215         for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
5216                 match event {
5217                         &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
5218                         _ => panic!("Unexpected event"),
5219                 }
5220         }
5221 }
5222
5223 #[test]
5224 fn test_fail_backwards_latest_remote_announce_a() {
5225         do_test_fail_backwards_unrevoked_remote_announce(false, true);
5226 }
5227
5228 #[test]
5229 fn test_fail_backwards_latest_remote_announce_b() {
5230         do_test_fail_backwards_unrevoked_remote_announce(true, true);
5231 }
5232
5233 #[test]
5234 fn test_fail_backwards_previous_remote_announce() {
5235         do_test_fail_backwards_unrevoked_remote_announce(false, false);
5236         // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
5237         // tested for in test_commitment_revoked_fail_backward_exhaustive()
5238 }
5239
5240 #[test]
5241 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
5242         let chanmon_cfgs = create_chanmon_cfgs(2);
5243         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5244         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5245         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5246
5247         // Create some initial channels
5248         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5249
5250         let (_, our_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000);
5251         let local_txn = get_local_commitment_txn!(nodes[0], chan_1.2);
5252         assert_eq!(local_txn[0].input.len(), 1);
5253         check_spends!(local_txn[0], chan_1.3);
5254
5255         // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
5256         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5257         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
5258         check_closed_broadcast!(nodes[0], false);
5259         check_added_monitors!(nodes[0], 1);
5260
5261         let htlc_timeout = {
5262                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
5263                 assert_eq!(node_txn[0].input.len(), 1);
5264                 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
5265                 check_spends!(node_txn[0], local_txn[0]);
5266                 node_txn[0].clone()
5267         };
5268
5269         let header_201 = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5270         nodes[0].block_notifier.block_connected(&Block { header: header_201, txdata: vec![htlc_timeout.clone()] }, 201);
5271         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 201, true, header_201.bitcoin_hash());
5272         expect_payment_failed!(nodes[0], our_payment_hash, true);
5273
5274         // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
5275         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
5276         assert_eq!(spend_txn.len(), 3);
5277         assert_eq!(spend_txn[0], spend_txn[1]);
5278         check_spends!(spend_txn[0], local_txn[0]);
5279         check_spends!(spend_txn[2], htlc_timeout);
5280 }
5281
5282 #[test]
5283 fn test_static_output_closing_tx() {
5284         let chanmon_cfgs = create_chanmon_cfgs(2);
5285         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5286         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5287         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5288
5289         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5290
5291         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
5292         let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
5293
5294         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5295         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5296         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5297
5298         let spend_txn = check_spendable_outputs!(nodes[0], 2, node_cfgs[0].keys_manager, 100000);
5299         assert_eq!(spend_txn.len(), 1);
5300         check_spends!(spend_txn[0], closing_tx);
5301
5302         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![closing_tx.clone()] }, 0);
5303         connect_blocks(&nodes[1].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
5304
5305         let spend_txn = check_spendable_outputs!(nodes[1], 2, node_cfgs[1].keys_manager, 100000);
5306         assert_eq!(spend_txn.len(), 1);
5307         check_spends!(spend_txn[0], closing_tx);
5308 }
5309
5310 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
5311         let chanmon_cfgs = create_chanmon_cfgs(2);
5312         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5313         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5314         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5315         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5316
5317         let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
5318
5319         // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
5320         // present in B's local commitment transaction, but none of A's commitment transactions.
5321         assert!(nodes[1].node.claim_funds(our_payment_preimage, &None, if use_dust { 50_000 } else { 3_000_000 }));
5322         check_added_monitors!(nodes[1], 1);
5323
5324         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5325         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]);
5326         let events = nodes[0].node.get_and_clear_pending_events();
5327         assert_eq!(events.len(), 1);
5328         match events[0] {
5329                 Event::PaymentSent { payment_preimage } => {
5330                         assert_eq!(payment_preimage, our_payment_preimage);
5331                 },
5332                 _ => panic!("Unexpected event"),
5333         }
5334
5335         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5336         check_added_monitors!(nodes[0], 1);
5337         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5338         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5339         check_added_monitors!(nodes[1], 1);
5340
5341         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5342         for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
5343                 nodes[1].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5344                 header.prev_blockhash = header.bitcoin_hash();
5345         }
5346         test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
5347         check_closed_broadcast!(nodes[1], false);
5348         check_added_monitors!(nodes[1], 1);
5349 }
5350
5351 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
5352         let chanmon_cfgs = create_chanmon_cfgs(2);
5353         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5354         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5355         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5356         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5357         let logger = test_utils::TestLogger::new();
5358
5359         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5360         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5361         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV, &logger).unwrap();
5362         nodes[0].node.send_payment(&route, payment_hash, &None).unwrap();
5363         check_added_monitors!(nodes[0], 1);
5364
5365         let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5366
5367         // As far as A is concerned, the HTLC is now present only in the latest remote commitment
5368         // transaction, however it is not in A's latest local commitment, so we can just broadcast that
5369         // to "time out" the HTLC.
5370
5371         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5372
5373         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5374                 nodes[0].block_notifier.block_connected(&Block { header, txdata: Vec::new()}, i);
5375                 header.prev_blockhash = header.bitcoin_hash();
5376         }
5377         test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5378         check_closed_broadcast!(nodes[0], false);
5379         check_added_monitors!(nodes[0], 1);
5380 }
5381
5382 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
5383         let chanmon_cfgs = create_chanmon_cfgs(3);
5384         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5385         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5386         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5387         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
5388
5389         // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
5390         // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
5391         // Also optionally test that we *don't* fail the channel in case the commitment transaction was
5392         // actually revoked.
5393         let htlc_value = if use_dust { 50000 } else { 3000000 };
5394         let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
5395         assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash, &None));
5396         expect_pending_htlcs_forwardable!(nodes[1]);
5397         check_added_monitors!(nodes[1], 1);
5398
5399         let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5400         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]);
5401         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed);
5402         check_added_monitors!(nodes[0], 1);
5403         let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5404         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0);
5405         check_added_monitors!(nodes[1], 1);
5406         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1);
5407         check_added_monitors!(nodes[1], 1);
5408         let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
5409
5410         if check_revoke_no_close {
5411                 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack);
5412                 check_added_monitors!(nodes[0], 1);
5413         }
5414
5415         let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5416         for i in 1..TEST_FINAL_CLTV + LATENCY_GRACE_PERIOD_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
5417                 nodes[0].block_notifier.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
5418                 header.prev_blockhash = header.bitcoin_hash();
5419         }
5420         if !check_revoke_no_close {
5421                 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
5422                 check_closed_broadcast!(nodes[0], false);
5423                 check_added_monitors!(nodes[0], 1);
5424         } else {
5425                 expect_payment_failed!(nodes[0], our_payment_hash, true);
5426         }
5427 }
5428
5429 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
5430 // There are only a few cases to test here:
5431 //  * its not really normative behavior, but we test that below-dust HTLCs "included" in
5432 //    broadcastable commitment transactions result in channel closure,
5433 //  * its included in an unrevoked-but-previous remote commitment transaction,
5434 //  * its included in the latest remote or local commitment transactions.
5435 // We test each of the three possible commitment transactions individually and use both dust and
5436 // non-dust HTLCs.
5437 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
5438 // assume they are handled the same across all six cases, as both outbound and inbound failures are
5439 // tested for at least one of the cases in other tests.
5440 #[test]
5441 fn htlc_claim_single_commitment_only_a() {
5442         do_htlc_claim_local_commitment_only(true);
5443         do_htlc_claim_local_commitment_only(false);
5444
5445         do_htlc_claim_current_remote_commitment_only(true);
5446         do_htlc_claim_current_remote_commitment_only(false);
5447 }
5448
5449 #[test]
5450 fn htlc_claim_single_commitment_only_b() {
5451         do_htlc_claim_previous_remote_commitment_only(true, false);
5452         do_htlc_claim_previous_remote_commitment_only(false, false);
5453         do_htlc_claim_previous_remote_commitment_only(true, true);
5454         do_htlc_claim_previous_remote_commitment_only(false, true);
5455 }
5456
5457 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>)
5458         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5459                                 F2: FnMut(),
5460 {
5461         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);
5462 }
5463
5464 // test_case
5465 // 0: node1 fails backward
5466 // 1: final node fails backward
5467 // 2: payment completed but the user rejects the payment
5468 // 3: final node fails backward (but tamper onion payloads from node0)
5469 // 100: trigger error in the intermediate node and tamper returning fail_htlc
5470 // 200: trigger error in the final node and tamper returning fail_htlc
5471 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>)
5472         where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
5473                                 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
5474                                 F3: FnMut(),
5475 {
5476
5477         // reset block height
5478         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5479         for ix in 0..nodes.len() {
5480                 nodes[ix].block_notifier.block_connected_checked(&header, 1, &[], &[]);
5481         }
5482
5483         macro_rules! expect_event {
5484                 ($node: expr, $event_type: path) => {{
5485                         let events = $node.node.get_and_clear_pending_events();
5486                         assert_eq!(events.len(), 1);
5487                         match events[0] {
5488                                 $event_type { .. } => {},
5489                                 _ => panic!("Unexpected event"),
5490                         }
5491                 }}
5492         }
5493
5494         macro_rules! expect_htlc_forward {
5495                 ($node: expr) => {{
5496                         expect_event!($node, Event::PendingHTLCsForwardable);
5497                         $node.node.process_pending_htlc_forwards();
5498                 }}
5499         }
5500
5501         // 0 ~~> 2 send payment
5502         nodes[0].node.send_payment(&route, payment_hash.clone(), &None).unwrap();
5503         check_added_monitors!(nodes[0], 1);
5504         let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5505         // temper update_add (0 => 1)
5506         let mut update_add_0 = update_0.update_add_htlcs[0].clone();
5507         if test_case == 0 || test_case == 3 || test_case == 100 {
5508                 callback_msg(&mut update_add_0);
5509                 callback_node();
5510         }
5511         // 0 => 1 update_add & CS
5512         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0);
5513         commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
5514
5515         let update_1_0 = match test_case {
5516                 0|100 => { // intermediate node failure; fail backward to 0
5517                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5518                         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));
5519                         update_1_0
5520                 },
5521                 1|2|3|200 => { // final node failure; forwarding to 2
5522                         assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
5523                         // forwarding on 1
5524                         if test_case != 200 {
5525                                 callback_node();
5526                         }
5527                         expect_htlc_forward!(&nodes[1]);
5528
5529                         let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
5530                         check_added_monitors!(&nodes[1], 1);
5531                         assert_eq!(update_1.update_add_htlcs.len(), 1);
5532                         // tamper update_add (1 => 2)
5533                         let mut update_add_1 = update_1.update_add_htlcs[0].clone();
5534                         if test_case != 3 && test_case != 200 {
5535                                 callback_msg(&mut update_add_1);
5536                         }
5537
5538                         // 1 => 2
5539                         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1);
5540                         commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
5541
5542                         if test_case == 2 || test_case == 200 {
5543                                 expect_htlc_forward!(&nodes[2]);
5544                                 expect_event!(&nodes[2], Event::PaymentReceived);
5545                                 callback_node();
5546                                 expect_pending_htlcs_forwardable!(nodes[2]);
5547                         }
5548
5549                         let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
5550                         if test_case == 2 || test_case == 200 {
5551                                 check_added_monitors!(&nodes[2], 1);
5552                         }
5553                         assert!(update_2_1.update_fail_htlcs.len() == 1);
5554
5555                         let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
5556                         if test_case == 200 {
5557                                 callback_fail(&mut fail_msg);
5558                         }
5559
5560                         // 2 => 1
5561                         nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg);
5562                         commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
5563
5564                         // backward fail on 1
5565                         let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5566                         assert!(update_1_0.update_fail_htlcs.len() == 1);
5567                         update_1_0
5568                 },
5569                 _ => unreachable!(),
5570         };
5571
5572         // 1 => 0 commitment_signed_dance
5573         if update_1_0.update_fail_htlcs.len() > 0 {
5574                 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
5575                 if test_case == 100 {
5576                         callback_fail(&mut fail_msg);
5577                 }
5578                 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg);
5579         } else {
5580                 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]);
5581         };
5582
5583         commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
5584
5585         let events = nodes[0].node.get_and_clear_pending_events();
5586         assert_eq!(events.len(), 1);
5587         if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code, error_data: _ } = &events[0] {
5588                 assert_eq!(*rejected_by_dest, !expected_retryable);
5589                 assert_eq!(*error_code, expected_error_code);
5590         } else {
5591                 panic!("Uexpected event");
5592         }
5593
5594         let events = nodes[0].node.get_and_clear_pending_msg_events();
5595         if expected_channel_update.is_some() {
5596                 assert_eq!(events.len(), 1);
5597                 match events[0] {
5598                         MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
5599                                 match update {
5600                                         &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
5601                                                 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
5602                                                         panic!("channel_update not found!");
5603                                                 }
5604                                         },
5605                                         &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
5606                                                 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5607                                                         assert!(*short_channel_id == *expected_short_channel_id);
5608                                                         assert!(*is_permanent == *expected_is_permanent);
5609                                                 } else {
5610                                                         panic!("Unexpected message event");
5611                                                 }
5612                                         },
5613                                         &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
5614                                                 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
5615                                                         assert!(*node_id == *expected_node_id);
5616                                                         assert!(*is_permanent == *expected_is_permanent);
5617                                                 } else {
5618                                                         panic!("Unexpected message event");
5619                                                 }
5620                                         },
5621                                 }
5622                         },
5623                         _ => panic!("Unexpected message event"),
5624                 }
5625         } else {
5626                 assert_eq!(events.len(), 0);
5627         }
5628 }
5629
5630 impl msgs::ChannelUpdate {
5631         fn dummy() -> msgs::ChannelUpdate {
5632                 use bitcoin::secp256k1::ffi::Signature as FFISignature;
5633                 use bitcoin::secp256k1::Signature;
5634                 msgs::ChannelUpdate {
5635                         signature: Signature::from(FFISignature::new()),
5636                         contents: msgs::UnsignedChannelUpdate {
5637                                 chain_hash: BlockHash::hash(&vec![0u8][..]),
5638                                 short_channel_id: 0,
5639                                 timestamp: 0,
5640                                 flags: 0,
5641                                 cltv_expiry_delta: 0,
5642                                 htlc_minimum_msat: 0,
5643                                 fee_base_msat: 0,
5644                                 fee_proportional_millionths: 0,
5645                                 excess_data: vec![],
5646                         }
5647                 }
5648         }
5649 }
5650
5651 struct BogusOnionHopData {
5652         data: Vec<u8>
5653 }
5654 impl BogusOnionHopData {
5655         fn new(orig: msgs::OnionHopData) -> Self {
5656                 Self { data: orig.encode() }
5657         }
5658 }
5659 impl Writeable for BogusOnionHopData {
5660         fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
5661                 writer.write_all(&self.data[..])
5662         }
5663 }
5664
5665 #[test]
5666 fn test_onion_failure() {
5667         use ln::msgs::ChannelUpdate;
5668         use ln::channelmanager::CLTV_FAR_FAR_AWAY;
5669         use bitcoin::secp256k1;
5670
5671         const BADONION: u16 = 0x8000;
5672         const PERM: u16 = 0x4000;
5673         const NODE: u16 = 0x2000;
5674         const UPDATE: u16 = 0x1000;
5675
5676         let chanmon_cfgs = create_chanmon_cfgs(3);
5677         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
5678         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
5679         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
5680         for node in nodes.iter() {
5681                 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
5682         }
5683         let channels = [create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()), create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known())];
5684         let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
5685         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5686         let logger = test_utils::TestLogger::new();
5687         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV, &logger).unwrap();
5688         // positve case
5689         send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000, 40_000);
5690
5691         // intermediate node failure
5692         run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
5693                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5694                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5695                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5696                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5697                 let mut new_payloads = Vec::new();
5698                 for payload in onion_payloads.drain(..) {
5699                         new_payloads.push(BogusOnionHopData::new(payload));
5700                 }
5701                 // break the first (non-final) hop payload by swapping the realm (0) byte for a byte
5702                 // describing a length-1 TLV payload, which is obviously bogus.
5703                 new_payloads[0].data[0] = 1;
5704                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5705         }, ||{}, true, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
5706
5707         // final node failure
5708         run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
5709                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5710                 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
5711                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5712                 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, cur_height).unwrap();
5713                 let mut new_payloads = Vec::new();
5714                 for payload in onion_payloads.drain(..) {
5715                         new_payloads.push(BogusOnionHopData::new(payload));
5716                 }
5717                 // break the last-hop payload by swapping the realm (0) byte for a byte describing a
5718                 // length-1 TLV payload, which is obviously bogus.
5719                 new_payloads[1].data[0] = 1;
5720                 msg.onion_routing_packet = onion_utils::construct_onion_packet_bogus_hopdata(new_payloads, onion_keys, [0; 32], &payment_hash);
5721         }, ||{}, false, Some(PERM|22), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5722
5723         // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
5724         // receiving simulated fail messages
5725         // intermediate node failure
5726         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5727                 // trigger error
5728                 msg.amount_msat -= 1;
5729         }, |msg| {
5730                 // and tamper returning error message
5731                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5732                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5733                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
5734         }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: false}));
5735
5736         // final node failure
5737         run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5738                 // and tamper returning error message
5739                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5740                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5741                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
5742         }, ||{
5743                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5744         }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: false}));
5745
5746         // intermediate node failure
5747         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
5748                 msg.amount_msat -= 1;
5749         }, |msg| {
5750                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5751                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5752                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
5753         }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5754
5755         // final node failure
5756         run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5757                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5758                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5759                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
5760         }, ||{
5761                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5762         }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5763
5764         // intermediate node failure
5765         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5766                 msg.amount_msat -= 1;
5767         }, |msg| {
5768                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5769                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5770                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
5771         }, ||{
5772                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5773         }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][0].pubkey, is_permanent: true}));
5774
5775         // final node failure
5776         run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
5777                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5778                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5779                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
5780         }, ||{
5781                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5782         }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.paths[0][1].pubkey, is_permanent: true}));
5783
5784         run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
5785                 Some(BADONION|PERM|4), None);
5786
5787         run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
5788                 Some(BADONION|PERM|5), None);
5789
5790         run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
5791                 Some(BADONION|PERM|6), None);
5792
5793         run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5794                 msg.amount_msat -= 1;
5795         }, |msg| {
5796                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5797                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5798                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
5799         }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5800
5801         run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
5802                 msg.amount_msat -= 1;
5803         }, |msg| {
5804                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5805                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5806                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
5807                 // short_channel_id from the processing node
5808         }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5809
5810         run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
5811                 msg.amount_msat -= 1;
5812         }, |msg| {
5813                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5814                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5815                 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
5816                 // short_channel_id from the processing node
5817         }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
5818
5819         let mut bogus_route = route.clone();
5820         bogus_route.paths[0][1].short_channel_id -= 1;
5821         run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
5822           Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.paths[0][1].short_channel_id, is_permanent:true}));
5823
5824         let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
5825         let mut bogus_route = route.clone();
5826         let route_len = bogus_route.paths[0].len();
5827         bogus_route.paths[0][route_len-1].fee_msat = amt_to_forward;
5828         run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5829
5830         //TODO: with new config API, we will be able to generate both valid and
5831         //invalid channel_update cases.
5832         run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
5833                 msg.amount_msat -= 1;
5834         }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5835
5836         run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
5837                 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
5838                 msg.cltv_expiry -= 1;
5839         }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
5840
5841         run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
5842                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5843                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5844
5845                 nodes[1].block_notifier.block_connected_checked(&header, height, &[], &[]);
5846         }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5847
5848         run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
5849                 nodes[2].node.fail_htlc_backwards(&payment_hash, &None);
5850         }, false, Some(PERM|15), None);
5851
5852         run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
5853                 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - LATENCY_GRACE_PERIOD_BLOCKS + 1;
5854                 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
5855
5856                 nodes[2].block_notifier.block_connected_checked(&header, height, &[], &[]);
5857         }, || {}, true, Some(17), None);
5858
5859         run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
5860                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5861                         for f in pending_forwards.iter_mut() {
5862                                 match f {
5863                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5864                                                 forward_info.outgoing_cltv_value += 1,
5865                                         _ => {},
5866                                 }
5867                         }
5868                 }
5869         }, true, Some(18), None);
5870
5871         run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
5872                 // violate amt_to_forward > msg.amount_msat
5873                 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().forward_htlcs.iter_mut() {
5874                         for f in pending_forwards.iter_mut() {
5875                                 match f {
5876                                         &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
5877                                                 forward_info.amt_to_forward -= 1,
5878                                         _ => {},
5879                                 }
5880                         }
5881                 }
5882         }, true, Some(19), None);
5883
5884         run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
5885                 // disconnect event to the channel between nodes[1] ~ nodes[2]
5886                 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
5887                 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5888         }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
5889         reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
5890
5891         run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
5892                 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
5893                 let mut route = route.clone();
5894                 let height = 1;
5895                 route.paths[0][1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.paths[0][0].cltv_expiry_delta + 1;
5896                 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route.paths[0], &session_priv).unwrap();
5897                 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 40000, &None, height).unwrap();
5898                 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &payment_hash);
5899                 msg.cltv_expiry = htlc_cltv;
5900                 msg.onion_routing_packet = onion_packet;
5901         }, ||{}, true, Some(21), None);
5902 }
5903
5904 #[test]
5905 #[should_panic]
5906 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
5907         let chanmon_cfgs = create_chanmon_cfgs(2);
5908         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5909         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5910         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5911         //Force duplicate channel ids
5912         for node in nodes.iter() {
5913                 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
5914         }
5915
5916         // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
5917         let channel_value_satoshis=10000;
5918         let push_msat=10001;
5919         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).unwrap();
5920         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5921         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &node0_to_1_send_open_channel);
5922
5923         //Create a second channel with a channel_id collision
5924         assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5925 }
5926
5927 #[test]
5928 fn bolt2_open_channel_sending_node_checks_part2() {
5929         let chanmon_cfgs = create_chanmon_cfgs(2);
5930         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5931         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5932         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5933
5934         // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
5935         let channel_value_satoshis=2^24;
5936         let push_msat=10001;
5937         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5938
5939         // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
5940         let channel_value_satoshis=10000;
5941         // Test when push_msat is equal to 1000 * funding_satoshis.
5942         let push_msat=1000*channel_value_satoshis+1;
5943         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_err());
5944
5945         // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
5946         let channel_value_satoshis=10000;
5947         let push_msat=10001;
5948         assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42, None).is_ok()); //Create a valid channel
5949         let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
5950         assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
5951
5952         // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
5953         // 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
5954         assert!(node0_to_1_send_open_channel.channel_flags<=1);
5955
5956         // 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.
5957         assert!(BREAKDOWN_TIMEOUT>0);
5958         assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
5959
5960         // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
5961         let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
5962         assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
5963
5964         // 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.
5965         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
5966         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
5967         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
5968         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_point.serialize()).is_ok());
5969         assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
5970 }
5971
5972 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
5973 // 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.
5974 //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.
5975
5976 #[test]
5977 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
5978         //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
5979         let chanmon_cfgs = create_chanmon_cfgs(2);
5980         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
5981         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
5982         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
5983         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
5984
5985         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5986         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
5987         let logger = test_utils::TestLogger::new();
5988         let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
5989         route.paths[0][0].fee_msat = 100;
5990
5991         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
5992                 assert_eq!(err, "Cannot send less than their minimum HTLC value"));
5993         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
5994         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send less than their minimum HTLC value".to_string(), 1);
5995 }
5996
5997 #[test]
5998 fn test_update_add_htlc_bolt2_sender_zero_value_msat() {
5999         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6000         let chanmon_cfgs = create_chanmon_cfgs(2);
6001         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6002         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6003         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6004         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6005         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6006
6007         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6008         let logger = test_utils::TestLogger::new();
6009         let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6010         route.paths[0][0].fee_msat = 0;
6011         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6012                 assert_eq!(err, "Cannot send 0-msat HTLC"));
6013
6014         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6015         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send 0-msat HTLC".to_string(), 1);
6016 }
6017
6018 #[test]
6019 fn test_update_add_htlc_bolt2_receiver_zero_value_msat() {
6020         //BOLT2 Requirement: MUST offer amount_msat greater than 0.
6021         let chanmon_cfgs = create_chanmon_cfgs(2);
6022         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6023         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6024         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6025         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6026
6027         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6028         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6029         let logger = test_utils::TestLogger::new();
6030         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6031         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6032         check_added_monitors!(nodes[0], 1);
6033         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6034         updates.update_add_htlcs[0].amount_msat = 0;
6035
6036         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6037         nodes[1].logger.assert_log("lightning::ln::channelmanager".to_string(), "Remote side tried to send a 0-msat HTLC".to_string(), 1);
6038         check_closed_broadcast!(nodes[1], true).unwrap();
6039         check_added_monitors!(nodes[1], 1);
6040 }
6041
6042 #[test]
6043 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
6044         //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
6045         //It is enforced when constructing a route.
6046         let chanmon_cfgs = create_chanmon_cfgs(2);
6047         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6048         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6049         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6050         let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0, InitFeatures::known(), InitFeatures::known());
6051         let logger = test_utils::TestLogger::new();
6052
6053         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6054
6055         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6056         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001, &logger).unwrap();
6057         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::RouteError { err },
6058                 assert_eq!(err, "Channel CLTV overflowed?!"));
6059 }
6060
6061 #[test]
6062 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
6063         //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.
6064         //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
6065         //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
6066         let chanmon_cfgs = create_chanmon_cfgs(2);
6067         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6068         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6069         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6070         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0, InitFeatures::known(), InitFeatures::known());
6071         let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
6072
6073         let logger = test_utils::TestLogger::new();
6074         for i in 0..max_accepted_htlcs {
6075                 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6076                 let payment_event = {
6077                         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6078                         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6079                         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6080                         check_added_monitors!(nodes[0], 1);
6081
6082                         let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6083                         assert_eq!(events.len(), 1);
6084                         if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
6085                                 assert_eq!(htlcs[0].htlc_id, i);
6086                         } else {
6087                                 assert!(false);
6088                         }
6089                         SendEvent::from_event(events.remove(0))
6090                 };
6091                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6092                 check_added_monitors!(nodes[1], 0);
6093                 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6094
6095                 expect_pending_htlcs_forwardable!(nodes[1]);
6096                 expect_payment_received!(nodes[1], our_payment_hash, 100000);
6097         }
6098         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6099         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6100         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
6101         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6102                 assert_eq!(err, "Cannot push more than their max accepted HTLCs"));
6103
6104         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6105         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot push more than their max accepted HTLCs".to_string(), 1);
6106 }
6107
6108 #[test]
6109 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
6110         //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.
6111         let chanmon_cfgs = create_chanmon_cfgs(2);
6112         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6113         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6114         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6115         let channel_value = 100000;
6116         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0, InitFeatures::known(), InitFeatures::known());
6117         let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
6118
6119         send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight, max_in_flight);
6120
6121         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6122         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6123         let logger = test_utils::TestLogger::new();
6124         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV, &logger).unwrap();
6125         unwrap_send_err!(nodes[0].node.send_payment(&route, our_payment_hash, &None), true, APIError::ChannelUnavailable { err },
6126                 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight our peer will accept"));
6127
6128         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
6129         nodes[0].logger.assert_log("lightning::ln::channelmanager".to_string(), "Cannot send value that would put us over the max HTLC value in flight our peer will accept".to_string(), 1);
6130
6131         send_payment(&nodes[0], &[&nodes[1]], max_in_flight, max_in_flight);
6132 }
6133
6134 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
6135 #[test]
6136 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
6137         //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
6138         let chanmon_cfgs = create_chanmon_cfgs(2);
6139         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6140         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6141         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6142         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6143         let htlc_minimum_msat: u64;
6144         {
6145                 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
6146                 let channel = chan_lock.by_id.get(&chan.2).unwrap();
6147                 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
6148         }
6149
6150         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6151         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6152         let logger = test_utils::TestLogger::new();
6153         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV, &logger).unwrap();
6154         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6155         check_added_monitors!(nodes[0], 1);
6156         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6157         updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
6158         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6159         assert!(nodes[1].node.list_channels().is_empty());
6160         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6161         assert_eq!(err_msg.data, "Remote side tried to send less than our minimum HTLC value");
6162         check_added_monitors!(nodes[1], 1);
6163 }
6164
6165 #[test]
6166 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
6167         //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
6168         let chanmon_cfgs = create_chanmon_cfgs(2);
6169         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6170         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6171         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6172         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6173
6174         let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
6175
6176         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6177         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6178         let logger = test_utils::TestLogger::new();
6179         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV, &logger).unwrap();
6180         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6181         check_added_monitors!(nodes[0], 1);
6182         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6183
6184         updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
6185         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6186
6187         assert!(nodes[1].node.list_channels().is_empty());
6188         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6189         assert_eq!(err_msg.data, "Remote HTLC add would put them under their reserve value");
6190         check_added_monitors!(nodes[1], 1);
6191 }
6192
6193 #[test]
6194 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
6195         //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
6196         //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
6197         let chanmon_cfgs = create_chanmon_cfgs(2);
6198         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6199         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6200         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6201         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6202         let logger = test_utils::TestLogger::new();
6203
6204         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6205
6206         let session_priv = SecretKey::from_slice(&{
6207                 let mut session_key = [0; 32];
6208                 let mut rng = thread_rng();
6209                 rng.fill_bytes(&mut session_key);
6210                 session_key
6211         }).expect("RNG is bad!");
6212
6213         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6214         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV, &logger).unwrap();
6215
6216         let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
6217         let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route.paths[0], &session_priv).unwrap();
6218         let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route.paths[0], 3999999, &None, cur_height).unwrap();
6219         let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, [0; 32], &our_payment_hash);
6220
6221         let mut msg = msgs::UpdateAddHTLC {
6222                 channel_id: chan.2,
6223                 htlc_id: 0,
6224                 amount_msat: 1000,
6225                 payment_hash: our_payment_hash,
6226                 cltv_expiry: htlc_cltv,
6227                 onion_routing_packet: onion_packet.clone(),
6228         };
6229
6230         for i in 0..super::channel::OUR_MAX_HTLCS {
6231                 msg.htlc_id = i as u64;
6232                 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6233         }
6234         msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
6235         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
6236
6237         assert!(nodes[1].node.list_channels().is_empty());
6238         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6239         assert_eq!(err_msg.data, "Remote tried to push more than our max accepted HTLCs");
6240         check_added_monitors!(nodes[1], 1);
6241 }
6242
6243 #[test]
6244 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
6245         //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
6246         let chanmon_cfgs = create_chanmon_cfgs(2);
6247         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6248         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6249         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6250         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6251         let logger = test_utils::TestLogger::new();
6252
6253         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6254         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6255         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6256         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6257         check_added_monitors!(nodes[0], 1);
6258         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6259         updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
6260         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6261
6262         assert!(nodes[1].node.list_channels().is_empty());
6263         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6264         assert_eq!(err_msg.data,"Remote HTLC add would put them over our max HTLC value");
6265         check_added_monitors!(nodes[1], 1);
6266 }
6267
6268 #[test]
6269 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
6270         //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
6271         let chanmon_cfgs = create_chanmon_cfgs(2);
6272         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6273         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6274         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6275         let logger = test_utils::TestLogger::new();
6276
6277         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000, InitFeatures::known(), InitFeatures::known());
6278         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6279         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6280         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6281         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6282         check_added_monitors!(nodes[0], 1);
6283         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6284         updates.update_add_htlcs[0].cltv_expiry = 500000000;
6285         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6286
6287         assert!(nodes[1].node.list_channels().is_empty());
6288         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6289         assert_eq!(err_msg.data,"Remote provided CLTV expiry in seconds instead of block height");
6290         check_added_monitors!(nodes[1], 1);
6291 }
6292
6293 #[test]
6294 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
6295         //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
6296         // We test this by first testing that that repeated HTLCs pass commitment signature checks
6297         // after disconnect and that non-sequential htlc_ids result in a channel failure.
6298         let chanmon_cfgs = create_chanmon_cfgs(2);
6299         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6300         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6301         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6302         let logger = test_utils::TestLogger::new();
6303
6304         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6305         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6306         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6307         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6308         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6309         check_added_monitors!(nodes[0], 1);
6310         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6311         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6312
6313         //Disconnect and Reconnect
6314         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
6315         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
6316         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6317         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
6318         assert_eq!(reestablish_1.len(), 1);
6319         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
6320         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
6321         assert_eq!(reestablish_2.len(), 1);
6322         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
6323         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
6324         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
6325         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
6326
6327         //Resend HTLC
6328         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6329         assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
6330         nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed);
6331         check_added_monitors!(nodes[1], 1);
6332         let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6333
6334         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6335
6336         assert!(nodes[1].node.list_channels().is_empty());
6337         let err_msg = check_closed_broadcast!(nodes[1], true).unwrap();
6338         assert_eq!(err_msg.data, "Remote skipped HTLC ID");
6339         check_added_monitors!(nodes[1], 1);
6340 }
6341
6342 #[test]
6343 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
6344         //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.
6345
6346         let chanmon_cfgs = create_chanmon_cfgs(2);
6347         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6348         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6349         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6350         let logger = test_utils::TestLogger::new();
6351         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6352         let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6353         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6354         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6355         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6356
6357         check_added_monitors!(nodes[0], 1);
6358         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6359         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6360
6361         let update_msg = msgs::UpdateFulfillHTLC{
6362                 channel_id: chan.2,
6363                 htlc_id: 0,
6364                 payment_preimage: our_payment_preimage,
6365         };
6366
6367         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6368
6369         assert!(nodes[0].node.list_channels().is_empty());
6370         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6371         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6372         check_added_monitors!(nodes[0], 1);
6373 }
6374
6375 #[test]
6376 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
6377         //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.
6378
6379         let chanmon_cfgs = create_chanmon_cfgs(2);
6380         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6381         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6382         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6383         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6384         let logger = test_utils::TestLogger::new();
6385
6386         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6387         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6388         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6389         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6390         check_added_monitors!(nodes[0], 1);
6391         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6392         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6393
6394         let update_msg = msgs::UpdateFailHTLC{
6395                 channel_id: chan.2,
6396                 htlc_id: 0,
6397                 reason: msgs::OnionErrorPacket { data: Vec::new()},
6398         };
6399
6400         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6401
6402         assert!(nodes[0].node.list_channels().is_empty());
6403         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6404         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6405         check_added_monitors!(nodes[0], 1);
6406 }
6407
6408 #[test]
6409 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
6410         //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.
6411
6412         let chanmon_cfgs = create_chanmon_cfgs(2);
6413         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6414         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6415         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6416         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6417         let logger = test_utils::TestLogger::new();
6418
6419         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6420         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6421         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6422         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6423         check_added_monitors!(nodes[0], 1);
6424         let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6425         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6426
6427         let update_msg = msgs::UpdateFailMalformedHTLC{
6428                 channel_id: chan.2,
6429                 htlc_id: 0,
6430                 sha256_of_onion: [1; 32],
6431                 failure_code: 0x8000,
6432         };
6433
6434         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6435
6436         assert!(nodes[0].node.list_channels().is_empty());
6437         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6438         assert_eq!(err_msg.data, "Remote tried to fulfill/fail HTLC before it had been committed");
6439         check_added_monitors!(nodes[0], 1);
6440 }
6441
6442 #[test]
6443 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
6444         //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
6445
6446         let chanmon_cfgs = create_chanmon_cfgs(2);
6447         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6448         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6449         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6450         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6451
6452         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6453
6454         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6455         check_added_monitors!(nodes[1], 1);
6456
6457         let events = nodes[1].node.get_and_clear_pending_msg_events();
6458         assert_eq!(events.len(), 1);
6459         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6460                 match events[0] {
6461                         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, .. } } => {
6462                                 assert!(update_add_htlcs.is_empty());
6463                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6464                                 assert!(update_fail_htlcs.is_empty());
6465                                 assert!(update_fail_malformed_htlcs.is_empty());
6466                                 assert!(update_fee.is_none());
6467                                 update_fulfill_htlcs[0].clone()
6468                         },
6469                         _ => panic!("Unexpected event"),
6470                 }
6471         };
6472
6473         update_fulfill_msg.htlc_id = 1;
6474
6475         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6476
6477         assert!(nodes[0].node.list_channels().is_empty());
6478         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6479         assert_eq!(err_msg.data, "Remote tried to fulfill/fail an HTLC we couldn't find");
6480         check_added_monitors!(nodes[0], 1);
6481 }
6482
6483 #[test]
6484 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
6485         //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.
6486
6487         let chanmon_cfgs = create_chanmon_cfgs(2);
6488         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6489         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6490         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6491         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6492
6493         let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
6494
6495         nodes[1].node.claim_funds(our_payment_preimage, &None, 100_000);
6496         check_added_monitors!(nodes[1], 1);
6497
6498         let events = nodes[1].node.get_and_clear_pending_msg_events();
6499         assert_eq!(events.len(), 1);
6500         let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
6501                 match events[0] {
6502                         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, .. } } => {
6503                                 assert!(update_add_htlcs.is_empty());
6504                                 assert_eq!(update_fulfill_htlcs.len(), 1);
6505                                 assert!(update_fail_htlcs.is_empty());
6506                                 assert!(update_fail_malformed_htlcs.is_empty());
6507                                 assert!(update_fee.is_none());
6508                                 update_fulfill_htlcs[0].clone()
6509                         },
6510                         _ => panic!("Unexpected event"),
6511                 }
6512         };
6513
6514         update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
6515
6516         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
6517
6518         assert!(nodes[0].node.list_channels().is_empty());
6519         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6520         assert_eq!(err_msg.data, "Remote tried to fulfill HTLC with an incorrect preimage");
6521         check_added_monitors!(nodes[0], 1);
6522 }
6523
6524 #[test]
6525 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
6526         //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.
6527
6528         let chanmon_cfgs = create_chanmon_cfgs(2);
6529         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6530         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6531         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6532         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6533         let logger = test_utils::TestLogger::new();
6534
6535         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6536         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6537         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV, &logger).unwrap();
6538         nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6539         check_added_monitors!(nodes[0], 1);
6540
6541         let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
6542         updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6543
6544         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
6545         check_added_monitors!(nodes[1], 0);
6546         commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
6547
6548         let events = nodes[1].node.get_and_clear_pending_msg_events();
6549
6550         let mut update_msg: msgs::UpdateFailMalformedHTLC = {
6551                 match events[0] {
6552                         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, .. } } => {
6553                                 assert!(update_add_htlcs.is_empty());
6554                                 assert!(update_fulfill_htlcs.is_empty());
6555                                 assert!(update_fail_htlcs.is_empty());
6556                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6557                                 assert!(update_fee.is_none());
6558                                 update_fail_malformed_htlcs[0].clone()
6559                         },
6560                         _ => panic!("Unexpected event"),
6561                 }
6562         };
6563         update_msg.failure_code &= !0x8000;
6564         nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
6565
6566         assert!(nodes[0].node.list_channels().is_empty());
6567         let err_msg = check_closed_broadcast!(nodes[0], true).unwrap();
6568         assert_eq!(err_msg.data, "Got update_fail_malformed_htlc with BADONION not set");
6569         check_added_monitors!(nodes[0], 1);
6570 }
6571
6572 #[test]
6573 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
6574         //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
6575         //    * 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.
6576
6577         let chanmon_cfgs = create_chanmon_cfgs(3);
6578         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6579         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6580         let mut nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6581         create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6582         create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
6583         let logger = test_utils::TestLogger::new();
6584
6585         let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
6586
6587         //First hop
6588         let mut payment_event = {
6589                 let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
6590                 let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV, &logger).unwrap();
6591                 nodes[0].node.send_payment(&route, our_payment_hash, &None).unwrap();
6592                 check_added_monitors!(nodes[0], 1);
6593                 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
6594                 assert_eq!(events.len(), 1);
6595                 SendEvent::from_event(events.remove(0))
6596         };
6597         nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]);
6598         check_added_monitors!(nodes[1], 0);
6599         commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
6600         expect_pending_htlcs_forwardable!(nodes[1]);
6601         let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
6602         assert_eq!(events_2.len(), 1);
6603         check_added_monitors!(nodes[1], 1);
6604         payment_event = SendEvent::from_event(events_2.remove(0));
6605         assert_eq!(payment_event.msgs.len(), 1);
6606
6607         //Second Hop
6608         payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
6609         nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]);
6610         check_added_monitors!(nodes[2], 0);
6611         commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
6612
6613         let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
6614         assert_eq!(events_3.len(), 1);
6615         let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
6616                 match events_3[0] {
6617                         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 } } => {
6618                                 assert!(update_add_htlcs.is_empty());
6619                                 assert!(update_fulfill_htlcs.is_empty());
6620                                 assert!(update_fail_htlcs.is_empty());
6621                                 assert_eq!(update_fail_malformed_htlcs.len(), 1);
6622                                 assert!(update_fee.is_none());
6623                                 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
6624                         },
6625                         _ => panic!("Unexpected event"),
6626                 }
6627         };
6628
6629         nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0);
6630
6631         check_added_monitors!(nodes[1], 0);
6632         commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
6633         expect_pending_htlcs_forwardable!(nodes[1]);
6634         let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
6635         assert_eq!(events_4.len(), 1);
6636
6637         //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
6638         match events_4[0] {
6639                 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, .. } } => {
6640                         assert!(update_add_htlcs.is_empty());
6641                         assert!(update_fulfill_htlcs.is_empty());
6642                         assert_eq!(update_fail_htlcs.len(), 1);
6643                         assert!(update_fail_malformed_htlcs.is_empty());
6644                         assert!(update_fee.is_none());
6645                 },
6646                 _ => panic!("Unexpected event"),
6647         };
6648
6649         check_added_monitors!(nodes[1], 1);
6650 }
6651
6652 fn do_test_failure_delay_dust_htlc_local_commitment(announce_latest: bool) {
6653         // Dust-HTLC failure updates must be delayed until failure-trigger tx (in this case local commitment) reach ANTI_REORG_DELAY
6654         // 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
6655         // HTLC could have been removed from lastest local commitment tx but still valid until we get remote RAA
6656
6657         let chanmon_cfgs = create_chanmon_cfgs(2);
6658         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6659         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6660         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6661         let chan =create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6662
6663         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6664
6665         // We route 2 dust-HTLCs between A and B
6666         let (_, payment_hash_1) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6667         let (_, payment_hash_2) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6668         route_payment(&nodes[0], &[&nodes[1]], 1000000);
6669
6670         // Cache one local commitment tx as previous
6671         let as_prev_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6672
6673         // Fail one HTLC to prune it in the will-be-latest-local commitment tx
6674         assert!(nodes[1].node.fail_htlc_backwards(&payment_hash_2, &None));
6675         check_added_monitors!(nodes[1], 0);
6676         expect_pending_htlcs_forwardable!(nodes[1]);
6677         check_added_monitors!(nodes[1], 1);
6678
6679         let remove = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
6680         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &remove.update_fail_htlcs[0]);
6681         nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &remove.commitment_signed);
6682         check_added_monitors!(nodes[0], 1);
6683
6684         // Cache one local commitment tx as lastest
6685         let as_last_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6686
6687         let events = nodes[0].node.get_and_clear_pending_msg_events();
6688         match events[0] {
6689                 MessageSendEvent::SendRevokeAndACK { node_id, .. } => {
6690                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6691                 },
6692                 _ => panic!("Unexpected event"),
6693         }
6694         match events[1] {
6695                 MessageSendEvent::UpdateHTLCs { node_id, .. } => {
6696                         assert_eq!(node_id, nodes[1].node.get_our_node_id());
6697                 },
6698                 _ => panic!("Unexpected event"),
6699         }
6700
6701         assert_ne!(as_prev_commitment_tx, as_last_commitment_tx);
6702         // Fail the 2 dust-HTLCs, move their failure in maturation buffer (htlc_updated_waiting_threshold_conf)
6703         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6704
6705         if announce_latest {
6706                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_last_commitment_tx[0].clone()]}, 1);
6707         } else {
6708                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_prev_commitment_tx[0].clone()]}, 1);
6709         }
6710
6711         check_closed_broadcast!(nodes[0], false);
6712         check_added_monitors!(nodes[0], 1);
6713
6714         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6715         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 1, true,  header.bitcoin_hash());
6716         let events = nodes[0].node.get_and_clear_pending_events();
6717         // Only 2 PaymentFailed events should show up, over-dust HTLC has to be failed by timeout tx
6718         assert_eq!(events.len(), 2);
6719         let mut first_failed = false;
6720         for event in events {
6721                 match event {
6722                         Event::PaymentFailed { payment_hash, .. } => {
6723                                 if payment_hash == payment_hash_1 {
6724                                         assert!(!first_failed);
6725                                         first_failed = true;
6726                                 } else {
6727                                         assert_eq!(payment_hash, payment_hash_2);
6728                                 }
6729                         }
6730                         _ => panic!("Unexpected event"),
6731                 }
6732         }
6733 }
6734
6735 #[test]
6736 fn test_failure_delay_dust_htlc_local_commitment() {
6737         do_test_failure_delay_dust_htlc_local_commitment(true);
6738         do_test_failure_delay_dust_htlc_local_commitment(false);
6739 }
6740
6741 #[test]
6742 fn test_no_failure_dust_htlc_local_commitment() {
6743         // Transaction filters for failing back dust htlc based on local commitment txn infos has been
6744         // prone to error, we test here that a dummy transaction don't fail them.
6745
6746         let chanmon_cfgs = create_chanmon_cfgs(2);
6747         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6748         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
6749         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6750         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6751
6752         // Rebalance a bit
6753         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
6754
6755         let as_dust_limit = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6756         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6757
6758         // We route 2 dust-HTLCs between A and B
6759         let (preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6760         let (preimage_2, _) = route_payment(&nodes[1], &[&nodes[0]], as_dust_limit*1000);
6761
6762         // Build a dummy invalid transaction trying to spend a commitment tx
6763         let input = TxIn {
6764                 previous_output: BitcoinOutPoint { txid: chan.3.txid(), vout: 0 },
6765                 script_sig: Script::new(),
6766                 sequence: 0,
6767                 witness: Vec::new(),
6768         };
6769
6770         let outp = TxOut {
6771                 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
6772                 value: 10000,
6773         };
6774
6775         let dummy_tx = Transaction {
6776                 version: 2,
6777                 lock_time: 0,
6778                 input: vec![input],
6779                 output: vec![outp]
6780         };
6781
6782         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6783         nodes[0].chan_monitor.simple_monitor.block_connected(&header, 1, &[&dummy_tx], &[1;1]);
6784         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6785         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6786         // We broadcast a few more block to check everything is all right
6787         connect_blocks(&nodes[0].block_notifier, 20, 1, true,  header.bitcoin_hash());
6788         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6789         assert_eq!(nodes[0].node.get_and_clear_pending_msg_events().len(), 0);
6790
6791         claim_payment(&nodes[0], &vec!(&nodes[1])[..], preimage_1, bs_dust_limit*1000);
6792         claim_payment(&nodes[1], &vec!(&nodes[0])[..], preimage_2, as_dust_limit*1000);
6793 }
6794
6795 fn do_test_sweep_outbound_htlc_failure_update(revoked: bool, local: bool) {
6796         // Outbound HTLC-failure updates must be cancelled if we get a reorg before we reach ANTI_REORG_DELAY.
6797         // Broadcast of revoked remote commitment tx, trigger failure-update of dust/non-dust HTLCs
6798         // Broadcast of remote commitment tx, trigger failure-update of dust-HTLCs
6799         // Broadcast of timeout tx on remote commitment tx, trigger failure-udate of non-dust HTLCs
6800         // Broadcast of local commitment tx, trigger failure-update of dust-HTLCs
6801         // Broadcast of HTLC-timeout tx on local commitment tx, trigger failure-update of non-dust HTLCs
6802
6803         let chanmon_cfgs = create_chanmon_cfgs(3);
6804         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6805         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
6806         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6807         let chan = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
6808
6809         let bs_dust_limit = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
6810
6811         let (_payment_preimage_1, dust_hash) = route_payment(&nodes[0], &[&nodes[1]], bs_dust_limit*1000);
6812         let (_payment_preimage_2, non_dust_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6813
6814         let as_commitment_tx = get_local_commitment_txn!(nodes[0], chan.2);
6815         let bs_commitment_tx = get_local_commitment_txn!(nodes[1], chan.2);
6816
6817         // We revoked bs_commitment_tx
6818         if revoked {
6819                 let (payment_preimage_3, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
6820                 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3, 1_000_000);
6821         }
6822
6823         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6824         let mut timeout_tx = Vec::new();
6825         if local {
6826                 // We fail dust-HTLC 1 by broadcast of local commitment tx
6827                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![as_commitment_tx[0].clone()]}, 1);
6828                 check_closed_broadcast!(nodes[0], false);
6829                 check_added_monitors!(nodes[0], 1);
6830                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6831                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6832                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6833                 expect_payment_failed!(nodes[0], dust_hash, true);
6834                 assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
6835                 // We fail non-dust-HTLC 2 by broadcast of local HTLC-timeout tx on local commitment tx
6836                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6837                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6838                 nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6839                 let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6840                 connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6841                 expect_payment_failed!(nodes[0], non_dust_hash, true);
6842         } else {
6843                 // We fail dust-HTLC 1 by broadcast of remote commitment tx. If revoked, fail also non-dust HTLC
6844                 nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![bs_commitment_tx[0].clone()]}, 1);
6845                 check_closed_broadcast!(nodes[0], false);
6846                 check_added_monitors!(nodes[0], 1);
6847                 assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6848                 timeout_tx.push(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap()[0].clone());
6849                 let parent_hash  = connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 2, true, header.bitcoin_hash());
6850                 let header_2 = BlockHeader { version: 0x20000000, prev_blockhash: parent_hash, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6851                 if !revoked {
6852                         expect_payment_failed!(nodes[0], dust_hash, true);
6853                         assert_eq!(timeout_tx[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
6854                         // We fail non-dust-HTLC 2 by broadcast of local timeout tx on remote commitment tx
6855                         nodes[0].block_notifier.block_connected(&Block { header: header_2, txdata: vec![timeout_tx[0].clone()]}, 7);
6856                         assert_eq!(nodes[0].node.get_and_clear_pending_events().len(), 0);
6857                         let header_3 = BlockHeader { version: 0x20000000, prev_blockhash: header_2.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
6858                         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 8, true, header_3.bitcoin_hash());
6859                         expect_payment_failed!(nodes[0], non_dust_hash, true);
6860                 } else {
6861                         // If revoked, both dust & non-dust HTLCs should have been failed after ANTI_REORG_DELAY confs of revoked
6862                         // commitment tx
6863                         let events = nodes[0].node.get_and_clear_pending_events();
6864                         assert_eq!(events.len(), 2);
6865                         let first;
6866                         match events[0] {
6867                                 Event::PaymentFailed { payment_hash, .. } => {
6868                                         if payment_hash == dust_hash { first = true; }
6869                                         else { first = false; }
6870                                 },
6871                                 _ => panic!("Unexpected event"),
6872                         }
6873                         match events[1] {
6874                                 Event::PaymentFailed { payment_hash, .. } => {
6875                                         if first { assert_eq!(payment_hash, non_dust_hash); }
6876                                         else { assert_eq!(payment_hash, dust_hash); }
6877                                 },
6878                                 _ => panic!("Unexpected event"),
6879                         }
6880                 }
6881         }
6882 }
6883
6884 #[test]
6885 fn test_sweep_outbound_htlc_failure_update() {
6886         do_test_sweep_outbound_htlc_failure_update(false, true);
6887         do_test_sweep_outbound_htlc_failure_update(false, false);
6888         do_test_sweep_outbound_htlc_failure_update(true, false);
6889 }
6890
6891 #[test]
6892 fn test_upfront_shutdown_script() {
6893         // BOLT 2 : Option upfront shutdown script, if peer commit its closing_script at channel opening
6894         // enforce it at shutdown message
6895
6896         let mut config = UserConfig::default();
6897         config.channel_options.announced_channel = true;
6898         config.peer_channel_config_limits.force_announced_channel_preference = false;
6899         config.channel_options.commit_upfront_shutdown_pubkey = false;
6900         let user_cfgs = [None, Some(config), None];
6901         let chanmon_cfgs = create_chanmon_cfgs(3);
6902         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
6903         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &user_cfgs);
6904         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
6905
6906         // We test that in case of peer committing upfront to a script, if it changes at closing, we refuse to sign
6907         let flags = InitFeatures::known();
6908         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6909         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6910         let mut node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6911         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6912         // Test we enforce upfront_scriptpbukey if by providing a diffrent one at closing that  we disconnect peer
6913         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6914         assert_eq!(check_closed_broadcast!(nodes[2], true).unwrap().data, "Got shutdown request with a scriptpubkey which did not match their previous scriptpubkey");
6915         check_added_monitors!(nodes[2], 1);
6916
6917         // We test that in case of peer committing upfront to a script, if it doesn't change at closing, we sign
6918         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 2, 1000000, 1000000, flags.clone(), flags.clone());
6919         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6920         let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[2].node.get_our_node_id());
6921         // We test that in case of peer committing upfront to a script, if it oesn't change at closing, we sign
6922         nodes[2].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown);
6923         let events = nodes[2].node.get_and_clear_pending_msg_events();
6924         assert_eq!(events.len(), 1);
6925         match events[0] {
6926                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6927                 _ => panic!("Unexpected event"),
6928         }
6929
6930         // We test that if case of peer non-signaling we don't enforce committed script at channel opening
6931         let flags_no = InitFeatures::known().clear_upfront_shutdown_script();
6932         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags_no, flags.clone());
6933         nodes[0].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6934         let mut node_1_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
6935         node_1_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6936         nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_1_shutdown);
6937         let events = nodes[1].node.get_and_clear_pending_msg_events();
6938         assert_eq!(events.len(), 1);
6939         match events[0] {
6940                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[0].node.get_our_node_id()) }
6941                 _ => panic!("Unexpected event"),
6942         }
6943
6944         // We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6945         // channel smoothly, opt-out is from channel initiator here
6946         let chan = create_announced_chan_between_nodes_with_value(&nodes, 1, 0, 1000000, 1000000, flags.clone(), flags.clone());
6947         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6948         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6949         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6950         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6951         let events = nodes[0].node.get_and_clear_pending_msg_events();
6952         assert_eq!(events.len(), 1);
6953         match events[0] {
6954                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6955                 _ => panic!("Unexpected event"),
6956         }
6957
6958         //// We test that if user opt-out, we provide a zero-length script at channel opening and we are able to close
6959         //// channel smoothly
6960         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, flags.clone(), flags.clone());
6961         nodes[1].node.close_channel(&OutPoint::new(chan.3.txid(), 0).to_channel_id()).unwrap();
6962         let mut node_0_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
6963         node_0_shutdown.scriptpubkey = Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script().to_p2sh();
6964         nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_0_shutdown);
6965         let events = nodes[0].node.get_and_clear_pending_msg_events();
6966         assert_eq!(events.len(), 2);
6967         match events[0] {
6968                 MessageSendEvent::SendShutdown { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6969                 _ => panic!("Unexpected event"),
6970         }
6971         match events[1] {
6972                 MessageSendEvent::SendClosingSigned { node_id, .. } => { assert_eq!(node_id, nodes[1].node.get_our_node_id()) }
6973                 _ => panic!("Unexpected event"),
6974         }
6975 }
6976
6977 #[test]
6978 fn test_user_configurable_csv_delay() {
6979         // We test our channel constructors yield errors when we pass them absurd csv delay
6980
6981         let mut low_our_to_self_config = UserConfig::default();
6982         low_our_to_self_config.own_channel_config.our_to_self_delay = 6;
6983         let mut high_their_to_self_config = UserConfig::default();
6984         high_their_to_self_config.peer_channel_config_limits.their_to_self_delay = 100;
6985         let user_cfgs = [Some(high_their_to_self_config.clone()), None];
6986         let chanmon_cfgs = create_chanmon_cfgs(2);
6987         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
6988         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &user_cfgs);
6989         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
6990
6991         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_outbound()
6992         let keys_manager: Arc<KeysInterface<ChanKeySigner = EnforcingChannelKeys>> = Arc::new(test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet));
6993         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, &low_our_to_self_config) {
6994                 match error {
6995                         APIError::APIMisuseError { err } => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
6996                         _ => panic!("Unexpected event"),
6997                 }
6998         } else { assert!(false) }
6999
7000         // We test config.our_to_self > BREAKDOWN_TIMEOUT is enforced in Channel::new_from_req()
7001         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7002         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7003         open_channel.to_self_delay = 200;
7004         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &low_our_to_self_config) {
7005                 match error {
7006                         ChannelError::Close(err) => { assert_eq!(err, "Configured with an unreasonable our_to_self_delay putting user funds at risks"); },
7007                         _ => panic!("Unexpected event"),
7008                 }
7009         } else { assert!(false); }
7010
7011         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Chanel::accept_channel()
7012         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7013         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id()));
7014         let mut accept_channel = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7015         accept_channel.to_self_delay = 200;
7016         nodes[0].node.handle_accept_channel(&nodes[1].node.get_our_node_id(), InitFeatures::known(), &accept_channel);
7017         if let MessageSendEvent::HandleError { ref action, .. } = nodes[0].node.get_and_clear_pending_msg_events()[0] {
7018                 match action {
7019                         &ErrorAction::SendErrorMessage { ref msg } => {
7020                                 assert_eq!(msg.data,"They wanted our payments to be delayed by a needlessly long period");
7021                         },
7022                         _ => { assert!(false); }
7023                 }
7024         } else { assert!(false); }
7025
7026         // We test msg.to_self_delay <= config.their_to_self_delay is enforced in Channel::new_from_req()
7027         nodes[1].node.create_channel(nodes[0].node.get_our_node_id(), 1000000, 1000000, 42, None).unwrap();
7028         let mut open_channel = get_event_msg!(nodes[1], MessageSendEvent::SendOpenChannel, nodes[0].node.get_our_node_id());
7029         open_channel.to_self_delay = 200;
7030         if let Err(error) = Channel::new_from_req(&&test_utils::TestFeeEstimator { sat_per_kw: 253 }, &keys_manager, nodes[1].node.get_our_node_id(), InitFeatures::known(), &open_channel, 0, &high_their_to_self_config) {
7031                 match error {
7032                         ChannelError::Close(err) => { assert_eq!(err, "They wanted our payments to be delayed by a needlessly long period"); },
7033                         _ => panic!("Unexpected event"),
7034                 }
7035         } else { assert!(false); }
7036 }
7037
7038 #[test]
7039 fn test_data_loss_protect() {
7040         // We want to be sure that :
7041         // * we don't broadcast our Local Commitment Tx in case of fallen behind
7042         // * we close channel in case of detecting other being fallen behind
7043         // * we are able to claim our own outputs thanks to to_remote being static
7044         let keys_manager;
7045         let logger;
7046         let fee_estimator;
7047         let tx_broadcaster;
7048         let chain_monitor;
7049         let monitor;
7050         let node_state_0;
7051         let chanmon_cfgs = create_chanmon_cfgs(2);
7052         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7053         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7054         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7055
7056         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000, InitFeatures::known(), InitFeatures::known());
7057
7058         // Cache node A state before any channel update
7059         let previous_node_state = nodes[0].node.encode();
7060         let mut previous_chan_monitor_state = test_utils::TestVecWriter(Vec::new());
7061         nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut previous_chan_monitor_state).unwrap();
7062
7063         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7064         send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000, 8_000_000);
7065
7066         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7067         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7068
7069         // Restore node A from previous state
7070         logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7071         let mut chan_monitor = <(BlockHash, ChannelMonitor<EnforcingChannelKeys>)>::read(&mut ::std::io::Cursor::new(previous_chan_monitor_state.0)).unwrap().1;
7072         chain_monitor = ChainWatchInterfaceUtil::new(Network::Testnet);
7073         tx_broadcaster = test_utils::TestBroadcaster{txn_broadcasted: Mutex::new(Vec::new())};
7074         fee_estimator = test_utils::TestFeeEstimator { sat_per_kw: 253 };
7075         keys_manager = test_utils::TestKeysInterface::new(&nodes[0].node_seed, Network::Testnet);
7076         monitor = test_utils::TestChannelMonitor::new(&chain_monitor, &tx_broadcaster, &logger, &fee_estimator);
7077         node_state_0 = {
7078                 let mut channel_monitors = HashMap::new();
7079                 channel_monitors.insert(OutPoint { txid: chan.3.txid(), index: 0 }, &mut chan_monitor);
7080                 <(BlockHash, ChannelManager<EnforcingChannelKeys, &test_utils::TestChannelMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(previous_node_state), ChannelManagerReadArgs {
7081                         keys_manager: &keys_manager,
7082                         fee_estimator: &fee_estimator,
7083                         monitor: &monitor,
7084                         logger: &logger,
7085                         tx_broadcaster: &tx_broadcaster,
7086                         default_config: UserConfig::default(),
7087                         channel_monitors: &mut channel_monitors,
7088                 }).unwrap().1
7089         };
7090         nodes[0].node = &node_state_0;
7091         assert!(monitor.add_monitor(OutPoint { txid: chan.3.txid(), index: 0 }, chan_monitor).is_ok());
7092         nodes[0].chan_monitor = &monitor;
7093         nodes[0].chain_monitor = &chain_monitor;
7094
7095         nodes[0].block_notifier = BlockNotifier::new(&nodes[0].chain_monitor);
7096         nodes[0].block_notifier.register_listener(&nodes[0].chan_monitor.simple_monitor);
7097         nodes[0].block_notifier.register_listener(nodes[0].node);
7098
7099         check_added_monitors!(nodes[0], 1);
7100
7101         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7102         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7103
7104         let reestablish_0 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7105
7106         // Check we don't broadcast any transactions following learning of per_commitment_point from B
7107         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_0[0]);
7108         check_added_monitors!(nodes[0], 1);
7109
7110         {
7111                 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7112                 assert_eq!(node_txn.len(), 0);
7113         }
7114
7115         let mut reestablish_1 = Vec::with_capacity(1);
7116         for msg in nodes[0].node.get_and_clear_pending_msg_events() {
7117                 if let MessageSendEvent::SendChannelReestablish { ref node_id, ref msg } = msg {
7118                         assert_eq!(*node_id, nodes[1].node.get_our_node_id());
7119                         reestablish_1.push(msg.clone());
7120                 } else if let MessageSendEvent::BroadcastChannelUpdate { .. } = msg {
7121                 } else if let MessageSendEvent::HandleError { ref action, .. } = msg {
7122                         match action {
7123                                 &ErrorAction::SendErrorMessage { ref msg } => {
7124                                         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");
7125                                 },
7126                                 _ => panic!("Unexpected event!"),
7127                         }
7128                 } else {
7129                         panic!("Unexpected event")
7130                 }
7131         }
7132
7133         // Check we close channel detecting A is fallen-behind
7134         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7135         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Peer attempted to reestablish channel with a very old local commitment transaction");
7136         check_added_monitors!(nodes[1], 1);
7137
7138
7139         // Check A is able to claim to_remote output
7140         let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
7141         assert_eq!(node_txn.len(), 1);
7142         check_spends!(node_txn[0], chan.3);
7143         assert_eq!(node_txn[0].output.len(), 2);
7144         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
7145         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![node_txn[0].clone()]}, 0);
7146         connect_blocks(&nodes[0].block_notifier, ANTI_REORG_DELAY - 1, 0, true, header.bitcoin_hash());
7147         let spend_txn = check_spendable_outputs!(nodes[0], 1, node_cfgs[0].keys_manager, 100000);
7148         assert_eq!(spend_txn.len(), 1);
7149         check_spends!(spend_txn[0], node_txn[0]);
7150 }
7151
7152 #[test]
7153 fn test_check_htlc_underpaying() {
7154         // Send payment through A -> B but A is maliciously
7155         // sending a probe payment (i.e less than expected value0
7156         // to B, B should refuse payment.
7157
7158         let chanmon_cfgs = create_chanmon_cfgs(2);
7159         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7160         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7161         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7162
7163         // Create some initial channels
7164         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7165
7166         let (payment_preimage, payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 10_000);
7167
7168         // Node 3 is expecting payment of 100_000 but receive 10_000,
7169         // fail htlc like we didn't know the preimage.
7170         nodes[1].node.claim_funds(payment_preimage, &None, 100_000);
7171         nodes[1].node.process_pending_htlc_forwards();
7172
7173         let events = nodes[1].node.get_and_clear_pending_msg_events();
7174         assert_eq!(events.len(), 1);
7175         let (update_fail_htlc, commitment_signed) = match events[0] {
7176                 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 } } => {
7177                         assert!(update_add_htlcs.is_empty());
7178                         assert!(update_fulfill_htlcs.is_empty());
7179                         assert_eq!(update_fail_htlcs.len(), 1);
7180                         assert!(update_fail_malformed_htlcs.is_empty());
7181                         assert!(update_fee.is_none());
7182                         (update_fail_htlcs[0].clone(), commitment_signed)
7183                 },
7184                 _ => panic!("Unexpected event"),
7185         };
7186         check_added_monitors!(nodes[1], 1);
7187
7188         nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlc);
7189         commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
7190
7191         // 10_000 msat as u64, followed by a height of 99 as u32
7192         let mut expected_failure_data = byte_utils::be64_to_array(10_000).to_vec();
7193         expected_failure_data.extend_from_slice(&byte_utils::be32_to_array(99));
7194         expect_payment_failed!(nodes[0], payment_hash, true, 0x4000|15, &expected_failure_data[..]);
7195         nodes[1].node.get_and_clear_pending_events();
7196 }
7197
7198 #[test]
7199 fn test_announce_disable_channels() {
7200         // Create 2 channels between A and B. Disconnect B. Call timer_chan_freshness_every_min and check for generated
7201         // ChannelUpdate. Reconnect B, reestablish and check there is non-generated ChannelUpdate.
7202
7203         let chanmon_cfgs = create_chanmon_cfgs(2);
7204         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7205         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7206         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7207
7208         let short_id_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7209         let short_id_2 = create_announced_chan_between_nodes(&nodes, 1, 0, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7210         let short_id_3 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7211
7212         // Disconnect peers
7213         nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
7214         nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
7215
7216         nodes[0].node.timer_chan_freshness_every_min(); // dirty -> stagged
7217         nodes[0].node.timer_chan_freshness_every_min(); // staged -> fresh
7218         let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
7219         assert_eq!(msg_events.len(), 3);
7220         for e in msg_events {
7221                 match e {
7222                         MessageSendEvent::BroadcastChannelUpdate { ref msg } => {
7223                                 let short_id = msg.contents.short_channel_id;
7224                                 // Check generated channel_update match list in PendingChannelUpdate
7225                                 if short_id != short_id_1 && short_id != short_id_2 && short_id != short_id_3 {
7226                                         panic!("Generated ChannelUpdate for wrong chan!");
7227                                 }
7228                         },
7229                         _ => panic!("Unexpected event"),
7230                 }
7231         }
7232         // Reconnect peers
7233         nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7234         let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
7235         assert_eq!(reestablish_1.len(), 3);
7236         nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id(), &msgs::Init { features: InitFeatures::empty() });
7237         let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
7238         assert_eq!(reestablish_2.len(), 3);
7239
7240         // Reestablish chan_1
7241         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]);
7242         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7243         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]);
7244         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7245         // Reestablish chan_2
7246         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[1]);
7247         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7248         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[1]);
7249         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7250         // Reestablish chan_3
7251         nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[2]);
7252         handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
7253         nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[2]);
7254         handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
7255
7256         nodes[0].node.timer_chan_freshness_every_min();
7257         assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
7258 }
7259
7260 #[test]
7261 fn test_bump_penalty_txn_on_revoked_commitment() {
7262         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to be sure
7263         // we're able to claim outputs on revoked commitment transaction before timelocks expiration
7264
7265         let chanmon_cfgs = create_chanmon_cfgs(2);
7266         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7267         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7268         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7269
7270         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7271         let logger = test_utils::TestLogger::new();
7272
7273
7274         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7275         let net_graph_msg_handler = &nodes[1].net_graph_msg_handler;
7276         let route = get_route(&nodes[1].node.get_our_node_id(), net_graph_msg_handler, &nodes[0].node.get_our_node_id(), None, &Vec::new(), 3000000, 30, &logger).unwrap();
7277         send_along_route(&nodes[1], route, &vec!(&nodes[0])[..], 3000000);
7278
7279         let revoked_txn = get_local_commitment_txn!(nodes[0], chan.2);
7280         // Revoked commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7281         assert_eq!(revoked_txn[0].output.len(), 4);
7282         assert_eq!(revoked_txn[0].input.len(), 1);
7283         assert_eq!(revoked_txn[0].input[0].previous_output.txid, chan.3.txid());
7284         let revoked_txid = revoked_txn[0].txid();
7285
7286         let mut penalty_sum = 0;
7287         for outp in revoked_txn[0].output.iter() {
7288                 if outp.script_pubkey.is_v0_p2wsh() {
7289                         penalty_sum += outp.value;
7290                 }
7291         }
7292
7293         // Connect blocks to change height_timer range to see if we use right soonest_timelock
7294         let header_114 = connect_blocks(&nodes[1].block_notifier, 114, 0, false, Default::default());
7295
7296         // Actually revoke tx by claiming a HTLC
7297         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7298         let header = BlockHeader { version: 0x20000000, prev_blockhash: header_114, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7299         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_txn[0].clone()] }, 115);
7300         check_added_monitors!(nodes[1], 1);
7301
7302         // One or more justice tx should have been broadcast, check it
7303         let penalty_1;
7304         let feerate_1;
7305         {
7306                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7307                 assert_eq!(node_txn.len(), 3); // justice tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout (broadcasted from ChannelManager)
7308                 assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7309                 assert_eq!(node_txn[0].output.len(), 1);
7310                 check_spends!(node_txn[0], revoked_txn[0]);
7311                 let fee_1 = penalty_sum - node_txn[0].output[0].value;
7312                 feerate_1 = fee_1 * 1000 / node_txn[0].get_weight() as u64;
7313                 penalty_1 = node_txn[0].txid();
7314                 node_txn.clear();
7315         };
7316
7317         // After exhaustion of height timer, a new bumped justice tx should have been broadcast, check it
7318         let header = connect_blocks(&nodes[1].block_notifier, 3, 115,  true, header.bitcoin_hash());
7319         let mut penalty_2 = penalty_1;
7320         let mut feerate_2 = 0;
7321         {
7322                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7323                 assert_eq!(node_txn.len(), 1);
7324                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7325                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7326                         assert_eq!(node_txn[0].output.len(), 1);
7327                         check_spends!(node_txn[0], revoked_txn[0]);
7328                         penalty_2 = node_txn[0].txid();
7329                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7330                         assert_ne!(penalty_2, penalty_1);
7331                         let fee_2 = penalty_sum - node_txn[0].output[0].value;
7332                         feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7333                         // Verify 25% bump heuristic
7334                         assert!(feerate_2 * 100 >= feerate_1 * 125);
7335                         node_txn.clear();
7336                 }
7337         }
7338         assert_ne!(feerate_2, 0);
7339
7340         // After exhaustion of height timer for a 2nd time, a new bumped justice tx should have been broadcast, check it
7341         connect_blocks(&nodes[1].block_notifier, 3, 118, true, header);
7342         let penalty_3;
7343         let mut feerate_3 = 0;
7344         {
7345                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7346                 assert_eq!(node_txn.len(), 1);
7347                 if node_txn[0].input[0].previous_output.txid == revoked_txid {
7348                         assert_eq!(node_txn[0].input.len(), 3); // Penalty txn claims to_local, offered_htlc and received_htlc outputs
7349                         assert_eq!(node_txn[0].output.len(), 1);
7350                         check_spends!(node_txn[0], revoked_txn[0]);
7351                         penalty_3 = node_txn[0].txid();
7352                         // Verify new bumped tx is different from last claiming transaction, we don't want spurrious rebroadcast
7353                         assert_ne!(penalty_3, penalty_2);
7354                         let fee_3 = penalty_sum - node_txn[0].output[0].value;
7355                         feerate_3 = fee_3 * 1000 / node_txn[0].get_weight() as u64;
7356                         // Verify 25% bump heuristic
7357                         assert!(feerate_3 * 100 >= feerate_2 * 125);
7358                         node_txn.clear();
7359                 }
7360         }
7361         assert_ne!(feerate_3, 0);
7362
7363         nodes[1].node.get_and_clear_pending_events();
7364         nodes[1].node.get_and_clear_pending_msg_events();
7365 }
7366
7367 #[test]
7368 fn test_bump_penalty_txn_on_revoked_htlcs() {
7369         // In case of penalty txn with too low feerates for getting into mempools, RBF-bump them to sure
7370         // we're able to claim outputs on revoked HTLC transactions before timelocks expiration
7371
7372         let chanmon_cfgs = create_chanmon_cfgs(2);
7373         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7374         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7375         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7376
7377         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7378         // Lock HTLC in both directions
7379         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3_000_000).0;
7380         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7381
7382         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7383         assert_eq!(revoked_local_txn[0].input.len(), 1);
7384         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7385
7386         // Revoke local commitment tx
7387         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 3_000_000);
7388
7389         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7390         // B will generate both revoked HTLC-timeout/HTLC-preimage txn from revoked commitment tx
7391         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
7392         check_closed_broadcast!(nodes[1], false);
7393         check_added_monitors!(nodes[1], 1);
7394
7395         let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7396         assert_eq!(revoked_htlc_txn.len(), 4);
7397         if revoked_htlc_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7398                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7399                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7400                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7401                 assert_eq!(revoked_htlc_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7402                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7403         } else if revoked_htlc_txn[1].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7404                 assert_eq!(revoked_htlc_txn[1].input.len(), 1);
7405                 check_spends!(revoked_htlc_txn[1], revoked_local_txn[0]);
7406                 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
7407                 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
7408                 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0]);
7409         }
7410
7411         // Broadcast set of revoked txn on A
7412         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0, true, header.bitcoin_hash());
7413         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7414
7415         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7416         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone(), revoked_htlc_txn[1].clone()] }, 129);
7417         let first;
7418         let feerate_1;
7419         let penalty_txn;
7420         {
7421                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7422                 assert_eq!(node_txn.len(), 5); // 3 penalty txn on revoked commitment tx + A commitment tx + 1 penalty tnx on revoked HTLC txn
7423                 // Verify claim tx are spending revoked HTLC txn
7424                 assert_eq!(node_txn[4].input.len(), 2);
7425                 assert_eq!(node_txn[4].output.len(), 1);
7426                 check_spends!(node_txn[4], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7427                 first = node_txn[4].txid();
7428                 // Store both feerates for later comparison
7429                 let fee_1 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[4].output[0].value;
7430                 feerate_1 = fee_1 * 1000 / node_txn[4].get_weight() as u64;
7431                 penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7432                 node_txn.clear();
7433         }
7434
7435         // Connect three more block to see if bumped penalty are issued for HTLC txn
7436         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7437         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7438         {
7439                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7440                 assert_eq!(node_txn.len(), 2); // 2 bumped penalty txn on revoked commitment tx
7441
7442                 check_spends!(node_txn[0], revoked_local_txn[0]);
7443                 check_spends!(node_txn[1], revoked_local_txn[0]);
7444
7445                 node_txn.clear();
7446         };
7447
7448         // Few more blocks to confirm penalty txn
7449         let header_135 = connect_blocks(&nodes[0].block_notifier, 5, 130, true, header_130.bitcoin_hash());
7450         assert!(nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().is_empty());
7451         let header_144 = connect_blocks(&nodes[0].block_notifier, 9, 135, true, header_135);
7452         let node_txn = {
7453                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7454                 assert_eq!(node_txn.len(), 1);
7455
7456                 assert_eq!(node_txn[0].input.len(), 2);
7457                 check_spends!(node_txn[0], revoked_htlc_txn[0], revoked_htlc_txn[1]);
7458                 // Verify bumped tx is different and 25% bump heuristic
7459                 assert_ne!(first, node_txn[0].txid());
7460                 let fee_2 = revoked_htlc_txn[0].output[0].value + revoked_htlc_txn[1].output[0].value - node_txn[0].output[0].value;
7461                 let feerate_2 = fee_2 * 1000 / node_txn[0].get_weight() as u64;
7462                 assert!(feerate_2 * 100 > feerate_1 * 125);
7463                 let txn = vec![node_txn[0].clone()];
7464                 node_txn.clear();
7465                 txn
7466         };
7467         // Broadcast claim txn and confirm blocks to avoid further bumps on this outputs
7468         let header_145 = BlockHeader { version: 0x20000000, prev_blockhash: header_144, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7469         nodes[0].block_notifier.block_connected(&Block { header: header_145, txdata: node_txn }, 145);
7470         connect_blocks(&nodes[0].block_notifier, 20, 145, true, header_145.bitcoin_hash());
7471         {
7472                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7473                 // We verify than no new transaction has been broadcast because previously
7474                 // we were buggy on this exact behavior by not tracking for monitoring remote HTLC outputs (see #411)
7475                 // which means we wouldn't see a spend of them by a justice tx and bumped justice tx
7476                 // were generated forever instead of safe cleaning after confirmation and ANTI_REORG_SAFE_DELAY blocks.
7477                 // Enforce spending of revoked htlc output by claiming transaction remove request as expected and dry
7478                 // up bumped justice generation.
7479                 assert_eq!(node_txn.len(), 0);
7480                 node_txn.clear();
7481         }
7482         check_closed_broadcast!(nodes[0], false);
7483         check_added_monitors!(nodes[0], 1);
7484 }
7485
7486 #[test]
7487 fn test_bump_penalty_txn_on_remote_commitment() {
7488         // In case of claim txn with too low feerates for getting into mempools, RBF-bump them to be sure
7489         // we're able to claim outputs on remote commitment transaction before timelocks expiration
7490
7491         // Create 2 HTLCs
7492         // Provide preimage for one
7493         // Check aggregation
7494
7495         let chanmon_cfgs = create_chanmon_cfgs(2);
7496         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7497         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7498         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7499
7500         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7501         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
7502         route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000).0;
7503
7504         // Remote commitment txn with 4 outputs : to_local, to_remote, 1 outgoing HTLC, 1 incoming HTLC
7505         let remote_txn = get_local_commitment_txn!(nodes[0], chan.2);
7506         assert_eq!(remote_txn[0].output.len(), 4);
7507         assert_eq!(remote_txn[0].input.len(), 1);
7508         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7509
7510         // Claim a HTLC without revocation (provide B monitor with preimage)
7511         nodes[1].node.claim_funds(payment_preimage, &None, 3_000_000);
7512         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7513         nodes[1].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 1);
7514         check_added_monitors!(nodes[1], 2);
7515
7516         // One or more claim tx should have been broadcast, check it
7517         let timeout;
7518         let preimage;
7519         let feerate_timeout;
7520         let feerate_preimage;
7521         {
7522                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7523                 assert_eq!(node_txn.len(), 5); // 2 * claim tx (broadcasted from ChannelMonitor) + local commitment tx + local HTLC-timeout + local HTLC-success (broadcasted from ChannelManager)
7524                 assert_eq!(node_txn[0].input.len(), 1);
7525                 assert_eq!(node_txn[1].input.len(), 1);
7526                 check_spends!(node_txn[0], remote_txn[0]);
7527                 check_spends!(node_txn[1], remote_txn[0]);
7528                 check_spends!(node_txn[2], chan.3);
7529                 check_spends!(node_txn[3], node_txn[2]);
7530                 check_spends!(node_txn[4], node_txn[2]);
7531                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7532                         timeout = node_txn[0].txid();
7533                         let index = node_txn[0].input[0].previous_output.vout;
7534                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7535                         feerate_timeout = fee * 1000 / node_txn[0].get_weight() as u64;
7536
7537                         preimage = node_txn[1].txid();
7538                         let index = node_txn[1].input[0].previous_output.vout;
7539                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7540                         feerate_preimage = fee * 1000 / node_txn[1].get_weight() as u64;
7541                 } else {
7542                         timeout = node_txn[1].txid();
7543                         let index = node_txn[1].input[0].previous_output.vout;
7544                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7545                         feerate_timeout = fee * 1000 / node_txn[1].get_weight() as u64;
7546
7547                         preimage = node_txn[0].txid();
7548                         let index = node_txn[0].input[0].previous_output.vout;
7549                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7550                         feerate_preimage = fee * 1000 / node_txn[0].get_weight() as u64;
7551                 }
7552                 node_txn.clear();
7553         };
7554         assert_ne!(feerate_timeout, 0);
7555         assert_ne!(feerate_preimage, 0);
7556
7557         // After exhaustion of height timer, new bumped claim txn should have been broadcast, check it
7558         connect_blocks(&nodes[1].block_notifier, 15, 1,  true, header.bitcoin_hash());
7559         {
7560                 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7561                 assert_eq!(node_txn.len(), 2);
7562                 assert_eq!(node_txn[0].input.len(), 1);
7563                 assert_eq!(node_txn[1].input.len(), 1);
7564                 check_spends!(node_txn[0], remote_txn[0]);
7565                 check_spends!(node_txn[1], remote_txn[0]);
7566                 if node_txn[0].input[0].witness.last().unwrap().len() == ACCEPTED_HTLC_SCRIPT_WEIGHT {
7567                         let index = node_txn[0].input[0].previous_output.vout;
7568                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7569                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7570                         assert!(new_feerate * 100 > feerate_timeout * 125);
7571                         assert_ne!(timeout, node_txn[0].txid());
7572
7573                         let index = node_txn[1].input[0].previous_output.vout;
7574                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7575                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7576                         assert!(new_feerate * 100 > feerate_preimage * 125);
7577                         assert_ne!(preimage, node_txn[1].txid());
7578                 } else {
7579                         let index = node_txn[1].input[0].previous_output.vout;
7580                         let fee = remote_txn[0].output[index as usize].value - node_txn[1].output[0].value;
7581                         let new_feerate = fee * 1000 / node_txn[1].get_weight() as u64;
7582                         assert!(new_feerate * 100 > feerate_timeout * 125);
7583                         assert_ne!(timeout, node_txn[1].txid());
7584
7585                         let index = node_txn[0].input[0].previous_output.vout;
7586                         let fee = remote_txn[0].output[index as usize].value - node_txn[0].output[0].value;
7587                         let new_feerate = fee * 1000 / node_txn[0].get_weight() as u64;
7588                         assert!(new_feerate * 100 > feerate_preimage * 125);
7589                         assert_ne!(preimage, node_txn[0].txid());
7590                 }
7591                 node_txn.clear();
7592         }
7593
7594         nodes[1].node.get_and_clear_pending_events();
7595         nodes[1].node.get_and_clear_pending_msg_events();
7596 }
7597
7598 #[test]
7599 fn test_set_outpoints_partial_claiming() {
7600         // - remote party claim tx, new bump tx
7601         // - disconnect remote claiming tx, new bump
7602         // - disconnect tx, see no tx anymore
7603         let chanmon_cfgs = create_chanmon_cfgs(2);
7604         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7605         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7606         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7607
7608         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7609         let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7610         let payment_preimage_2 = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3_000_000).0;
7611
7612         // Remote commitment txn with 4 outputs: to_local, to_remote, 2 outgoing HTLC
7613         let remote_txn = get_local_commitment_txn!(nodes[1], chan.2);
7614         assert_eq!(remote_txn.len(), 3);
7615         assert_eq!(remote_txn[0].output.len(), 4);
7616         assert_eq!(remote_txn[0].input.len(), 1);
7617         assert_eq!(remote_txn[0].input[0].previous_output.txid, chan.3.txid());
7618         check_spends!(remote_txn[1], remote_txn[0]);
7619         check_spends!(remote_txn[2], remote_txn[0]);
7620
7621         // Connect blocks on node A to advance height towards TEST_FINAL_CLTV
7622         let prev_header_100 = connect_blocks(&nodes[1].block_notifier, 100, 0, false, Default::default());
7623         // Provide node A with both preimage
7624         nodes[0].node.claim_funds(payment_preimage_1, &None, 3_000_000);
7625         nodes[0].node.claim_funds(payment_preimage_2, &None, 3_000_000);
7626         check_added_monitors!(nodes[0], 2);
7627         nodes[0].node.get_and_clear_pending_events();
7628         nodes[0].node.get_and_clear_pending_msg_events();
7629
7630         // Connect blocks on node A commitment transaction
7631         let header = BlockHeader { version: 0x20000000, prev_blockhash: prev_header_100, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7632         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![remote_txn[0].clone()] }, 101);
7633         check_closed_broadcast!(nodes[0], false);
7634         check_added_monitors!(nodes[0], 1);
7635         // Verify node A broadcast tx claiming both HTLCs
7636         {
7637                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7638                 // ChannelMonitor: claim tx, ChannelManager: local commitment tx + HTLC-Success*2
7639                 assert_eq!(node_txn.len(), 4);
7640                 check_spends!(node_txn[0], remote_txn[0]);
7641                 check_spends!(node_txn[1], chan.3);
7642                 check_spends!(node_txn[2], node_txn[1]);
7643                 check_spends!(node_txn[3], node_txn[1]);
7644                 assert_eq!(node_txn[0].input.len(), 2);
7645                 node_txn.clear();
7646         }
7647
7648         // Connect blocks on node B
7649         connect_blocks(&nodes[1].block_notifier, 135, 0, false, Default::default());
7650         check_closed_broadcast!(nodes[1], false);
7651         check_added_monitors!(nodes[1], 1);
7652         // Verify node B broadcast 2 HTLC-timeout txn
7653         let partial_claim_tx = {
7654                 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
7655                 assert_eq!(node_txn.len(), 3);
7656                 check_spends!(node_txn[1], node_txn[0]);
7657                 check_spends!(node_txn[2], node_txn[0]);
7658                 assert_eq!(node_txn[1].input.len(), 1);
7659                 assert_eq!(node_txn[2].input.len(), 1);
7660                 node_txn[1].clone()
7661         };
7662
7663         // Broadcast partial claim on node A, should regenerate a claiming tx with HTLC dropped
7664         let header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7665         nodes[0].block_notifier.block_connected(&Block { header, txdata: vec![partial_claim_tx.clone()] }, 102);
7666         {
7667                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7668                 assert_eq!(node_txn.len(), 1);
7669                 check_spends!(node_txn[0], remote_txn[0]);
7670                 assert_eq!(node_txn[0].input.len(), 1); //dropped HTLC
7671                 node_txn.clear();
7672         }
7673         nodes[0].node.get_and_clear_pending_msg_events();
7674
7675         // Disconnect last block on node A, should regenerate a claiming tx with HTLC dropped
7676         nodes[0].block_notifier.block_disconnected(&header, 102);
7677         {
7678                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7679                 assert_eq!(node_txn.len(), 1);
7680                 check_spends!(node_txn[0], remote_txn[0]);
7681                 assert_eq!(node_txn[0].input.len(), 2); //resurrected HTLC
7682                 node_txn.clear();
7683         }
7684
7685         //// Disconnect one more block and then reconnect multiple no transaction should be generated
7686         nodes[0].block_notifier.block_disconnected(&header, 101);
7687         connect_blocks(&nodes[1].block_notifier, 15, 101, false, prev_header_100);
7688         {
7689                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7690                 assert_eq!(node_txn.len(), 0);
7691                 node_txn.clear();
7692         }
7693 }
7694
7695 #[test]
7696 fn test_counterparty_raa_skip_no_crash() {
7697         // Previously, if our counterparty sent two RAAs in a row without us having provided a
7698         // commitment transaction, we would have happily carried on and provided them the next
7699         // commitment transaction based on one RAA forward. This would probably eventually have led to
7700         // channel closure, but it would not have resulted in funds loss. Still, our
7701         // EnforcingChannelKeys would have paniced as it doesn't like jumps into the future. Here, we
7702         // check simply that the channel is closed in response to such an RAA, but don't check whether
7703         // we decide to punish our counterparty for revoking their funds (as we don't currently
7704         // implement that).
7705         let chanmon_cfgs = create_chanmon_cfgs(2);
7706         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7707         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7708         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7709         let channel_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).2;
7710
7711         let commitment_seed = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&channel_id).unwrap().local_keys.commitment_seed().clone();
7712         const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
7713         let next_per_commitment_point = PublicKey::from_secret_key(&Secp256k1::new(),
7714                 &SecretKey::from_slice(&chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER - 2)).unwrap());
7715         let per_commitment_secret = chan_utils::build_commitment_secret(&commitment_seed, INITIAL_COMMITMENT_NUMBER);
7716
7717         nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(),
7718                 &msgs::RevokeAndACK { channel_id, per_commitment_secret, next_per_commitment_point });
7719         assert_eq!(check_closed_broadcast!(nodes[1], true).unwrap().data, "Received an unexpected revoke_and_ack");
7720         check_added_monitors!(nodes[1], 1);
7721 }
7722
7723 #[test]
7724 fn test_bump_txn_sanitize_tracking_maps() {
7725         // Sanitizing pendning_claim_request and claimable_outpoints used to be buggy,
7726         // verify we clean then right after expiration of ANTI_REORG_DELAY.
7727
7728         let chanmon_cfgs = create_chanmon_cfgs(2);
7729         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7730         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7731         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7732
7733         let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 59000000, InitFeatures::known(), InitFeatures::known());
7734         // Lock HTLC in both directions
7735         let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7736         route_payment(&nodes[1], &vec!(&nodes[0])[..], 9_000_000).0;
7737
7738         let revoked_local_txn = get_local_commitment_txn!(nodes[1], chan.2);
7739         assert_eq!(revoked_local_txn[0].input.len(), 1);
7740         assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
7741
7742         // Revoke local commitment tx
7743         claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage, 9_000_000);
7744
7745         // Broadcast set of revoked txn on A
7746         let header_128 = connect_blocks(&nodes[0].block_notifier, 128, 0,  false, Default::default());
7747         expect_pending_htlcs_forwardable_ignore!(nodes[0]);
7748
7749         let header_129 = BlockHeader { version: 0x20000000, prev_blockhash: header_128, merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7750         nodes[0].block_notifier.block_connected(&Block { header: header_129, txdata: vec![revoked_local_txn[0].clone()] }, 129);
7751         check_closed_broadcast!(nodes[0], false);
7752         check_added_monitors!(nodes[0], 1);
7753         let penalty_txn = {
7754                 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
7755                 assert_eq!(node_txn.len(), 4); //ChannelMonitor: justice txn * 3, ChannelManager: local commitment tx
7756                 check_spends!(node_txn[0], revoked_local_txn[0]);
7757                 check_spends!(node_txn[1], revoked_local_txn[0]);
7758                 check_spends!(node_txn[2], revoked_local_txn[0]);
7759                 let penalty_txn = vec![node_txn[0].clone(), node_txn[1].clone(), node_txn[2].clone()];
7760                 node_txn.clear();
7761                 penalty_txn
7762         };
7763         let header_130 = BlockHeader { version: 0x20000000, prev_blockhash: header_129.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7764         nodes[0].block_notifier.block_connected(&Block { header: header_130, txdata: penalty_txn }, 130);
7765         connect_blocks(&nodes[0].block_notifier, 5, 130,  false, header_130.bitcoin_hash());
7766         {
7767                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7768                 if let Some(monitor) = monitors.get(&OutPoint::new(chan.3.txid(), 0)) {
7769                         assert!(monitor.onchain_tx_handler.pending_claim_requests.is_empty());
7770                         assert!(monitor.onchain_tx_handler.claimable_outpoints.is_empty());
7771                 }
7772         }
7773 }
7774
7775 #[test]
7776 fn test_override_channel_config() {
7777         let chanmon_cfgs = create_chanmon_cfgs(2);
7778         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7779         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7780         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7781
7782         // Node0 initiates a channel to node1 using the override config.
7783         let mut override_config = UserConfig::default();
7784         override_config.own_channel_config.our_to_self_delay = 200;
7785
7786         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(override_config)).unwrap();
7787
7788         // Assert the channel created by node0 is using the override config.
7789         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7790         assert_eq!(res.channel_flags, 0);
7791         assert_eq!(res.to_self_delay, 200);
7792 }
7793
7794 #[test]
7795 fn test_override_0msat_htlc_minimum() {
7796         let mut zero_config = UserConfig::default();
7797         zero_config.own_channel_config.our_htlc_minimum_msat = 0;
7798         let chanmon_cfgs = create_chanmon_cfgs(2);
7799         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7800         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, Some(zero_config.clone())]);
7801         let nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7802
7803         nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), 16_000_000, 12_000_000, 42, Some(zero_config)).unwrap();
7804         let res = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
7805         assert_eq!(res.htlc_minimum_msat, 1);
7806
7807         nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), InitFeatures::known(), &res);
7808         let res = get_event_msg!(nodes[1], MessageSendEvent::SendAcceptChannel, nodes[0].node.get_our_node_id());
7809         assert_eq!(res.htlc_minimum_msat, 1);
7810 }
7811
7812 #[test]
7813 fn test_simple_payment_secret() {
7814         // Simple test of sending a payment with a payment_secret present. This does not use any AMP
7815         // features, however.
7816         let chanmon_cfgs = create_chanmon_cfgs(3);
7817         let node_cfgs = create_node_cfgs(3, &chanmon_cfgs);
7818         let node_chanmgrs = create_node_chanmgrs(3, &node_cfgs, &[None, None, None]);
7819         let nodes = create_network(3, &node_cfgs, &node_chanmgrs);
7820
7821         create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7822         create_announced_chan_between_nodes(&nodes, 1, 2, InitFeatures::known(), InitFeatures::known());
7823         let logger = test_utils::TestLogger::new();
7824
7825         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7826         let payment_secret = PaymentSecret([0xdb; 32]);
7827         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7828         let route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
7829         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[2]]], 100000, payment_hash, Some(payment_secret.clone()));
7830         // Claiming with all the correct values but the wrong secret should result in nothing...
7831         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &None, 100_000), false);
7832         assert_eq!(nodes[2].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 100_000), false);
7833         // ...but with the right secret we should be able to claim all the way back
7834         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[2]]], false, payment_preimage, Some(payment_secret.clone()), 100_000);
7835 }
7836
7837 #[test]
7838 fn test_simple_mpp() {
7839         // Simple test of sending a multi-path payment.
7840         let chanmon_cfgs = create_chanmon_cfgs(4);
7841         let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
7842         let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
7843         let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
7844
7845         let chan_1_id = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7846         let chan_2_id = create_announced_chan_between_nodes(&nodes, 0, 2, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7847         let chan_3_id = create_announced_chan_between_nodes(&nodes, 1, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7848         let chan_4_id = create_announced_chan_between_nodes(&nodes, 2, 3, InitFeatures::known(), InitFeatures::known()).0.contents.short_channel_id;
7849         let logger = test_utils::TestLogger::new();
7850
7851         let (payment_preimage, payment_hash) = get_payment_preimage_hash!(&nodes[0]);
7852         let payment_secret = PaymentSecret([0xdb; 32]);
7853         let net_graph_msg_handler = &nodes[0].net_graph_msg_handler;
7854         let mut route = get_route(&nodes[0].node.get_our_node_id(), net_graph_msg_handler, &nodes[3].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV, &logger).unwrap();
7855         let path = route.paths[0].clone();
7856         route.paths.push(path);
7857         route.paths[0][0].pubkey = nodes[1].node.get_our_node_id();
7858         route.paths[0][0].short_channel_id = chan_1_id;
7859         route.paths[0][1].short_channel_id = chan_3_id;
7860         route.paths[1][0].pubkey = nodes[2].node.get_our_node_id();
7861         route.paths[1][0].short_channel_id = chan_2_id;
7862         route.paths[1][1].short_channel_id = chan_4_id;
7863         send_along_route_with_secret(&nodes[0], route, &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], 200_000, payment_hash, Some(payment_secret.clone()));
7864         // Claiming with all the correct values but the wrong secret should result in nothing...
7865         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &None, 200_000), false);
7866         assert_eq!(nodes[3].node.claim_funds(payment_preimage, &Some(PaymentSecret([42; 32])), 200_000), false);
7867         // ...but with the right secret we should be able to claim all the way back
7868         claim_payment_along_route_with_secret(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_preimage, Some(payment_secret), 200_000);
7869 }
7870
7871 #[test]
7872 fn test_update_err_monitor_lockdown() {
7873         // Our monitor will lock update of local commitment transaction if a broadcastion condition
7874         // has been fulfilled (either force-close from Channel or block height requiring a HTLC-
7875         // timeout). Trying to update monitor after lockdown should return a ChannelMonitorUpdateErr.
7876         //
7877         // This scenario may happen in a watchtower setup, where watchtower process a block height
7878         // triggering a timeout while a slow-block-processing ChannelManager receives a local signed
7879         // commitment at same time.
7880
7881         let chanmon_cfgs = create_chanmon_cfgs(2);
7882         let node_cfgs = create_node_cfgs(2, &chanmon_cfgs);
7883         let node_chanmgrs = create_node_chanmgrs(2, &node_cfgs, &[None, None]);
7884         let mut nodes = create_network(2, &node_cfgs, &node_chanmgrs);
7885
7886         // Create some initial channel
7887         let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1, InitFeatures::known(), InitFeatures::known());
7888         let outpoint = OutPoint { txid: chan_1.3.txid(), index: 0 };
7889
7890         // Rebalance the network to generate htlc in the two directions
7891         send_payment(&nodes[0], &vec!(&nodes[1])[..], 10_000_000, 10_000_000);
7892
7893         // Route a HTLC from node 0 to node 1 (but don't settle)
7894         let preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9_000_000).0;
7895
7896         // Copy SimpleManyChannelMonitor to simulate a watchtower and update block height of node 0 until its ChannelMonitor timeout HTLC onchain
7897         let logger = test_utils::TestLogger::with_id(format!("node {}", 0));
7898         let chain_monitor = chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet);
7899         let watchtower = {
7900                 let monitors = nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap();
7901                 let monitor = monitors.get(&outpoint).unwrap();
7902                 let mut w = test_utils::TestVecWriter(Vec::new());
7903                 monitor.write_for_disk(&mut w).unwrap();
7904                 let new_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingChannelKeys>)>::read(
7905                                 &mut ::std::io::Cursor::new(&w.0)).unwrap().1;
7906                 assert!(new_monitor == *monitor);
7907                 let watchtower = test_utils::TestChannelMonitor::new(&chain_monitor, &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator);
7908                 assert!(watchtower.add_monitor(outpoint, new_monitor).is_ok());
7909                 watchtower
7910         };
7911         let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
7912         watchtower.simple_monitor.block_connected(&header, 200, &vec![], &vec![]);
7913
7914         // Try to update ChannelMonitor
7915         assert!(nodes[1].node.claim_funds(preimage, &None, 9_000_000));
7916         check_added_monitors!(nodes[1], 1);
7917         let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
7918         assert_eq!(updates.update_fulfill_htlcs.len(), 1);
7919         nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]);
7920         if let Some(ref mut channel) = nodes[0].node.channel_state.lock().unwrap().by_id.get_mut(&chan_1.2) {
7921                 if let Ok((_, _, _, update)) = channel.commitment_signed(&updates.commitment_signed, &node_cfgs[0].fee_estimator, &node_cfgs[0].logger) {
7922                         if let Err(_) =  watchtower.simple_monitor.update_monitor(outpoint, update.clone()) {} else { assert!(false); }
7923                         if let Ok(_) = nodes[0].chan_monitor.update_monitor(outpoint, update) {} else { assert!(false); }
7924                 } else { assert!(false); }
7925         } else { assert!(false); };
7926         // Our local monitor is in-sync and hasn't processed yet timeout
7927         check_added_monitors!(nodes[0], 1);
7928         let events = nodes[0].node.get_and_clear_pending_events();
7929         assert_eq!(events.len(), 1);
7930 }