1 //! Tests that test standing up a network of ChannelManagers, creating channels, sending
2 //! payments/messages between them, and often checking the resulting ChannelMonitors are able to
3 //! claim outputs on-chain.
5 use chain::transaction::OutPoint;
6 use chain::chaininterface::{ChainListener, ChainWatchInterface};
7 use chain::keysinterface::{KeysInterface, SpendableOutputDescriptor};
8 use chain::keysinterface;
9 use ln::channel::{COMMITMENT_TX_BASE_WEIGHT, COMMITMENT_TX_WEIGHT_PER_HTLC, BREAKDOWN_TIMEOUT};
10 use ln::channelmanager::{ChannelManager,ChannelManagerReadArgs,HTLCForwardInfo,RAACommitmentOrder, PaymentPreimage, PaymentHash};
11 use ln::channelmonitor::{ChannelMonitor, CLTV_CLAIM_BUFFER, HTLC_FAIL_TIMEOUT_BLOCKS, ManyChannelMonitor};
12 use ln::channel::{ACCEPTED_HTLC_SCRIPT_WEIGHT, OFFERED_HTLC_SCRIPT_WEIGHT};
14 use ln::router::{Route, RouteHop};
16 use ln::msgs::{ChannelMessageHandler,RoutingMessageHandler,HTLCFailChannelUpdate};
18 use util::events::{Event, EventsProvider, MessageSendEvent, MessageSendEventsProvider};
19 use util::errors::APIError;
20 use util::ser::{Writeable, ReadableArgs};
21 use util::config::UserConfig;
24 use bitcoin::util::hash::BitcoinHash;
25 use bitcoin_hashes::sha256d::Hash as Sha256dHash;
26 use bitcoin::util::bip143;
27 use bitcoin::util::address::Address;
28 use bitcoin::util::bip32::{ChildNumber, ExtendedPubKey, ExtendedPrivKey};
29 use bitcoin::blockdata::block::{Block, BlockHeader};
30 use bitcoin::blockdata::transaction::{Transaction, TxOut, TxIn, SigHashType};
31 use bitcoin::blockdata::script::{Builder, Script};
32 use bitcoin::blockdata::opcodes;
33 use bitcoin::blockdata::constants::genesis_block;
34 use bitcoin::network::constants::Network;
36 use bitcoin_hashes::sha256::Hash as Sha256;
37 use bitcoin_hashes::Hash;
39 use secp256k1::{Secp256k1, Message};
40 use secp256k1::key::{PublicKey,SecretKey};
42 use std::collections::{BTreeSet, HashMap, HashSet};
43 use std::default::Default;
45 use std::sync::atomic::Ordering;
46 use std::time::Instant;
49 use ln::functional_test_utils::*;
52 fn test_async_inbound_update_fee() {
53 let mut nodes = create_network(2);
54 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
55 let channel_id = chan.2;
58 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
62 // send (1) commitment_signed -.
63 // <- update_add_htlc/commitment_signed
64 // send (2) RAA (awaiting remote revoke) -.
65 // (1) commitment_signed is delivered ->
66 // .- send (3) RAA (awaiting remote revoke)
67 // (2) RAA is delivered ->
68 // .- send (4) commitment_signed
69 // <- (3) RAA is delivered
70 // send (5) commitment_signed -.
71 // <- (4) commitment_signed is delivered
73 // (5) commitment_signed is delivered ->
75 // (6) RAA is delivered ->
77 // First nodes[0] generates an update_fee
78 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
79 check_added_monitors!(nodes[0], 1);
81 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
82 assert_eq!(events_0.len(), 1);
83 let (update_msg, commitment_signed) = match events_0[0] { // (1)
84 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
85 (update_fee.as_ref(), commitment_signed)
87 _ => panic!("Unexpected event"),
90 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
92 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
93 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
94 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
95 check_added_monitors!(nodes[1], 1);
98 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
99 assert_eq!(events_1.len(), 1);
100 SendEvent::from_event(events_1.remove(0))
102 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
103 assert_eq!(payment_event.msgs.len(), 1);
105 // ...now when the messages get delivered everyone should be happy
106 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
107 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
108 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
109 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
110 check_added_monitors!(nodes[0], 1);
112 // deliver(1), generate (3):
113 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
114 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
115 // nodes[1] is awaiting nodes[0] revoke_and_ack so get_event_msg's assert(len == 1) passes
116 check_added_monitors!(nodes[1], 1);
118 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap(); // deliver (2)
119 let bs_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
120 assert!(bs_update.update_add_htlcs.is_empty()); // (4)
121 assert!(bs_update.update_fulfill_htlcs.is_empty()); // (4)
122 assert!(bs_update.update_fail_htlcs.is_empty()); // (4)
123 assert!(bs_update.update_fail_malformed_htlcs.is_empty()); // (4)
124 assert!(bs_update.update_fee.is_none()); // (4)
125 check_added_monitors!(nodes[1], 1);
127 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap(); // deliver (3)
128 let as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
129 assert!(as_update.update_add_htlcs.is_empty()); // (5)
130 assert!(as_update.update_fulfill_htlcs.is_empty()); // (5)
131 assert!(as_update.update_fail_htlcs.is_empty()); // (5)
132 assert!(as_update.update_fail_malformed_htlcs.is_empty()); // (5)
133 assert!(as_update.update_fee.is_none()); // (5)
134 check_added_monitors!(nodes[0], 1);
136 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_update.commitment_signed).unwrap(); // deliver (4)
137 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
138 // only (6) so get_event_msg's assert(len == 1) passes
139 check_added_monitors!(nodes[0], 1);
141 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_update.commitment_signed).unwrap(); // deliver (5)
142 let bs_second_revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
143 check_added_monitors!(nodes[1], 1);
145 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
146 check_added_monitors!(nodes[0], 1);
148 let events_2 = nodes[0].node.get_and_clear_pending_events();
149 assert_eq!(events_2.len(), 1);
151 Event::PendingHTLCsForwardable {..} => {}, // If we actually processed we'd receive the payment
152 _ => panic!("Unexpected event"),
155 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap(); // deliver (6)
156 check_added_monitors!(nodes[1], 1);
160 fn test_update_fee_unordered_raa() {
161 // Just the intro to the previous test followed by an out-of-order RAA (which caused a
162 // crash in an earlier version of the update_fee patch)
163 let mut nodes = create_network(2);
164 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
165 let channel_id = chan.2;
168 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
170 // First nodes[0] generates an update_fee
171 nodes[0].node.update_fee(channel_id, get_feerate!(nodes[0], channel_id) + 20).unwrap();
172 check_added_monitors!(nodes[0], 1);
174 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
175 assert_eq!(events_0.len(), 1);
176 let update_msg = match events_0[0] { // (1)
177 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, .. }, .. } => {
180 _ => panic!("Unexpected event"),
183 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
185 // ...but before it's delivered, nodes[1] starts to send a payment back to nodes[0]...
186 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
187 nodes[1].node.send_payment(nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap(), our_payment_hash).unwrap();
188 check_added_monitors!(nodes[1], 1);
190 let payment_event = {
191 let mut events_1 = nodes[1].node.get_and_clear_pending_msg_events();
192 assert_eq!(events_1.len(), 1);
193 SendEvent::from_event(events_1.remove(0))
195 assert_eq!(payment_event.node_id, nodes[0].node.get_our_node_id());
196 assert_eq!(payment_event.msgs.len(), 1);
198 // ...now when the messages get delivered everyone should be happy
199 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
200 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap(); // (2)
201 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
202 // nodes[0] is awaiting nodes[1] revoke_and_ack so get_event_msg's assert(len == 1) passes
203 check_added_monitors!(nodes[0], 1);
205 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap(); // deliver (2)
206 check_added_monitors!(nodes[1], 1);
208 // We can't continue, sadly, because our (1) now has a bogus signature
212 fn test_multi_flight_update_fee() {
213 let nodes = create_network(2);
214 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
215 let channel_id = chan.2;
218 // update_fee/commitment_signed ->
219 // .- send (1) RAA and (2) commitment_signed
220 // update_fee (never committed) ->
222 // We have to manually generate the above update_fee, it is allowed by the protocol but we
223 // don't track which updates correspond to which revoke_and_ack responses so we're in
224 // AwaitingRAA mode and will not generate the update_fee yet.
225 // <- (1) RAA delivered
226 // (3) is generated and send (4) CS -.
227 // Note that A cannot generate (4) prior to (1) being delivered as it otherwise doesn't
228 // know the per_commitment_point to use for it.
229 // <- (2) commitment_signed delivered
231 // B should send no response here
232 // (4) commitment_signed delivered ->
233 // <- RAA/commitment_signed delivered
236 // First nodes[0] generates an update_fee
237 let initial_feerate = get_feerate!(nodes[0], channel_id);
238 nodes[0].node.update_fee(channel_id, initial_feerate + 20).unwrap();
239 check_added_monitors!(nodes[0], 1);
241 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
242 assert_eq!(events_0.len(), 1);
243 let (update_msg_1, commitment_signed_1) = match events_0[0] { // (1)
244 MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate { ref update_fee, ref commitment_signed, .. }, .. } => {
245 (update_fee.as_ref().unwrap(), commitment_signed)
247 _ => panic!("Unexpected event"),
250 // Deliver first update_fee/commitment_signed pair, generating (1) and (2):
251 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg_1).unwrap();
252 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed_1).unwrap();
253 let (bs_revoke_msg, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
254 check_added_monitors!(nodes[1], 1);
256 // nodes[0] is awaiting a revoke from nodes[1] before it will create a new commitment
258 nodes[0].node.update_fee(channel_id, initial_feerate + 40).unwrap();
259 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
260 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
262 // Create the (3) update_fee message that nodes[0] will generate before it does...
263 let mut update_msg_2 = msgs::UpdateFee {
264 channel_id: update_msg_1.channel_id.clone(),
265 feerate_per_kw: (initial_feerate + 30) as u32,
268 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
270 update_msg_2.feerate_per_kw = (initial_feerate + 40) as u32;
272 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg_2).unwrap();
274 // Deliver (1), generating (3) and (4)
275 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_msg).unwrap();
276 let as_second_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
277 check_added_monitors!(nodes[0], 1);
278 assert!(as_second_update.update_add_htlcs.is_empty());
279 assert!(as_second_update.update_fulfill_htlcs.is_empty());
280 assert!(as_second_update.update_fail_htlcs.is_empty());
281 assert!(as_second_update.update_fail_malformed_htlcs.is_empty());
282 // Check that the update_fee newly generated matches what we delivered:
283 assert_eq!(as_second_update.update_fee.as_ref().unwrap().channel_id, update_msg_2.channel_id);
284 assert_eq!(as_second_update.update_fee.as_ref().unwrap().feerate_per_kw, update_msg_2.feerate_per_kw);
286 // Deliver (2) commitment_signed
287 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
288 let as_revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
289 check_added_monitors!(nodes[0], 1);
290 // No commitment_signed so get_event_msg's assert(len == 1) passes
292 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_msg).unwrap();
293 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
294 check_added_monitors!(nodes[1], 1);
297 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_second_update.commitment_signed).unwrap();
298 let (bs_second_revoke, bs_second_commitment) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
299 check_added_monitors!(nodes[1], 1);
301 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke).unwrap();
302 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
303 check_added_monitors!(nodes[0], 1);
305 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment).unwrap();
306 let as_second_revoke = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
307 // No commitment_signed so get_event_msg's assert(len == 1) passes
308 check_added_monitors!(nodes[0], 1);
310 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_second_revoke).unwrap();
311 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
312 check_added_monitors!(nodes[1], 1);
316 fn test_update_fee_vanilla() {
317 let nodes = create_network(2);
318 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
319 let channel_id = chan.2;
321 let feerate = get_feerate!(nodes[0], channel_id);
322 nodes[0].node.update_fee(channel_id, feerate+25).unwrap();
323 check_added_monitors!(nodes[0], 1);
325 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
326 assert_eq!(events_0.len(), 1);
327 let (update_msg, commitment_signed) = match events_0[0] {
328 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 } } => {
329 (update_fee.as_ref(), commitment_signed)
331 _ => panic!("Unexpected event"),
333 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
335 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
336 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
337 check_added_monitors!(nodes[1], 1);
339 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
340 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
341 check_added_monitors!(nodes[0], 1);
343 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
344 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
345 // No commitment_signed so get_event_msg's assert(len == 1) passes
346 check_added_monitors!(nodes[0], 1);
348 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
349 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
350 check_added_monitors!(nodes[1], 1);
354 fn test_update_fee_that_funder_cannot_afford() {
355 let nodes = create_network(2);
356 let channel_value = 1888;
357 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 700000);
358 let channel_id = chan.2;
361 nodes[0].node.update_fee(channel_id, feerate).unwrap();
362 check_added_monitors!(nodes[0], 1);
363 let update_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
365 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update_msg.update_fee.unwrap()).unwrap();
367 commitment_signed_dance!(nodes[1], nodes[0], update_msg.commitment_signed, false);
369 //Confirm that the new fee based on the last local commitment txn is what we expected based on the feerate of 260 set above.
370 //This value results in a fee that is exactly what the funder can afford (277 sat + 1000 sat channel reserve)
372 let chan_lock = nodes[1].node.channel_state.lock().unwrap();
373 let chan = chan_lock.by_id.get(&channel_id).unwrap();
375 //We made sure neither party's funds are below the dust limit so -2 non-HTLC txns from number of outputs
376 let num_htlcs = chan.last_local_commitment_txn[0].output.len() - 2;
377 let total_fee: u64 = feerate * (COMMITMENT_TX_BASE_WEIGHT + (num_htlcs as u64) * COMMITMENT_TX_WEIGHT_PER_HTLC) / 1000;
378 let mut actual_fee = chan.last_local_commitment_txn[0].output.iter().fold(0, |acc, output| acc + output.value);
379 actual_fee = channel_value - actual_fee;
380 assert_eq!(total_fee, actual_fee);
383 //Add 2 to the previous fee rate to the final fee increases by 1 (with no HTLCs the fee is essentially
384 //fee_rate*(724/1000) so the increment of 1*0.724 is rounded back down)
385 nodes[0].node.update_fee(channel_id, feerate+2).unwrap();
386 check_added_monitors!(nodes[0], 1);
388 let update2_msg = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
390 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), &update2_msg.update_fee.unwrap()).unwrap();
392 //While producing the commitment_signed response after handling a received update_fee request the
393 //check to see if the funder, who sent the update_fee request, can afford the new fee (funder_balance >= fee+channel_reserve)
394 //Should produce and error.
395 let err = nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &update2_msg.commitment_signed).unwrap_err();
397 assert!(match err.err {
398 "Funding remote cannot afford proposed new fee" => true,
402 //clear the message we could not handle
403 nodes[1].node.get_and_clear_pending_msg_events();
407 fn test_update_fee_with_fundee_update_add_htlc() {
408 let mut nodes = create_network(2);
409 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
410 let channel_id = chan.2;
413 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
415 let feerate = get_feerate!(nodes[0], channel_id);
416 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
417 check_added_monitors!(nodes[0], 1);
419 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
420 assert_eq!(events_0.len(), 1);
421 let (update_msg, commitment_signed) = match events_0[0] {
422 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 } } => {
423 (update_fee.as_ref(), commitment_signed)
425 _ => panic!("Unexpected event"),
427 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
428 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
429 let (revoke_msg, commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
430 check_added_monitors!(nodes[1], 1);
432 let route = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &Vec::new(), 800000, TEST_FINAL_CLTV).unwrap();
434 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[1]);
436 // nothing happens since node[1] is in AwaitingRemoteRevoke
437 nodes[1].node.send_payment(route, our_payment_hash).unwrap();
439 let mut added_monitors = nodes[0].chan_monitor.added_monitors.lock().unwrap();
440 assert_eq!(added_monitors.len(), 0);
441 added_monitors.clear();
443 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
444 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
445 // node[1] has nothing to do
447 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
448 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
449 check_added_monitors!(nodes[0], 1);
451 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
452 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
453 // No commitment_signed so get_event_msg's assert(len == 1) passes
454 check_added_monitors!(nodes[0], 1);
455 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
456 check_added_monitors!(nodes[1], 1);
457 // AwaitingRemoteRevoke ends here
459 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
460 assert_eq!(commitment_update.update_add_htlcs.len(), 1);
461 assert_eq!(commitment_update.update_fulfill_htlcs.len(), 0);
462 assert_eq!(commitment_update.update_fail_htlcs.len(), 0);
463 assert_eq!(commitment_update.update_fail_malformed_htlcs.len(), 0);
464 assert_eq!(commitment_update.update_fee.is_none(), true);
466 nodes[0].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &commitment_update.update_add_htlcs[0]).unwrap();
467 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
468 check_added_monitors!(nodes[0], 1);
469 let (revoke, commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
471 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke).unwrap();
472 check_added_monitors!(nodes[1], 1);
473 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
475 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &commitment_signed).unwrap();
476 check_added_monitors!(nodes[1], 1);
477 let revoke = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
478 // No commitment_signed so get_event_msg's assert(len == 1) passes
480 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke).unwrap();
481 check_added_monitors!(nodes[0], 1);
482 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
484 expect_pending_htlcs_forwardable!(nodes[0]);
486 let events = nodes[0].node.get_and_clear_pending_events();
487 assert_eq!(events.len(), 1);
489 Event::PaymentReceived { .. } => { },
490 _ => panic!("Unexpected event"),
493 claim_payment(&nodes[1], &vec!(&nodes[0])[..], our_payment_preimage);
495 send_payment(&nodes[1], &vec!(&nodes[0])[..], 800000);
496 send_payment(&nodes[0], &vec!(&nodes[1])[..], 800000);
497 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
501 fn test_update_fee() {
502 let nodes = create_network(2);
503 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
504 let channel_id = chan.2;
507 // (1) update_fee/commitment_signed ->
508 // <- (2) revoke_and_ack
509 // .- send (3) commitment_signed
510 // (4) update_fee/commitment_signed ->
511 // .- send (5) revoke_and_ack (no CS as we're awaiting a revoke)
512 // <- (3) commitment_signed delivered
513 // send (6) revoke_and_ack -.
514 // <- (5) deliver revoke_and_ack
515 // (6) deliver revoke_and_ack ->
516 // .- send (7) commitment_signed in response to (4)
517 // <- (7) deliver commitment_signed
520 // Create and deliver (1)...
521 let feerate = get_feerate!(nodes[0], channel_id);
522 nodes[0].node.update_fee(channel_id, feerate+20).unwrap();
523 check_added_monitors!(nodes[0], 1);
525 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
526 assert_eq!(events_0.len(), 1);
527 let (update_msg, commitment_signed) = match events_0[0] {
528 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 } } => {
529 (update_fee.as_ref(), commitment_signed)
531 _ => panic!("Unexpected event"),
533 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
535 // Generate (2) and (3):
536 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
537 let (revoke_msg, commitment_signed_0) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
538 check_added_monitors!(nodes[1], 1);
541 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
542 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
543 check_added_monitors!(nodes[0], 1);
545 // Create and deliver (4)...
546 nodes[0].node.update_fee(channel_id, feerate+30).unwrap();
547 check_added_monitors!(nodes[0], 1);
548 let events_0 = nodes[0].node.get_and_clear_pending_msg_events();
549 assert_eq!(events_0.len(), 1);
550 let (update_msg, commitment_signed) = match events_0[0] {
551 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 } } => {
552 (update_fee.as_ref(), commitment_signed)
554 _ => panic!("Unexpected event"),
557 nodes[1].node.handle_update_fee(&nodes[0].node.get_our_node_id(), update_msg.unwrap()).unwrap();
558 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), commitment_signed).unwrap();
559 check_added_monitors!(nodes[1], 1);
561 let revoke_msg = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
562 // No commitment_signed so get_event_msg's assert(len == 1) passes
564 // Handle (3), creating (6):
565 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed_0).unwrap();
566 check_added_monitors!(nodes[0], 1);
567 let revoke_msg_0 = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
568 // No commitment_signed so get_event_msg's assert(len == 1) passes
571 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &revoke_msg).unwrap();
572 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
573 check_added_monitors!(nodes[0], 1);
575 // Deliver (6), creating (7):
576 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg_0).unwrap();
577 let commitment_update = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
578 assert!(commitment_update.update_add_htlcs.is_empty());
579 assert!(commitment_update.update_fulfill_htlcs.is_empty());
580 assert!(commitment_update.update_fail_htlcs.is_empty());
581 assert!(commitment_update.update_fail_malformed_htlcs.is_empty());
582 assert!(commitment_update.update_fee.is_none());
583 check_added_monitors!(nodes[1], 1);
586 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_update.commitment_signed).unwrap();
587 check_added_monitors!(nodes[0], 1);
588 let revoke_msg = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
589 // No commitment_signed so get_event_msg's assert(len == 1) passes
591 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &revoke_msg).unwrap();
592 check_added_monitors!(nodes[1], 1);
593 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
595 assert_eq!(get_feerate!(nodes[0], channel_id), feerate + 30);
596 assert_eq!(get_feerate!(nodes[1], channel_id), feerate + 30);
597 close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true);
601 fn pre_funding_lock_shutdown_test() {
602 // Test sending a shutdown prior to funding_locked after funding generation
603 let nodes = create_network(2);
604 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 8000000, 0);
605 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
606 nodes[0].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
607 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx; 1], &[1; 1]);
609 nodes[0].node.close_channel(&OutPoint::new(tx.txid(), 0).to_channel_id()).unwrap();
610 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
611 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
612 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
613 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
615 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
616 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
617 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
618 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
619 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
620 assert!(node_0_none.is_none());
622 assert!(nodes[0].node.list_channels().is_empty());
623 assert!(nodes[1].node.list_channels().is_empty());
627 fn updates_shutdown_wait() {
628 // Test sending a shutdown with outstanding updates pending
629 let mut nodes = create_network(3);
630 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
631 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
632 let route_1 = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
633 let route_2 = nodes[1].router.get_route(&nodes[0].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
635 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
637 nodes[0].node.close_channel(&chan_1.2).unwrap();
638 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
639 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
640 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
641 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
643 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
644 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
646 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
647 if let Err(APIError::ChannelUnavailable {..}) = nodes[0].node.send_payment(route_1, payment_hash) {}
648 else { panic!("New sends should fail!") };
649 if let Err(APIError::ChannelUnavailable {..}) = nodes[1].node.send_payment(route_2, payment_hash) {}
650 else { panic!("New sends should fail!") };
652 assert!(nodes[2].node.claim_funds(our_payment_preimage));
653 check_added_monitors!(nodes[2], 1);
654 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
655 assert!(updates.update_add_htlcs.is_empty());
656 assert!(updates.update_fail_htlcs.is_empty());
657 assert!(updates.update_fail_malformed_htlcs.is_empty());
658 assert!(updates.update_fee.is_none());
659 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
660 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
661 check_added_monitors!(nodes[1], 1);
662 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
663 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
665 assert!(updates_2.update_add_htlcs.is_empty());
666 assert!(updates_2.update_fail_htlcs.is_empty());
667 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
668 assert!(updates_2.update_fee.is_none());
669 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
670 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
671 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
673 let events = nodes[0].node.get_and_clear_pending_events();
674 assert_eq!(events.len(), 1);
676 Event::PaymentSent { ref payment_preimage } => {
677 assert_eq!(our_payment_preimage, *payment_preimage);
679 _ => panic!("Unexpected event"),
682 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
683 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
684 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
685 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
686 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
687 assert!(node_0_none.is_none());
689 assert!(nodes[0].node.list_channels().is_empty());
691 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
692 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
693 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
694 assert!(nodes[1].node.list_channels().is_empty());
695 assert!(nodes[2].node.list_channels().is_empty());
699 fn htlc_fail_async_shutdown() {
700 // Test HTLCs fail if shutdown starts even if messages are delivered out-of-order
701 let mut nodes = create_network(3);
702 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
703 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
705 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
706 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
707 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
708 check_added_monitors!(nodes[0], 1);
709 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
710 assert_eq!(updates.update_add_htlcs.len(), 1);
711 assert!(updates.update_fulfill_htlcs.is_empty());
712 assert!(updates.update_fail_htlcs.is_empty());
713 assert!(updates.update_fail_malformed_htlcs.is_empty());
714 assert!(updates.update_fee.is_none());
716 nodes[1].node.close_channel(&chan_1.2).unwrap();
717 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
718 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
719 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
721 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
722 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
723 check_added_monitors!(nodes[1], 1);
724 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
725 commitment_signed_dance!(nodes[1], nodes[0], (), false, true, false);
727 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
728 assert!(updates_2.update_add_htlcs.is_empty());
729 assert!(updates_2.update_fulfill_htlcs.is_empty());
730 assert_eq!(updates_2.update_fail_htlcs.len(), 1);
731 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
732 assert!(updates_2.update_fee.is_none());
734 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fail_htlcs[0]).unwrap();
735 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
737 let events = nodes[0].node.get_and_clear_pending_events();
738 assert_eq!(events.len(), 1);
740 Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } => {
741 assert_eq!(our_payment_hash, *payment_hash);
742 assert!(!rejected_by_dest);
744 _ => panic!("Unexpected event"),
747 let msg_events = nodes[0].node.get_and_clear_pending_msg_events();
748 assert_eq!(msg_events.len(), 2);
749 let node_0_closing_signed = match msg_events[0] {
750 MessageSendEvent::SendClosingSigned { ref node_id, ref msg } => {
751 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
754 _ => panic!("Unexpected event"),
756 match msg_events[1] {
757 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
758 assert_eq!(msg.contents.short_channel_id, chan_1.0.contents.short_channel_id);
760 _ => panic!("Unexpected event"),
763 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
764 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
765 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
766 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
767 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
768 assert!(node_0_none.is_none());
770 assert!(nodes[0].node.list_channels().is_empty());
772 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
773 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
774 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
775 assert!(nodes[1].node.list_channels().is_empty());
776 assert!(nodes[2].node.list_channels().is_empty());
779 fn do_test_shutdown_rebroadcast(recv_count: u8) {
780 // Test that shutdown/closing_signed is re-sent on reconnect with a variable number of
781 // messages delivered prior to disconnect
782 let nodes = create_network(3);
783 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
784 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
786 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 100000);
788 nodes[1].node.close_channel(&chan_1.2).unwrap();
789 let node_1_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
791 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_shutdown).unwrap();
792 let node_0_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
794 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_shutdown).unwrap();
798 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
799 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
801 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
802 let node_0_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
803 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
804 let node_1_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
806 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_reestablish).unwrap();
807 let node_1_2nd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
808 assert!(node_1_shutdown == node_1_2nd_shutdown);
810 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_reestablish).unwrap();
811 let node_0_2nd_shutdown = if recv_count > 0 {
812 let node_0_2nd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
813 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
816 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
817 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_2nd_shutdown).unwrap();
818 get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id())
820 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_2nd_shutdown).unwrap();
822 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
823 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
825 assert!(nodes[2].node.claim_funds(our_payment_preimage));
826 check_added_monitors!(nodes[2], 1);
827 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
828 assert!(updates.update_add_htlcs.is_empty());
829 assert!(updates.update_fail_htlcs.is_empty());
830 assert!(updates.update_fail_malformed_htlcs.is_empty());
831 assert!(updates.update_fee.is_none());
832 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
833 nodes[1].node.handle_update_fulfill_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
834 check_added_monitors!(nodes[1], 1);
835 let updates_2 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
836 commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false);
838 assert!(updates_2.update_add_htlcs.is_empty());
839 assert!(updates_2.update_fail_htlcs.is_empty());
840 assert!(updates_2.update_fail_malformed_htlcs.is_empty());
841 assert!(updates_2.update_fee.is_none());
842 assert_eq!(updates_2.update_fulfill_htlcs.len(), 1);
843 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates_2.update_fulfill_htlcs[0]).unwrap();
844 commitment_signed_dance!(nodes[0], nodes[1], updates_2.commitment_signed, false, true);
846 let events = nodes[0].node.get_and_clear_pending_events();
847 assert_eq!(events.len(), 1);
849 Event::PaymentSent { ref payment_preimage } => {
850 assert_eq!(our_payment_preimage, *payment_preimage);
852 _ => panic!("Unexpected event"),
855 let node_0_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
857 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_closing_signed).unwrap();
858 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
859 assert!(node_1_closing_signed.is_some());
862 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
863 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
865 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
866 let node_0_2nd_reestablish = get_event_msg!(nodes[0], MessageSendEvent::SendChannelReestablish, nodes[1].node.get_our_node_id());
867 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
869 // If all closing_signeds weren't delivered we can just resume where we left off...
870 let node_1_2nd_reestablish = get_event_msg!(nodes[1], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
872 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &node_1_2nd_reestablish).unwrap();
873 let node_0_3rd_shutdown = get_event_msg!(nodes[0], MessageSendEvent::SendShutdown, nodes[1].node.get_our_node_id());
874 assert!(node_0_2nd_shutdown == node_0_3rd_shutdown);
876 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish).unwrap();
877 let node_1_3rd_shutdown = get_event_msg!(nodes[1], MessageSendEvent::SendShutdown, nodes[0].node.get_our_node_id());
878 assert!(node_1_3rd_shutdown == node_1_2nd_shutdown);
880 nodes[1].node.handle_shutdown(&nodes[0].node.get_our_node_id(), &node_0_3rd_shutdown).unwrap();
881 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
883 nodes[0].node.handle_shutdown(&nodes[1].node.get_our_node_id(), &node_1_3rd_shutdown).unwrap();
884 let node_0_2nd_closing_signed = get_event_msg!(nodes[0], MessageSendEvent::SendClosingSigned, nodes[1].node.get_our_node_id());
885 assert!(node_0_closing_signed == node_0_2nd_closing_signed);
887 nodes[1].node.handle_closing_signed(&nodes[0].node.get_our_node_id(), &node_0_2nd_closing_signed).unwrap();
888 let (_, node_1_closing_signed) = get_closing_signed_broadcast!(nodes[1].node, nodes[0].node.get_our_node_id());
889 nodes[0].node.handle_closing_signed(&nodes[1].node.get_our_node_id(), &node_1_closing_signed.unwrap()).unwrap();
890 let (_, node_0_none) = get_closing_signed_broadcast!(nodes[0].node, nodes[1].node.get_our_node_id());
891 assert!(node_0_none.is_none());
893 // If one node, however, received + responded with an identical closing_signed we end
894 // up erroring and node[0] will try to broadcast its own latest commitment transaction.
895 // There isn't really anything better we can do simply, but in the future we might
896 // explore storing a set of recently-closed channels that got disconnected during
897 // closing_signed and avoiding broadcasting local commitment txn for some timeout to
898 // give our counterparty enough time to (potentially) broadcast a cooperative closing
900 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
902 if let Err(msgs::HandleError{action: Some(msgs::ErrorAction::SendErrorMessage{msg}), ..}) =
903 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &node_0_2nd_reestablish) {
904 nodes[0].node.handle_error(&nodes[1].node.get_our_node_id(), &msg);
905 let msgs::ErrorMessage {ref channel_id, ..} = msg;
906 assert_eq!(*channel_id, chan_1.2);
907 } else { panic!("Needed SendErrorMessage close"); }
909 // get_closing_signed_broadcast usually eats the BroadcastChannelUpdate for us and
910 // checks it, but in this case nodes[0] didn't ever get a chance to receive a
911 // closing_signed so we do it ourselves
912 check_closed_broadcast!(nodes[0]);
915 assert!(nodes[0].node.list_channels().is_empty());
917 assert_eq!(nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().len(), 1);
918 nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clear();
919 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, true);
920 assert!(nodes[1].node.list_channels().is_empty());
921 assert!(nodes[2].node.list_channels().is_empty());
925 fn test_shutdown_rebroadcast() {
926 do_test_shutdown_rebroadcast(0);
927 do_test_shutdown_rebroadcast(1);
928 do_test_shutdown_rebroadcast(2);
932 fn fake_network_test() {
933 // Simple test which builds a network of ChannelManagers, connects them to each other, and
934 // tests that payments get routed and transactions broadcast in semi-reasonable ways.
935 let nodes = create_network(4);
937 // Create some initial channels
938 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
939 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
940 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
942 // Rebalance the network a bit by relaying one payment through all the channels...
943 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
944 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
945 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
946 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 8000000);
948 // Send some more payments
949 send_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 1000000);
950 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1], &nodes[0])[..], 1000000);
951 send_payment(&nodes[3], &vec!(&nodes[2], &nodes[1])[..], 1000000);
953 // Test failure packets
954 let payment_hash_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], 1000000).1;
955 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3])[..], payment_hash_1);
957 // Add a new channel that skips 3
958 let chan_4 = create_announced_chan_between_nodes(&nodes, 1, 3);
960 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 1000000);
961 send_payment(&nodes[2], &vec!(&nodes[3])[..], 1000000);
962 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
963 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
964 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
965 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
966 send_payment(&nodes[1], &vec!(&nodes[3])[..], 8000000);
968 // Do some rebalance loop payments, simultaneously
969 let mut hops = Vec::with_capacity(3);
971 pubkey: nodes[2].node.get_our_node_id(),
972 short_channel_id: chan_2.0.contents.short_channel_id,
974 cltv_expiry_delta: chan_3.0.contents.cltv_expiry_delta as u32
977 pubkey: nodes[3].node.get_our_node_id(),
978 short_channel_id: chan_3.0.contents.short_channel_id,
980 cltv_expiry_delta: chan_4.1.contents.cltv_expiry_delta as u32
983 pubkey: nodes[1].node.get_our_node_id(),
984 short_channel_id: chan_4.0.contents.short_channel_id,
986 cltv_expiry_delta: TEST_FINAL_CLTV,
988 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;
989 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;
990 let payment_preimage_1 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[2], &nodes[3], &nodes[1])[..], 1000000).0;
992 let mut hops = Vec::with_capacity(3);
994 pubkey: nodes[3].node.get_our_node_id(),
995 short_channel_id: chan_4.0.contents.short_channel_id,
997 cltv_expiry_delta: chan_3.1.contents.cltv_expiry_delta as u32
1000 pubkey: nodes[2].node.get_our_node_id(),
1001 short_channel_id: chan_3.0.contents.short_channel_id,
1003 cltv_expiry_delta: chan_2.1.contents.cltv_expiry_delta as u32
1005 hops.push(RouteHop {
1006 pubkey: nodes[1].node.get_our_node_id(),
1007 short_channel_id: chan_2.0.contents.short_channel_id,
1009 cltv_expiry_delta: TEST_FINAL_CLTV,
1011 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;
1012 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;
1013 let payment_hash_2 = send_along_route(&nodes[1], Route { hops }, &vec!(&nodes[3], &nodes[2], &nodes[1])[..], 1000000).1;
1015 // Claim the rebalances...
1016 fail_payment(&nodes[1], &vec!(&nodes[3], &nodes[2], &nodes[1])[..], payment_hash_2);
1017 claim_payment(&nodes[1], &vec!(&nodes[2], &nodes[3], &nodes[1])[..], payment_preimage_1);
1019 // Add a duplicate new channel from 2 to 4
1020 let chan_5 = create_announced_chan_between_nodes(&nodes, 1, 3);
1022 // Send some payments across both channels
1023 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1024 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1025 let payment_preimage_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000).0;
1027 route_over_limit(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], 3000000);
1029 //TODO: Test that routes work again here as we've been notified that the channel is full
1031 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_3);
1032 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_4);
1033 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[3])[..], payment_preimage_5);
1035 // Close down the channels...
1036 close_channel(&nodes[0], &nodes[1], &chan_1.2, chan_1.3, true);
1037 close_channel(&nodes[1], &nodes[2], &chan_2.2, chan_2.3, false);
1038 close_channel(&nodes[2], &nodes[3], &chan_3.2, chan_3.3, true);
1039 close_channel(&nodes[1], &nodes[3], &chan_4.2, chan_4.3, false);
1040 close_channel(&nodes[1], &nodes[3], &chan_5.2, chan_5.3, false);
1044 fn holding_cell_htlc_counting() {
1045 // Tests that HTLCs in the holding cell count towards the pending HTLC limits on outbound HTLCs
1046 // to ensure we don't end up with HTLCs sitting around in our holding cell for several
1047 // commitment dance rounds.
1048 let mut nodes = create_network(3);
1049 create_announced_chan_between_nodes(&nodes, 0, 1);
1050 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1052 let mut payments = Vec::new();
1053 for _ in 0..::ln::channel::OUR_MAX_HTLCS {
1054 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1055 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1056 nodes[1].node.send_payment(route, payment_hash).unwrap();
1057 payments.push((payment_preimage, payment_hash));
1059 check_added_monitors!(nodes[1], 1);
1061 let mut events = nodes[1].node.get_and_clear_pending_msg_events();
1062 assert_eq!(events.len(), 1);
1063 let initial_payment_event = SendEvent::from_event(events.pop().unwrap());
1064 assert_eq!(initial_payment_event.node_id, nodes[2].node.get_our_node_id());
1066 // There is now one HTLC in an outbound commitment transaction and (OUR_MAX_HTLCS - 1) HTLCs in
1067 // the holding cell waiting on B's RAA to send. At this point we should not be able to add
1069 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1070 let (_, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
1071 if let APIError::ChannelUnavailable { err } = nodes[1].node.send_payment(route, payment_hash_1).unwrap_err() {
1072 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
1073 } else { panic!("Unexpected event"); }
1075 // This should also be true if we try to forward a payment.
1076 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
1077 let (_, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
1078 nodes[0].node.send_payment(route, payment_hash_2).unwrap();
1079 check_added_monitors!(nodes[0], 1);
1081 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1082 assert_eq!(events.len(), 1);
1083 let payment_event = SendEvent::from_event(events.pop().unwrap());
1084 assert_eq!(payment_event.node_id, nodes[1].node.get_our_node_id());
1086 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
1087 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
1088 // We have to forward pending HTLCs twice - once tries to forward the payment forward (and
1089 // fails), the second will process the resulting failure and fail the HTLC backward.
1090 expect_pending_htlcs_forwardable!(nodes[1]);
1091 expect_pending_htlcs_forwardable!(nodes[1]);
1092 check_added_monitors!(nodes[1], 1);
1094 let bs_fail_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1095 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_updates.update_fail_htlcs[0]).unwrap();
1096 commitment_signed_dance!(nodes[0], nodes[1], bs_fail_updates.commitment_signed, false, true);
1098 let events = nodes[0].node.get_and_clear_pending_msg_events();
1099 assert_eq!(events.len(), 1);
1101 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelUpdateMessage { ref msg }} => {
1102 assert_eq!(msg.contents.short_channel_id, chan_2.0.contents.short_channel_id);
1104 _ => panic!("Unexpected event"),
1107 let events = nodes[0].node.get_and_clear_pending_events();
1108 assert_eq!(events.len(), 1);
1110 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
1111 assert_eq!(payment_hash, payment_hash_2);
1112 assert!(!rejected_by_dest);
1114 _ => panic!("Unexpected event"),
1117 // Now forward all the pending HTLCs and claim them back
1118 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &initial_payment_event.msgs[0]).unwrap();
1119 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &initial_payment_event.commitment_msg).unwrap();
1120 check_added_monitors!(nodes[2], 1);
1122 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1123 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1124 check_added_monitors!(nodes[1], 1);
1125 let as_updates = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
1127 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1128 check_added_monitors!(nodes[1], 1);
1129 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1131 for ref update in as_updates.update_add_htlcs.iter() {
1132 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), update).unwrap();
1134 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_updates.commitment_signed).unwrap();
1135 check_added_monitors!(nodes[2], 1);
1136 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
1137 check_added_monitors!(nodes[2], 1);
1138 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1140 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1141 check_added_monitors!(nodes[1], 1);
1142 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &bs_commitment_signed).unwrap();
1143 check_added_monitors!(nodes[1], 1);
1144 let as_final_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
1146 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_final_raa).unwrap();
1147 check_added_monitors!(nodes[2], 1);
1149 expect_pending_htlcs_forwardable!(nodes[2]);
1151 let events = nodes[2].node.get_and_clear_pending_events();
1152 assert_eq!(events.len(), payments.len());
1153 for (event, &(_, ref hash)) in events.iter().zip(payments.iter()) {
1155 &Event::PaymentReceived { ref payment_hash, .. } => {
1156 assert_eq!(*payment_hash, *hash);
1158 _ => panic!("Unexpected event"),
1162 for (preimage, _) in payments.drain(..) {
1163 claim_payment(&nodes[1], &[&nodes[2]], preimage);
1166 send_payment(&nodes[0], &[&nodes[1], &nodes[2]], 1000000);
1170 fn duplicate_htlc_test() {
1171 // Test that we accept duplicate payment_hash HTLCs across the network and that
1172 // claiming/failing them are all separate and don't affect each other
1173 let mut nodes = create_network(6);
1175 // Create some initial channels to route via 3 to 4/5 from 0/1/2
1176 create_announced_chan_between_nodes(&nodes, 0, 3);
1177 create_announced_chan_between_nodes(&nodes, 1, 3);
1178 create_announced_chan_between_nodes(&nodes, 2, 3);
1179 create_announced_chan_between_nodes(&nodes, 3, 4);
1180 create_announced_chan_between_nodes(&nodes, 3, 5);
1182 let (payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], 1000000);
1184 *nodes[0].network_payment_count.borrow_mut() -= 1;
1185 assert_eq!(route_payment(&nodes[1], &vec!(&nodes[3])[..], 1000000).0, payment_preimage);
1187 *nodes[0].network_payment_count.borrow_mut() -= 1;
1188 assert_eq!(route_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], 1000000).0, payment_preimage);
1190 claim_payment(&nodes[0], &vec!(&nodes[3], &nodes[4])[..], payment_preimage);
1191 fail_payment(&nodes[2], &vec!(&nodes[3], &nodes[5])[..], payment_hash);
1192 claim_payment(&nodes[1], &vec!(&nodes[3])[..], payment_preimage);
1195 fn do_channel_reserve_test(test_recv: bool) {
1197 use std::sync::atomic::Ordering;
1198 use ln::msgs::HandleError;
1200 let mut nodes = create_network(3);
1201 let chan_1 = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1900, 1001);
1202 let chan_2 = create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1900, 1001);
1204 let mut stat01 = get_channel_value_stat!(nodes[0], chan_1.2);
1205 let mut stat11 = get_channel_value_stat!(nodes[1], chan_1.2);
1207 let mut stat12 = get_channel_value_stat!(nodes[1], chan_2.2);
1208 let mut stat22 = get_channel_value_stat!(nodes[2], chan_2.2);
1210 macro_rules! get_route_and_payment_hash {
1211 ($recv_value: expr) => {{
1212 let route = nodes[0].router.get_route(&nodes.last().unwrap().node.get_our_node_id(), None, &Vec::new(), $recv_value, TEST_FINAL_CLTV).unwrap();
1213 let (payment_preimage, payment_hash) = get_payment_preimage_hash!(nodes[0]);
1214 (route, payment_hash, payment_preimage)
1218 macro_rules! expect_forward {
1220 let mut events = $node.node.get_and_clear_pending_msg_events();
1221 assert_eq!(events.len(), 1);
1222 check_added_monitors!($node, 1);
1223 let payment_event = SendEvent::from_event(events.remove(0));
1228 let feemsat = 239; // somehow we know?
1229 let total_fee_msat = (nodes.len() - 2) as u64 * 239;
1231 let recv_value_0 = stat01.their_max_htlc_value_in_flight_msat - total_fee_msat;
1233 // attempt to send amt_msat > their_max_htlc_value_in_flight_msat
1235 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_0 + 1);
1236 assert!(route.hops.iter().rev().skip(1).all(|h| h.fee_msat == feemsat));
1237 let err = nodes[0].node.send_payment(route, our_payment_hash).err().unwrap();
1239 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight"),
1240 _ => panic!("Unknown error variants"),
1244 let mut htlc_id = 0;
1245 // channel reserve is bigger than their_max_htlc_value_in_flight_msat so loop to deplete
1246 // nodes[0]'s wealth
1248 let amt_msat = recv_value_0 + total_fee_msat;
1249 if stat01.value_to_self_msat - amt_msat < stat01.channel_reserve_msat {
1252 send_payment(&nodes[0], &vec![&nodes[1], &nodes[2]][..], recv_value_0);
1255 let (stat01_, stat11_, stat12_, stat22_) = (
1256 get_channel_value_stat!(nodes[0], chan_1.2),
1257 get_channel_value_stat!(nodes[1], chan_1.2),
1258 get_channel_value_stat!(nodes[1], chan_2.2),
1259 get_channel_value_stat!(nodes[2], chan_2.2),
1262 assert_eq!(stat01_.value_to_self_msat, stat01.value_to_self_msat - amt_msat);
1263 assert_eq!(stat11_.value_to_self_msat, stat11.value_to_self_msat + amt_msat);
1264 assert_eq!(stat12_.value_to_self_msat, stat12.value_to_self_msat - (amt_msat - feemsat));
1265 assert_eq!(stat22_.value_to_self_msat, stat22.value_to_self_msat + (amt_msat - feemsat));
1266 stat01 = stat01_; stat11 = stat11_; stat12 = stat12_; stat22 = stat22_;
1270 let recv_value = stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat;
1271 // attempt to get channel_reserve violation
1272 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value + 1);
1273 let err = nodes[0].node.send_payment(route.clone(), our_payment_hash).err().unwrap();
1275 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the reserve value"),
1276 _ => panic!("Unknown error variants"),
1280 // adding pending output
1281 let recv_value_1 = (stat01.value_to_self_msat - stat01.channel_reserve_msat - total_fee_msat)/2;
1282 let amt_msat_1 = recv_value_1 + total_fee_msat;
1284 let (route_1, our_payment_hash_1, our_payment_preimage_1) = get_route_and_payment_hash!(recv_value_1);
1285 let payment_event_1 = {
1286 nodes[0].node.send_payment(route_1, our_payment_hash_1).unwrap();
1287 check_added_monitors!(nodes[0], 1);
1289 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
1290 assert_eq!(events.len(), 1);
1291 SendEvent::from_event(events.remove(0))
1293 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event_1.msgs[0]).unwrap();
1295 // channel reserve test with htlc pending output > 0
1296 let recv_value_2 = stat01.value_to_self_msat - amt_msat_1 - stat01.channel_reserve_msat - total_fee_msat;
1298 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1299 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1300 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the reserve value"),
1301 _ => panic!("Unknown error variants"),
1306 // test channel_reserve test on nodes[1] side
1307 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_2 + 1);
1309 // Need to manually create update_add_htlc message to go around the channel reserve check in send_htlc()
1310 let secp_ctx = Secp256k1::new();
1311 let session_priv = SecretKey::from_slice(&{
1312 let mut session_key = [0; 32];
1313 rng::fill_bytes(&mut session_key);
1315 }).expect("RNG is bad!");
1317 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
1318 let onion_keys = onion_utils::construct_onion_keys(&secp_ctx, &route, &session_priv).unwrap();
1319 let (onion_payloads, htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
1320 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
1321 let msg = msgs::UpdateAddHTLC {
1322 channel_id: chan_1.2,
1324 amount_msat: htlc_msat,
1325 payment_hash: our_payment_hash,
1326 cltv_expiry: htlc_cltv,
1327 onion_routing_packet: onion_packet,
1331 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).err().unwrap();
1333 HandleError{err, .. } => assert_eq!(err, "Remote HTLC add would put them over their reserve value"),
1335 // If we send a garbage message, the channel should get closed, making the rest of this test case fail.
1336 assert_eq!(nodes[1].node.list_channels().len(), 1);
1337 assert_eq!(nodes[1].node.list_channels().len(), 1);
1338 check_closed_broadcast!(nodes[1]);
1343 // split the rest to test holding cell
1344 let recv_value_21 = recv_value_2/2;
1345 let recv_value_22 = recv_value_2 - recv_value_21 - total_fee_msat;
1347 let stat = get_channel_value_stat!(nodes[0], chan_1.2);
1348 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);
1351 // now see if they go through on both sides
1352 let (route_21, our_payment_hash_21, our_payment_preimage_21) = get_route_and_payment_hash!(recv_value_21);
1353 // but this will stuck in the holding cell
1354 nodes[0].node.send_payment(route_21, our_payment_hash_21).unwrap();
1355 check_added_monitors!(nodes[0], 0);
1356 let events = nodes[0].node.get_and_clear_pending_events();
1357 assert_eq!(events.len(), 0);
1359 // test with outbound holding cell amount > 0
1361 let (route, our_payment_hash, _) = get_route_and_payment_hash!(recv_value_22+1);
1362 match nodes[0].node.send_payment(route, our_payment_hash).err().unwrap() {
1363 APIError::ChannelUnavailable{err} => assert_eq!(err, "Cannot send value that would put us over the reserve value"),
1364 _ => panic!("Unknown error variants"),
1368 let (route_22, our_payment_hash_22, our_payment_preimage_22) = get_route_and_payment_hash!(recv_value_22);
1369 // this will also stuck in the holding cell
1370 nodes[0].node.send_payment(route_22, our_payment_hash_22).unwrap();
1371 check_added_monitors!(nodes[0], 0);
1372 assert!(nodes[0].node.get_and_clear_pending_events().is_empty());
1373 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
1375 // flush the pending htlc
1376 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event_1.commitment_msg).unwrap();
1377 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
1378 check_added_monitors!(nodes[1], 1);
1380 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
1381 check_added_monitors!(nodes[0], 1);
1382 let commitment_update_2 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
1384 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &as_commitment_signed).unwrap();
1385 let bs_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
1386 // No commitment_signed so get_event_msg's assert(len == 1) passes
1387 check_added_monitors!(nodes[0], 1);
1389 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
1390 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
1391 check_added_monitors!(nodes[1], 1);
1393 expect_pending_htlcs_forwardable!(nodes[1]);
1395 let ref payment_event_11 = expect_forward!(nodes[1]);
1396 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_11.msgs[0]).unwrap();
1397 commitment_signed_dance!(nodes[2], nodes[1], payment_event_11.commitment_msg, false);
1399 expect_pending_htlcs_forwardable!(nodes[2]);
1400 expect_payment_received!(nodes[2], our_payment_hash_1, recv_value_1);
1402 // flush the htlcs in the holding cell
1403 assert_eq!(commitment_update_2.update_add_htlcs.len(), 2);
1404 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[0]).unwrap();
1405 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &commitment_update_2.update_add_htlcs[1]).unwrap();
1406 commitment_signed_dance!(nodes[1], nodes[0], &commitment_update_2.commitment_signed, false);
1407 expect_pending_htlcs_forwardable!(nodes[1]);
1409 let ref payment_event_3 = expect_forward!(nodes[1]);
1410 assert_eq!(payment_event_3.msgs.len(), 2);
1411 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[0]).unwrap();
1412 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event_3.msgs[1]).unwrap();
1414 commitment_signed_dance!(nodes[2], nodes[1], &payment_event_3.commitment_msg, false);
1415 expect_pending_htlcs_forwardable!(nodes[2]);
1417 let events = nodes[2].node.get_and_clear_pending_events();
1418 assert_eq!(events.len(), 2);
1420 Event::PaymentReceived { ref payment_hash, amt } => {
1421 assert_eq!(our_payment_hash_21, *payment_hash);
1422 assert_eq!(recv_value_21, amt);
1424 _ => panic!("Unexpected event"),
1427 Event::PaymentReceived { ref payment_hash, amt } => {
1428 assert_eq!(our_payment_hash_22, *payment_hash);
1429 assert_eq!(recv_value_22, amt);
1431 _ => panic!("Unexpected event"),
1434 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_1);
1435 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_21);
1436 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), our_payment_preimage_22);
1438 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);
1439 let stat0 = get_channel_value_stat!(nodes[0], chan_1.2);
1440 assert_eq!(stat0.value_to_self_msat, expected_value_to_self);
1441 assert_eq!(stat0.value_to_self_msat, stat0.channel_reserve_msat);
1443 let stat2 = get_channel_value_stat!(nodes[2], chan_2.2);
1444 assert_eq!(stat2.value_to_self_msat, stat22.value_to_self_msat + recv_value_1 + recv_value_21 + recv_value_22);
1448 fn channel_reserve_test() {
1449 do_channel_reserve_test(false);
1450 do_channel_reserve_test(true);
1454 fn channel_monitor_network_test() {
1455 // Simple test which builds a network of ChannelManagers, connects them to each other, and
1456 // tests that ChannelMonitor is able to recover from various states.
1457 let nodes = create_network(5);
1459 // Create some initial channels
1460 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1461 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1462 let chan_3 = create_announced_chan_between_nodes(&nodes, 2, 3);
1463 let chan_4 = create_announced_chan_between_nodes(&nodes, 3, 4);
1465 // Rebalance the network a bit by relaying one payment through all the channels...
1466 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1467 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1468 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1469 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2], &nodes[3], &nodes[4])[..], 8000000);
1471 // Simple case with no pending HTLCs:
1472 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), true);
1474 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_1, None, HTLCType::NONE);
1475 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1476 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1477 test_txn_broadcast(&nodes[0], &chan_1, None, HTLCType::NONE);
1479 get_announce_close_broadcast_events(&nodes, 0, 1);
1480 assert_eq!(nodes[0].node.list_channels().len(), 0);
1481 assert_eq!(nodes[1].node.list_channels().len(), 1);
1483 // One pending HTLC is discarded by the force-close:
1484 let payment_preimage_1 = route_payment(&nodes[1], &vec!(&nodes[2], &nodes[3])[..], 3000000).0;
1486 // Simple case of one pending HTLC to HTLC-Timeout
1487 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), true);
1489 let mut node_txn = test_txn_broadcast(&nodes[1], &chan_2, None, HTLCType::TIMEOUT);
1490 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1491 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn.drain(..).next().unwrap()] }, 1);
1492 test_txn_broadcast(&nodes[2], &chan_2, None, HTLCType::NONE);
1494 get_announce_close_broadcast_events(&nodes, 1, 2);
1495 assert_eq!(nodes[1].node.list_channels().len(), 0);
1496 assert_eq!(nodes[2].node.list_channels().len(), 1);
1498 macro_rules! claim_funds {
1499 ($node: expr, $prev_node: expr, $preimage: expr) => {
1501 assert!($node.node.claim_funds($preimage));
1502 check_added_monitors!($node, 1);
1504 let events = $node.node.get_and_clear_pending_msg_events();
1505 assert_eq!(events.len(), 1);
1507 MessageSendEvent::UpdateHTLCs { ref node_id, updates: msgs::CommitmentUpdate { ref update_add_htlcs, ref update_fail_htlcs, .. } } => {
1508 assert!(update_add_htlcs.is_empty());
1509 assert!(update_fail_htlcs.is_empty());
1510 assert_eq!(*node_id, $prev_node.node.get_our_node_id());
1512 _ => panic!("Unexpected event"),
1518 // nodes[3] gets the preimage, but nodes[2] already disconnected, resulting in a nodes[2]
1519 // HTLC-Timeout and a nodes[3] claim against it (+ its own announces)
1520 nodes[2].node.peer_disconnected(&nodes[3].node.get_our_node_id(), true);
1522 let node_txn = test_txn_broadcast(&nodes[2], &chan_3, None, HTLCType::TIMEOUT);
1524 // Claim the payment on nodes[3], giving it knowledge of the preimage
1525 claim_funds!(nodes[3], nodes[2], payment_preimage_1);
1527 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1528 nodes[3].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 1);
1530 check_preimage_claim(&nodes[3], &node_txn);
1532 get_announce_close_broadcast_events(&nodes, 2, 3);
1533 assert_eq!(nodes[2].node.list_channels().len(), 0);
1534 assert_eq!(nodes[3].node.list_channels().len(), 1);
1536 { // Cheat and reset nodes[4]'s height to 1
1537 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1538 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![] }, 1);
1541 assert_eq!(nodes[3].node.latest_block_height.load(Ordering::Acquire), 1);
1542 assert_eq!(nodes[4].node.latest_block_height.load(Ordering::Acquire), 1);
1543 // One pending HTLC to time out:
1544 let payment_preimage_2 = route_payment(&nodes[3], &vec!(&nodes[4])[..], 3000000).0;
1545 // CLTV expires at TEST_FINAL_CLTV + 1 (current height) + 1 (added in send_payment for
1549 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1550 nodes[3].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1551 for i in 3..TEST_FINAL_CLTV + 2 + HTLC_FAIL_TIMEOUT_BLOCKS + 1 {
1552 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1553 nodes[3].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1556 let node_txn = test_txn_broadcast(&nodes[3], &chan_4, None, HTLCType::TIMEOUT);
1558 // Claim the payment on nodes[4], giving it knowledge of the preimage
1559 claim_funds!(nodes[4], nodes[3], payment_preimage_2);
1561 header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1562 nodes[4].chain_monitor.block_connected_checked(&header, 2, &Vec::new()[..], &[0; 0]);
1563 for i in 3..TEST_FINAL_CLTV + 2 - CLTV_CLAIM_BUFFER + 1 {
1564 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1565 nodes[4].chain_monitor.block_connected_checked(&header, i, &Vec::new()[..], &[0; 0]);
1568 test_txn_broadcast(&nodes[4], &chan_4, None, HTLCType::SUCCESS);
1570 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1571 nodes[4].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, TEST_FINAL_CLTV - 5);
1573 check_preimage_claim(&nodes[4], &node_txn);
1575 get_announce_close_broadcast_events(&nodes, 3, 4);
1576 assert_eq!(nodes[3].node.list_channels().len(), 0);
1577 assert_eq!(nodes[4].node.list_channels().len(), 0);
1581 fn test_justice_tx() {
1582 // Test justice txn built on revoked HTLC-Success tx, against both sides
1584 let nodes = create_network(2);
1585 // Create some new channels:
1586 let chan_5 = create_announced_chan_between_nodes(&nodes, 0, 1);
1588 // A pending HTLC which will be revoked:
1589 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1590 // Get the will-be-revoked local txn from nodes[0]
1591 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1592 assert_eq!(revoked_local_txn.len(), 2); // First commitment tx, then HTLC tx
1593 assert_eq!(revoked_local_txn[0].input.len(), 1);
1594 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_5.3.txid());
1595 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to 0 are present
1596 assert_eq!(revoked_local_txn[1].input.len(), 1);
1597 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1598 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1599 // Revoke the old state
1600 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_3);
1603 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1604 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1606 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1607 assert_eq!(node_txn.len(), 3);
1608 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1609 assert_eq!(node_txn[0].input.len(), 2); // We should claim the revoked output and the HTLC output
1611 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1612 node_txn.swap_remove(0);
1614 test_txn_broadcast(&nodes[1], &chan_5, None, HTLCType::NONE);
1616 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1617 let node_txn = test_txn_broadcast(&nodes[0], &chan_5, Some(revoked_local_txn[0].clone()), HTLCType::TIMEOUT);
1618 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1619 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1620 test_revoked_htlc_claim_txn_broadcast(&nodes[1], node_txn[1].clone());
1622 get_announce_close_broadcast_events(&nodes, 0, 1);
1624 assert_eq!(nodes[0].node.list_channels().len(), 0);
1625 assert_eq!(nodes[1].node.list_channels().len(), 0);
1627 // We test justice_tx build by A on B's revoked HTLC-Success tx
1628 // Create some new channels:
1629 let chan_6 = create_announced_chan_between_nodes(&nodes, 0, 1);
1631 // A pending HTLC which will be revoked:
1632 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1633 // Get the will-be-revoked local txn from B
1634 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
1635 assert_eq!(revoked_local_txn.len(), 1); // Only commitment tx
1636 assert_eq!(revoked_local_txn[0].input.len(), 1);
1637 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_6.3.txid());
1638 assert_eq!(revoked_local_txn[0].output.len(), 2); // Only HTLC and output back to A are present
1639 // Revoke the old state
1640 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_4);
1642 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1643 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1645 let mut node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
1646 assert_eq!(node_txn.len(), 3);
1647 assert_eq!(node_txn.pop().unwrap(), node_txn[0]); // An outpoint registration will result in a 2nd block_connected
1648 assert_eq!(node_txn[0].input.len(), 1); // We claim the received HTLC output
1650 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1651 node_txn.swap_remove(0);
1653 test_txn_broadcast(&nodes[0], &chan_6, None, HTLCType::NONE);
1655 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1656 let node_txn = test_txn_broadcast(&nodes[1], &chan_6, Some(revoked_local_txn[0].clone()), HTLCType::SUCCESS);
1657 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1658 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[1].clone()] }, 1);
1659 test_revoked_htlc_claim_txn_broadcast(&nodes[0], node_txn[1].clone());
1661 get_announce_close_broadcast_events(&nodes, 0, 1);
1662 assert_eq!(nodes[0].node.list_channels().len(), 0);
1663 assert_eq!(nodes[1].node.list_channels().len(), 0);
1667 fn revoked_output_claim() {
1668 // Simple test to ensure a node will claim a revoked output when a stale remote commitment
1669 // transaction is broadcast by its counterparty
1670 let nodes = create_network(2);
1671 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1672 // node[0] is gonna to revoke an old state thus node[1] should be able to claim the revoked output
1673 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1674 assert_eq!(revoked_local_txn.len(), 1);
1675 // Only output is the full channel value back to nodes[0]:
1676 assert_eq!(revoked_local_txn[0].output.len(), 1);
1677 // Send a payment through, updating everyone's latest commitment txn
1678 send_payment(&nodes[0], &vec!(&nodes[1])[..], 5000000);
1680 // Inform nodes[1] that nodes[0] broadcast a stale tx
1681 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1682 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1683 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1684 assert_eq!(node_txn.len(), 3); // nodes[1] will broadcast justice tx twice, and its own local state once
1686 assert_eq!(node_txn[0], node_txn[2]);
1688 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1689 check_spends!(node_txn[1], chan_1.3.clone());
1691 // Inform nodes[0] that a watchtower cheated on its behalf, so it will force-close the chan
1692 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1693 get_announce_close_broadcast_events(&nodes, 0, 1);
1697 fn claim_htlc_outputs_shared_tx() {
1698 // Node revoked old state, htlcs haven't time out yet, claim them in shared justice tx
1699 let nodes = create_network(2);
1701 // Create some new channel:
1702 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1704 // Rebalance the network to generate htlc in the two directions
1705 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1706 // 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
1707 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1708 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
1710 // Get the will-be-revoked local txn from node[0]
1711 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1712 assert_eq!(revoked_local_txn.len(), 2); // commitment tx + 1 HTLC-Timeout tx
1713 assert_eq!(revoked_local_txn[0].input.len(), 1);
1714 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
1715 assert_eq!(revoked_local_txn[1].input.len(), 1);
1716 assert_eq!(revoked_local_txn[1].input[0].previous_output.txid, revoked_local_txn[0].txid());
1717 assert_eq!(revoked_local_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT); // HTLC-Timeout
1718 check_spends!(revoked_local_txn[1], revoked_local_txn[0].clone());
1720 //Revoke the old state
1721 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
1724 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1725 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1726 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
1728 let events = nodes[1].node.get_and_clear_pending_events();
1729 assert_eq!(events.len(), 1);
1731 Event::PaymentFailed { payment_hash, .. } => {
1732 assert_eq!(payment_hash, payment_hash_2);
1734 _ => panic!("Unexpected event"),
1737 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1738 assert_eq!(node_txn.len(), 4);
1740 assert_eq!(node_txn[0].input.len(), 3); // Claim the revoked output + both revoked HTLC outputs
1741 check_spends!(node_txn[0], revoked_local_txn[0].clone());
1743 assert_eq!(node_txn[0], node_txn[3]); // justice tx is duplicated due to block re-scanning
1745 let mut witness_lens = BTreeSet::new();
1746 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
1747 witness_lens.insert(node_txn[0].input[1].witness.last().unwrap().len());
1748 witness_lens.insert(node_txn[0].input[2].witness.last().unwrap().len());
1749 assert_eq!(witness_lens.len(), 3);
1750 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
1751 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
1752 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
1754 // Next nodes[1] broadcasts its current local tx state:
1755 assert_eq!(node_txn[1].input.len(), 1);
1756 assert_eq!(node_txn[1].input[0].previous_output.txid, chan_1.3.txid()); //Spending funding tx unique txouput, tx broadcasted by ChannelManager
1758 assert_eq!(node_txn[2].input.len(), 1);
1759 let witness_script = node_txn[2].clone().input[0].witness.pop().unwrap();
1760 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
1761 assert_eq!(node_txn[2].input[0].previous_output.txid, node_txn[1].txid());
1762 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
1763 assert_ne!(node_txn[2].input[0].previous_output.txid, node_txn[0].input[1].previous_output.txid);
1765 get_announce_close_broadcast_events(&nodes, 0, 1);
1766 assert_eq!(nodes[0].node.list_channels().len(), 0);
1767 assert_eq!(nodes[1].node.list_channels().len(), 0);
1771 fn claim_htlc_outputs_single_tx() {
1772 // Node revoked old state, htlcs have timed out, claim each of them in separated justice tx
1773 let nodes = create_network(2);
1775 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1777 // Rebalance the network to generate htlc in the two directions
1778 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
1779 // 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
1780 // time as two different claim transactions as we're gonna to timeout htlc with given a high current height
1781 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
1782 let (_payment_preimage_2, payment_hash_2) = route_payment(&nodes[1], &vec!(&nodes[0])[..], 3000000);
1784 // Get the will-be-revoked local txn from node[0]
1785 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1787 //Revoke the old state
1788 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage_1);
1791 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
1792 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
1793 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 200);
1795 let events = nodes[1].node.get_and_clear_pending_events();
1796 assert_eq!(events.len(), 1);
1798 Event::PaymentFailed { payment_hash, .. } => {
1799 assert_eq!(payment_hash, payment_hash_2);
1801 _ => panic!("Unexpected event"),
1804 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
1805 assert_eq!(node_txn.len(), 12); // ChannelManager : 2, ChannelMontitor: 8 (1 standard revoked output, 2 revocation htlc tx, 1 local commitment tx + 1 htlc timeout tx) * 2 (block-rescan)
1807 assert_eq!(node_txn[0], node_txn[7]);
1808 assert_eq!(node_txn[1], node_txn[8]);
1809 assert_eq!(node_txn[2], node_txn[9]);
1810 assert_eq!(node_txn[3], node_txn[10]);
1811 assert_eq!(node_txn[4], node_txn[11]);
1812 assert_eq!(node_txn[3], node_txn[5]); //local commitment tx + htlc timeout tx broadcasted by ChannelManger
1813 assert_eq!(node_txn[4], node_txn[6]);
1815 assert_eq!(node_txn[0].input.len(), 1);
1816 assert_eq!(node_txn[1].input.len(), 1);
1817 assert_eq!(node_txn[2].input.len(), 1);
1819 let mut revoked_tx_map = HashMap::new();
1820 revoked_tx_map.insert(revoked_local_txn[0].txid(), revoked_local_txn[0].clone());
1821 node_txn[0].verify(&revoked_tx_map).unwrap();
1822 node_txn[1].verify(&revoked_tx_map).unwrap();
1823 node_txn[2].verify(&revoked_tx_map).unwrap();
1825 let mut witness_lens = BTreeSet::new();
1826 witness_lens.insert(node_txn[0].input[0].witness.last().unwrap().len());
1827 witness_lens.insert(node_txn[1].input[0].witness.last().unwrap().len());
1828 witness_lens.insert(node_txn[2].input[0].witness.last().unwrap().len());
1829 assert_eq!(witness_lens.len(), 3);
1830 assert_eq!(*witness_lens.iter().skip(0).next().unwrap(), 77); // revoked to_local
1831 assert_eq!(*witness_lens.iter().skip(1).next().unwrap(), OFFERED_HTLC_SCRIPT_WEIGHT); // revoked offered HTLC
1832 assert_eq!(*witness_lens.iter().skip(2).next().unwrap(), ACCEPTED_HTLC_SCRIPT_WEIGHT); // revoked received HTLC
1834 assert_eq!(node_txn[3].input.len(), 1);
1835 check_spends!(node_txn[3], chan_1.3.clone());
1837 assert_eq!(node_txn[4].input.len(), 1);
1838 let witness_script = node_txn[4].input[0].witness.last().unwrap();
1839 assert_eq!(witness_script.len(), OFFERED_HTLC_SCRIPT_WEIGHT); //Spending an offered htlc output
1840 assert_eq!(node_txn[4].input[0].previous_output.txid, node_txn[3].txid());
1841 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[0].input[0].previous_output.txid);
1842 assert_ne!(node_txn[4].input[0].previous_output.txid, node_txn[1].input[0].previous_output.txid);
1844 get_announce_close_broadcast_events(&nodes, 0, 1);
1845 assert_eq!(nodes[0].node.list_channels().len(), 0);
1846 assert_eq!(nodes[1].node.list_channels().len(), 0);
1850 fn test_htlc_on_chain_success() {
1851 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
1852 // ChainWatchInterface and pass the preimage backward accordingly. So here we test that ChannelManager is
1853 // broadcasting the right event to other nodes in payment path.
1854 // We test with two HTLCs simultaneously as that was not handled correctly in the past.
1855 // A --------------------> B ----------------------> C (preimage)
1856 // First, C should claim the HTLC outputs via HTLC-Success when its own latest local
1857 // commitment transaction was broadcast.
1858 // Then, B should learn the preimage from said transactions, attempting to claim backwards
1860 // B should be able to claim via preimage if A then broadcasts its local tx.
1861 // Finally, when A sees B's latest local commitment transaction it should be able to claim
1862 // the HTLC outputs via the preimage it learned (which, once confirmed should generate a
1863 // PaymentSent event).
1865 let nodes = create_network(3);
1867 // Create some initial channels
1868 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
1869 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
1871 // Rebalance the network a bit by relaying one payment through all the channels...
1872 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
1873 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
1875 let (our_payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
1876 let (our_payment_preimage_2, _payment_hash_2) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
1877 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
1879 // Broadcast legit commitment tx from C on B's chain
1880 // Broadcast HTLC Success transaction by C on received output from C's commitment tx on B's chain
1881 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
1882 assert_eq!(commitment_tx.len(), 1);
1883 check_spends!(commitment_tx[0], chan_2.3.clone());
1884 nodes[2].node.claim_funds(our_payment_preimage);
1885 nodes[2].node.claim_funds(our_payment_preimage_2);
1886 check_added_monitors!(nodes[2], 2);
1887 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
1888 assert!(updates.update_add_htlcs.is_empty());
1889 assert!(updates.update_fail_htlcs.is_empty());
1890 assert!(updates.update_fail_malformed_htlcs.is_empty());
1891 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
1893 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
1894 check_closed_broadcast!(nodes[2]);
1895 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 4 (2*2 * HTLC-Success tx)
1896 assert_eq!(node_txn.len(), 5);
1897 assert_eq!(node_txn[0], node_txn[3]);
1898 assert_eq!(node_txn[1], node_txn[4]);
1899 assert_eq!(node_txn[2], commitment_tx[0]);
1900 check_spends!(node_txn[0], commitment_tx[0].clone());
1901 check_spends!(node_txn[1], commitment_tx[0].clone());
1902 assert_eq!(node_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
1903 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
1904 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
1905 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
1906 assert_eq!(node_txn[0].lock_time, 0);
1907 assert_eq!(node_txn[1].lock_time, 0);
1909 // Verify that B's ChannelManager is able to extract preimage from HTLC Success tx and pass it backward
1910 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: node_txn}, 1);
1911 let events = nodes[1].node.get_and_clear_pending_msg_events();
1913 let mut added_monitors = nodes[1].chan_monitor.added_monitors.lock().unwrap();
1914 assert_eq!(added_monitors.len(), 2);
1915 assert_eq!(added_monitors[0].0.txid, chan_1.3.txid());
1916 assert_eq!(added_monitors[1].0.txid, chan_1.3.txid());
1917 added_monitors.clear();
1919 assert_eq!(events.len(), 2);
1921 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
1922 _ => panic!("Unexpected event"),
1925 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, .. } } => {
1926 assert!(update_add_htlcs.is_empty());
1927 assert!(update_fail_htlcs.is_empty());
1928 assert_eq!(update_fulfill_htlcs.len(), 1);
1929 assert!(update_fail_malformed_htlcs.is_empty());
1930 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
1932 _ => panic!("Unexpected event"),
1934 macro_rules! check_tx_local_broadcast {
1935 ($node: expr, $htlc_offered: expr, $commitment_tx: expr, $chan_tx: expr) => { {
1936 // ChannelManager : 3 (commitment tx, 2*HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 (block-rescan)
1937 let mut node_txn = $node.tx_broadcaster.txn_broadcasted.lock().unwrap();
1938 assert_eq!(node_txn.len(), 7);
1939 assert_eq!(node_txn[0], node_txn[5]);
1940 assert_eq!(node_txn[1], node_txn[6]);
1941 check_spends!(node_txn[0], $commitment_tx.clone());
1942 check_spends!(node_txn[1], $commitment_tx.clone());
1943 assert_ne!(node_txn[0].lock_time, 0);
1944 assert_ne!(node_txn[1].lock_time, 0);
1946 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
1947 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
1948 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
1949 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
1951 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
1952 assert_eq!(node_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
1953 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
1954 assert!(node_txn[1].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
1956 check_spends!(node_txn[2], $chan_tx.clone());
1957 check_spends!(node_txn[3], node_txn[2].clone());
1958 check_spends!(node_txn[4], node_txn[2].clone());
1959 assert_eq!(node_txn[2].input[0].witness.last().unwrap().len(), 71);
1960 assert_eq!(node_txn[3].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
1961 assert_eq!(node_txn[4].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
1962 assert!(node_txn[3].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
1963 assert!(node_txn[4].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
1964 assert_ne!(node_txn[3].lock_time, 0);
1965 assert_ne!(node_txn[4].lock_time, 0);
1969 // nodes[1] now broadcasts its own local state as a fallback, suggesting an alternate
1970 // commitment transaction with a corresponding HTLC-Timeout transactions, as well as a
1971 // timeout-claim of the output that nodes[2] just claimed via success.
1972 check_tx_local_broadcast!(nodes[1], false, commitment_tx[0], chan_2.3);
1974 // Broadcast legit commitment tx from A on B's chain
1975 // Broadcast preimage tx by B on offered output from A commitment tx on A's chain
1976 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
1977 check_spends!(commitment_tx[0], chan_1.3.clone());
1978 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
1979 check_closed_broadcast!(nodes[1]);
1980 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx), ChannelMonitor : 1 (HTLC-Success) * 2 (block-rescan)
1981 assert_eq!(node_txn.len(), 3);
1982 assert_eq!(node_txn[0], node_txn[2]);
1983 check_spends!(node_txn[0], commitment_tx[0].clone());
1984 assert_eq!(node_txn[0].input.len(), 2);
1985 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
1986 assert_eq!(node_txn[0].input[1].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
1987 assert_eq!(node_txn[0].lock_time, 0);
1988 assert!(node_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
1989 check_spends!(node_txn[1], chan_1.3.clone());
1990 assert_eq!(node_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
1991 // We don't bother to check that B can claim the HTLC output on its commitment tx here as
1992 // we already checked the same situation with A.
1994 // Verify that A's ChannelManager is able to extract preimage from preimage tx and generate PaymentSent
1995 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone(), node_txn[0].clone()] }, 1);
1996 check_closed_broadcast!(nodes[0]);
1997 let events = nodes[0].node.get_and_clear_pending_events();
1998 assert_eq!(events.len(), 2);
1999 let mut first_claimed = false;
2000 for event in events {
2002 Event::PaymentSent { payment_preimage } => {
2003 if payment_preimage == our_payment_preimage {
2004 assert!(!first_claimed);
2005 first_claimed = true;
2007 assert_eq!(payment_preimage, our_payment_preimage_2);
2010 _ => panic!("Unexpected event"),
2013 check_tx_local_broadcast!(nodes[0], true, commitment_tx[0], chan_1.3);
2017 fn test_htlc_on_chain_timeout() {
2018 // Test that in case of a unilateral close onchain, we detect the state of output thanks to
2019 // ChainWatchInterface and timeout the HTLC backward accordingly. So here we test that ChannelManager is
2020 // broadcasting the right event to other nodes in payment path.
2021 // A ------------------> B ----------------------> C (timeout)
2022 // B's commitment tx C's commitment tx
2024 // B's HTLC timeout tx B's timeout tx
2026 let nodes = create_network(3);
2028 // Create some intial channels
2029 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
2030 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2032 // Rebalance the network a bit by relaying one payment thorugh all the channels...
2033 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2034 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
2036 let (_payment_preimage, payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
2037 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2039 // Broadcast legit commitment tx from C on B's chain
2040 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2041 check_spends!(commitment_tx[0], chan_2.3.clone());
2042 nodes[2].node.fail_htlc_backwards(&payment_hash);
2043 check_added_monitors!(nodes[2], 0);
2044 expect_pending_htlcs_forwardable!(nodes[2]);
2045 check_added_monitors!(nodes[2], 1);
2047 let events = nodes[2].node.get_and_clear_pending_msg_events();
2048 assert_eq!(events.len(), 1);
2050 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, .. } } => {
2051 assert!(update_add_htlcs.is_empty());
2052 assert!(!update_fail_htlcs.is_empty());
2053 assert!(update_fulfill_htlcs.is_empty());
2054 assert!(update_fail_malformed_htlcs.is_empty());
2055 assert_eq!(nodes[1].node.get_our_node_id(), *node_id);
2057 _ => panic!("Unexpected event"),
2059 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
2060 check_closed_broadcast!(nodes[2]);
2061 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 1 (commitment tx)
2062 assert_eq!(node_txn.len(), 1);
2063 check_spends!(node_txn[0], chan_2.3.clone());
2064 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), 71);
2066 // Broadcast timeout transaction by B on received output from C's commitment tx on B's chain
2067 // Verify that B's ChannelManager is able to detect that HTLC is timeout by its own tx and react backward in consequence
2068 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2071 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
2072 assert_eq!(node_txn.len(), 8); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 6 (HTLC-Timeout tx, commitment tx, timeout tx) * 2 (block-rescan)
2073 assert_eq!(node_txn[0], node_txn[5]);
2074 assert_eq!(node_txn[1], node_txn[6]);
2075 assert_eq!(node_txn[2], node_txn[7]);
2076 check_spends!(node_txn[0], commitment_tx[0].clone());
2077 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2078 check_spends!(node_txn[1], chan_2.3.clone());
2079 check_spends!(node_txn[2], node_txn[1].clone());
2080 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2081 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2082 check_spends!(node_txn[3], chan_2.3.clone());
2083 check_spends!(node_txn[4], node_txn[3].clone());
2084 assert_eq!(node_txn[3].input[0].witness.clone().last().unwrap().len(), 71);
2085 assert_eq!(node_txn[4].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2086 timeout_tx = node_txn[0].clone();
2090 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![timeout_tx]}, 1);
2091 check_added_monitors!(nodes[1], 0);
2092 check_closed_broadcast!(nodes[1]);
2094 expect_pending_htlcs_forwardable!(nodes[1]);
2095 check_added_monitors!(nodes[1], 1);
2096 let events = nodes[1].node.get_and_clear_pending_msg_events();
2097 assert_eq!(events.len(), 1);
2099 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, .. } } => {
2100 assert!(update_add_htlcs.is_empty());
2101 assert!(!update_fail_htlcs.is_empty());
2102 assert!(update_fulfill_htlcs.is_empty());
2103 assert!(update_fail_malformed_htlcs.is_empty());
2104 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2106 _ => panic!("Unexpected event"),
2108 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
2109 assert_eq!(node_txn.len(), 0);
2111 // Broadcast legit commitment tx from B on A's chain
2112 let commitment_tx = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
2113 check_spends!(commitment_tx[0], chan_1.3.clone());
2115 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 200);
2116 check_closed_broadcast!(nodes[0]);
2117 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Timeout tx), ChannelMonitor : 2 (timeout tx) * 2 block-rescan
2118 assert_eq!(node_txn.len(), 4);
2119 assert_eq!(node_txn[0], node_txn[3]);
2120 check_spends!(node_txn[0], commitment_tx[0].clone());
2121 assert_eq!(node_txn[0].clone().input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
2122 check_spends!(node_txn[1], chan_1.3.clone());
2123 check_spends!(node_txn[2], node_txn[1].clone());
2124 assert_eq!(node_txn[1].clone().input[0].witness.last().unwrap().len(), 71);
2125 assert_eq!(node_txn[2].clone().input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
2129 fn test_simple_commitment_revoked_fail_backward() {
2130 // Test that in case of a revoked commitment tx, we detect the resolution of output by justice tx
2131 // and fail backward accordingly.
2133 let nodes = create_network(3);
2135 // Create some initial channels
2136 create_announced_chan_between_nodes(&nodes, 0, 1);
2137 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2139 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2140 // Get the will-be-revoked local txn from nodes[2]
2141 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2142 // Revoke the old state
2143 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2145 route_payment(&nodes[0], &[&nodes[1], &nodes[2]], 3000000);
2147 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2148 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2149 check_added_monitors!(nodes[1], 0);
2150 check_closed_broadcast!(nodes[1]);
2152 expect_pending_htlcs_forwardable!(nodes[1]);
2153 check_added_monitors!(nodes[1], 1);
2154 let events = nodes[1].node.get_and_clear_pending_msg_events();
2155 assert_eq!(events.len(), 1);
2157 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, .. } } => {
2158 assert!(update_add_htlcs.is_empty());
2159 assert_eq!(update_fail_htlcs.len(), 1);
2160 assert!(update_fulfill_htlcs.is_empty());
2161 assert!(update_fail_malformed_htlcs.is_empty());
2162 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2164 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2165 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2167 let events = nodes[0].node.get_and_clear_pending_msg_events();
2168 assert_eq!(events.len(), 1);
2170 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2171 _ => panic!("Unexpected event"),
2173 let events = nodes[0].node.get_and_clear_pending_events();
2174 assert_eq!(events.len(), 1);
2176 Event::PaymentFailed { .. } => {},
2177 _ => panic!("Unexpected event"),
2180 _ => panic!("Unexpected event"),
2184 fn do_test_commitment_revoked_fail_backward_exhaustive(deliver_bs_raa: bool, use_dust: bool, no_to_remote: bool) {
2185 // Test that if our counterparty broadcasts a revoked commitment transaction we fail all
2186 // pending HTLCs on that channel backwards even if the HTLCs aren't present in our latest
2187 // commitment transaction anymore.
2188 // To do this, we have the peer which will broadcast a revoked commitment transaction send
2189 // a number of update_fail/commitment_signed updates without ever sending the RAA in
2190 // response to our commitment_signed. This is somewhat misbehavior-y, though not
2191 // technically disallowed and we should probably handle it reasonably.
2192 // Note that this is pretty exhaustive as an outbound HTLC which we haven't yet
2193 // failed/fulfilled backwards must be in at least one of the latest two remote commitment
2195 // * Once we move it out of our holding cell/add it, we will immediately include it in a
2196 // commitment_signed (implying it will be in the latest remote commitment transaction).
2197 // * Once they remove it, we will send a (the first) commitment_signed without the HTLC,
2198 // and once they revoke the previous commitment transaction (allowing us to send a new
2199 // commitment_signed) we will be free to fail/fulfill the HTLC backwards.
2200 let mut nodes = create_network(3);
2202 // Create some initial channels
2203 create_announced_chan_between_nodes(&nodes, 0, 1);
2204 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
2206 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], if no_to_remote { 10_000 } else { 3_000_000 });
2207 // Get the will-be-revoked local txn from nodes[2]
2208 let revoked_local_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
2209 assert_eq!(revoked_local_txn[0].output.len(), if no_to_remote { 1 } else { 2 });
2210 // Revoke the old state
2211 claim_payment(&nodes[0], &[&nodes[1], &nodes[2]], payment_preimage);
2213 let value = if use_dust {
2214 // The dust limit applied to HTLC outputs considers the fee of the HTLC transaction as
2215 // well, so HTLCs at exactly the dust limit will not be included in commitment txn.
2216 nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().our_dust_limit_satoshis * 1000
2219 let (_, first_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2220 let (_, second_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2221 let (_, third_payment_hash) = route_payment(&nodes[0], &[&nodes[1], &nodes[2]], value);
2223 assert!(nodes[2].node.fail_htlc_backwards(&first_payment_hash));
2224 expect_pending_htlcs_forwardable!(nodes[2]);
2225 check_added_monitors!(nodes[2], 1);
2226 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2227 assert!(updates.update_add_htlcs.is_empty());
2228 assert!(updates.update_fulfill_htlcs.is_empty());
2229 assert!(updates.update_fail_malformed_htlcs.is_empty());
2230 assert_eq!(updates.update_fail_htlcs.len(), 1);
2231 assert!(updates.update_fee.is_none());
2232 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2233 let bs_raa = commitment_signed_dance!(nodes[1], nodes[2], updates.commitment_signed, false, true, false, true);
2234 // Drop the last RAA from 3 -> 2
2236 assert!(nodes[2].node.fail_htlc_backwards(&second_payment_hash));
2237 expect_pending_htlcs_forwardable!(nodes[2]);
2238 check_added_monitors!(nodes[2], 1);
2239 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2240 assert!(updates.update_add_htlcs.is_empty());
2241 assert!(updates.update_fulfill_htlcs.is_empty());
2242 assert!(updates.update_fail_malformed_htlcs.is_empty());
2243 assert_eq!(updates.update_fail_htlcs.len(), 1);
2244 assert!(updates.update_fee.is_none());
2245 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2246 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2247 check_added_monitors!(nodes[1], 1);
2248 // Note that nodes[1] is in AwaitingRAA, so won't send a CS
2249 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2250 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2251 check_added_monitors!(nodes[2], 1);
2253 assert!(nodes[2].node.fail_htlc_backwards(&third_payment_hash));
2254 expect_pending_htlcs_forwardable!(nodes[2]);
2255 check_added_monitors!(nodes[2], 1);
2256 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2257 assert!(updates.update_add_htlcs.is_empty());
2258 assert!(updates.update_fulfill_htlcs.is_empty());
2259 assert!(updates.update_fail_malformed_htlcs.is_empty());
2260 assert_eq!(updates.update_fail_htlcs.len(), 1);
2261 assert!(updates.update_fee.is_none());
2262 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
2263 // At this point first_payment_hash has dropped out of the latest two commitment
2264 // transactions that nodes[1] is tracking...
2265 nodes[1].node.handle_commitment_signed(&nodes[2].node.get_our_node_id(), &updates.commitment_signed).unwrap();
2266 check_added_monitors!(nodes[1], 1);
2267 // Note that nodes[1] is (still) in AwaitingRAA, so won't send a CS
2268 let as_raa = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[2].node.get_our_node_id());
2269 nodes[2].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &as_raa).unwrap();
2270 check_added_monitors!(nodes[2], 1);
2272 // Add a fourth HTLC, this one will get sequestered away in nodes[1]'s holding cell waiting
2273 // on nodes[2]'s RAA.
2274 let route = nodes[1].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2275 let (_, fourth_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2276 nodes[1].node.send_payment(route, fourth_payment_hash).unwrap();
2277 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2278 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2279 check_added_monitors!(nodes[1], 0);
2282 nodes[1].node.handle_revoke_and_ack(&nodes[2].node.get_our_node_id(), &bs_raa).unwrap();
2283 // One monitor for the new revocation preimage, no second on as we won't generate a new
2284 // commitment transaction for nodes[0] until process_pending_htlc_forwards().
2285 check_added_monitors!(nodes[1], 1);
2286 let events = nodes[1].node.get_and_clear_pending_events();
2287 assert_eq!(events.len(), 1);
2289 Event::PendingHTLCsForwardable { .. } => { },
2290 _ => panic!("Unexpected event"),
2292 // Deliberately don't process the pending fail-back so they all fail back at once after
2293 // block connection just like the !deliver_bs_raa case
2296 let mut failed_htlcs = HashSet::new();
2297 assert!(nodes[1].node.get_and_clear_pending_events().is_empty());
2299 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
2300 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
2302 let events = nodes[1].node.get_and_clear_pending_events();
2303 assert_eq!(events.len(), if deliver_bs_raa { 1 } else { 2 });
2305 Event::PaymentFailed { ref payment_hash, .. } => {
2306 assert_eq!(*payment_hash, fourth_payment_hash);
2308 _ => panic!("Unexpected event"),
2310 if !deliver_bs_raa {
2312 Event::PendingHTLCsForwardable { .. } => { },
2313 _ => panic!("Unexpected event"),
2316 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
2317 nodes[1].node.process_pending_htlc_forwards();
2318 check_added_monitors!(nodes[1], 1);
2320 let events = nodes[1].node.get_and_clear_pending_msg_events();
2321 assert_eq!(events.len(), if deliver_bs_raa { 3 } else { 2 });
2322 match events[if deliver_bs_raa { 1 } else { 0 }] {
2323 MessageSendEvent::BroadcastChannelUpdate { msg: msgs::ChannelUpdate { .. } } => {},
2324 _ => panic!("Unexpected event"),
2328 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, .. } } => {
2329 assert_eq!(nodes[2].node.get_our_node_id(), *node_id);
2330 assert_eq!(update_add_htlcs.len(), 1);
2331 assert!(update_fulfill_htlcs.is_empty());
2332 assert!(update_fail_htlcs.is_empty());
2333 assert!(update_fail_malformed_htlcs.is_empty());
2335 _ => panic!("Unexpected event"),
2338 match events[if deliver_bs_raa { 2 } else { 1 }] {
2339 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, .. } } => {
2340 assert!(update_add_htlcs.is_empty());
2341 assert_eq!(update_fail_htlcs.len(), 3);
2342 assert!(update_fulfill_htlcs.is_empty());
2343 assert!(update_fail_malformed_htlcs.is_empty());
2344 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
2346 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[0]).unwrap();
2347 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[1]).unwrap();
2348 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_fail_htlcs[2]).unwrap();
2350 commitment_signed_dance!(nodes[0], nodes[1], commitment_signed, false, true);
2352 let events = nodes[0].node.get_and_clear_pending_msg_events();
2353 // If we delivered B's RAA we got an unknown preimage error, not something
2354 // that we should update our routing table for.
2355 assert_eq!(events.len(), if deliver_bs_raa { 2 } else { 3 });
2356 for event in events {
2358 MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
2359 _ => panic!("Unexpected event"),
2362 let events = nodes[0].node.get_and_clear_pending_events();
2363 assert_eq!(events.len(), 3);
2365 Event::PaymentFailed { ref payment_hash, .. } => {
2366 assert!(failed_htlcs.insert(payment_hash.0));
2368 _ => panic!("Unexpected event"),
2371 Event::PaymentFailed { ref payment_hash, .. } => {
2372 assert!(failed_htlcs.insert(payment_hash.0));
2374 _ => panic!("Unexpected event"),
2377 Event::PaymentFailed { ref payment_hash, .. } => {
2378 assert!(failed_htlcs.insert(payment_hash.0));
2380 _ => panic!("Unexpected event"),
2383 _ => panic!("Unexpected event"),
2386 assert!(failed_htlcs.contains(&first_payment_hash.0));
2387 assert!(failed_htlcs.contains(&second_payment_hash.0));
2388 assert!(failed_htlcs.contains(&third_payment_hash.0));
2392 fn test_commitment_revoked_fail_backward_exhaustive_a() {
2393 do_test_commitment_revoked_fail_backward_exhaustive(false, true, false);
2394 do_test_commitment_revoked_fail_backward_exhaustive(true, true, false);
2395 do_test_commitment_revoked_fail_backward_exhaustive(false, false, false);
2396 do_test_commitment_revoked_fail_backward_exhaustive(true, false, false);
2400 fn test_commitment_revoked_fail_backward_exhaustive_b() {
2401 do_test_commitment_revoked_fail_backward_exhaustive(false, true, true);
2402 do_test_commitment_revoked_fail_backward_exhaustive(true, true, true);
2403 do_test_commitment_revoked_fail_backward_exhaustive(false, false, true);
2404 do_test_commitment_revoked_fail_backward_exhaustive(true, false, true);
2408 fn test_htlc_ignore_latest_remote_commitment() {
2409 // Test that HTLC transactions spending the latest remote commitment transaction are simply
2410 // ignored if we cannot claim them. This originally tickled an invalid unwrap().
2411 let nodes = create_network(2);
2412 create_announced_chan_between_nodes(&nodes, 0, 1);
2414 route_payment(&nodes[0], &[&nodes[1]], 10000000);
2415 nodes[0].node.force_close_channel(&nodes[0].node.list_channels()[0].channel_id);
2416 check_closed_broadcast!(nodes[0]);
2418 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
2419 assert_eq!(node_txn.len(), 2);
2421 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2422 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
2423 check_closed_broadcast!(nodes[1]);
2425 // Duplicate the block_connected call since this may happen due to other listeners
2426 // registering new transactions
2427 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&node_txn[0], &node_txn[1]], &[1; 2]);
2431 fn test_force_close_fail_back() {
2432 // Check which HTLCs are failed-backwards on channel force-closure
2433 let mut nodes = create_network(3);
2434 create_announced_chan_between_nodes(&nodes, 0, 1);
2435 create_announced_chan_between_nodes(&nodes, 1, 2);
2437 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 1000000, 42).unwrap();
2439 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
2441 let mut payment_event = {
2442 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
2443 check_added_monitors!(nodes[0], 1);
2445 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2446 assert_eq!(events.len(), 1);
2447 SendEvent::from_event(events.remove(0))
2450 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2451 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
2453 expect_pending_htlcs_forwardable!(nodes[1]);
2455 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
2456 assert_eq!(events_2.len(), 1);
2457 payment_event = SendEvent::from_event(events_2.remove(0));
2458 assert_eq!(payment_event.msgs.len(), 1);
2460 check_added_monitors!(nodes[1], 1);
2461 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2462 nodes[2].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2463 check_added_monitors!(nodes[2], 1);
2464 let (_, _) = get_revoke_commit_msgs!(nodes[2], nodes[1].node.get_our_node_id());
2466 // nodes[2] now has the latest commitment transaction, but hasn't revoked its previous
2467 // state or updated nodes[1]' state. Now force-close and broadcast that commitment/HTLC
2468 // transaction and ensure nodes[1] doesn't fail-backwards (this was originally a bug!).
2470 nodes[2].node.force_close_channel(&payment_event.commitment_msg.channel_id);
2471 check_closed_broadcast!(nodes[2]);
2473 let mut node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2474 // Note that we don't bother broadcasting the HTLC-Success transaction here as we don't
2475 // have a use for it unless nodes[2] learns the preimage somehow, the funds will go
2476 // back to nodes[1] upon timeout otherwise.
2477 assert_eq!(node_txn.len(), 1);
2481 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2482 nodes[1].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
2484 // Note no UpdateHTLCs event here from nodes[1] to nodes[0]!
2485 check_closed_broadcast!(nodes[1]);
2487 // Now check that if we add the preimage to ChannelMonitor it broadcasts our HTLC-Success..
2489 let mut monitors = nodes[2].chan_monitor.simple_monitor.monitors.lock().unwrap();
2490 monitors.get_mut(&OutPoint::new(Sha256dHash::from_slice(&payment_event.commitment_msg.channel_id[..]).unwrap(), 0)).unwrap()
2491 .provide_payment_preimage(&our_payment_hash, &our_payment_preimage);
2493 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&tx], &[1]);
2494 let node_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap();
2495 assert_eq!(node_txn.len(), 1);
2496 assert_eq!(node_txn[0].input.len(), 1);
2497 assert_eq!(node_txn[0].input[0].previous_output.txid, tx.txid());
2498 assert_eq!(node_txn[0].lock_time, 0); // Must be an HTLC-Success
2499 assert_eq!(node_txn[0].input[0].witness.len(), 5); // Must be an HTLC-Success
2501 check_spends!(node_txn[0], tx);
2505 fn test_unconf_chan() {
2506 // After creating a chan between nodes, we disconnect all blocks previously seen to force a channel close on nodes[0] side
2507 let nodes = create_network(2);
2508 create_announced_chan_between_nodes(&nodes, 0, 1);
2510 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2511 assert_eq!(channel_state.by_id.len(), 1);
2512 assert_eq!(channel_state.short_to_id.len(), 1);
2513 mem::drop(channel_state);
2515 let mut headers = Vec::new();
2516 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2517 headers.push(header.clone());
2519 header = BlockHeader { version: 0x20000000, prev_blockhash: header.bitcoin_hash(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
2520 headers.push(header.clone());
2522 while !headers.is_empty() {
2523 nodes[0].node.block_disconnected(&headers.pop().unwrap());
2525 check_closed_broadcast!(nodes[0]);
2526 let channel_state = nodes[0].node.channel_state.lock().unwrap();
2527 assert_eq!(channel_state.by_id.len(), 0);
2528 assert_eq!(channel_state.short_to_id.len(), 0);
2532 fn test_simple_peer_disconnect() {
2533 // Test that we can reconnect when there are no lost messages
2534 let nodes = create_network(3);
2535 create_announced_chan_between_nodes(&nodes, 0, 1);
2536 create_announced_chan_between_nodes(&nodes, 1, 2);
2538 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2539 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2540 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2542 let payment_preimage_1 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2543 let payment_hash_2 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2544 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_2);
2545 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_1);
2547 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2548 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2549 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2551 let payment_preimage_3 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2552 let payment_preimage_4 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).0;
2553 let payment_hash_5 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2554 let payment_hash_6 = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 1000000).1;
2556 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2557 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2559 claim_payment_along_route(&nodes[0], &vec!(&nodes[1], &nodes[2]), true, payment_preimage_3);
2560 fail_payment_along_route(&nodes[0], &[&nodes[1], &nodes[2]], true, payment_hash_5);
2562 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (1, 0), (1, 0), (false, false));
2564 let events = nodes[0].node.get_and_clear_pending_events();
2565 assert_eq!(events.len(), 2);
2567 Event::PaymentSent { payment_preimage } => {
2568 assert_eq!(payment_preimage, payment_preimage_3);
2570 _ => panic!("Unexpected event"),
2573 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
2574 assert_eq!(payment_hash, payment_hash_5);
2575 assert!(rejected_by_dest);
2577 _ => panic!("Unexpected event"),
2581 claim_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_preimage_4);
2582 fail_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), payment_hash_6);
2585 fn do_test_drop_messages_peer_disconnect(messages_delivered: u8) {
2586 // Test that we can reconnect when in-flight HTLC updates get dropped
2587 let mut nodes = create_network(2);
2588 if messages_delivered == 0 {
2589 create_chan_between_nodes_with_value_a(&nodes[0], &nodes[1], 100000, 10001);
2590 // nodes[1] doesn't receive the funding_locked message (it'll be re-sent on reconnect)
2592 create_announced_chan_between_nodes(&nodes, 0, 1);
2595 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2596 let (payment_preimage_1, payment_hash_1) = get_payment_preimage_hash!(nodes[0]);
2598 let payment_event = {
2599 nodes[0].node.send_payment(route.clone(), payment_hash_1).unwrap();
2600 check_added_monitors!(nodes[0], 1);
2602 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
2603 assert_eq!(events.len(), 1);
2604 SendEvent::from_event(events.remove(0))
2606 assert_eq!(nodes[1].node.get_our_node_id(), payment_event.node_id);
2608 if messages_delivered < 2 {
2609 // Drop the payment_event messages, and let them get re-generated in reconnect_nodes!
2611 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
2612 if messages_delivered >= 3 {
2613 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &payment_event.commitment_msg).unwrap();
2614 check_added_monitors!(nodes[1], 1);
2615 let (bs_revoke_and_ack, bs_commitment_signed) = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2617 if messages_delivered >= 4 {
2618 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2619 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2620 check_added_monitors!(nodes[0], 1);
2622 if messages_delivered >= 5 {
2623 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_commitment_signed).unwrap();
2624 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2625 // No commitment_signed so get_event_msg's assert(len == 1) passes
2626 check_added_monitors!(nodes[0], 1);
2628 if messages_delivered >= 6 {
2629 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2630 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2631 check_added_monitors!(nodes[1], 1);
2638 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2639 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2640 if messages_delivered < 3 {
2641 // Even if the funding_locked messages get exchanged, as long as nothing further was
2642 // received on either side, both sides will need to resend them.
2643 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 1), (0, 0), (0, 0), (0, 0), (false, false));
2644 } else if messages_delivered == 3 {
2645 // nodes[0] still wants its RAA + commitment_signed
2646 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (true, false));
2647 } else if messages_delivered == 4 {
2648 // nodes[0] still wants its commitment_signed
2649 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (-1, 0), (0, 0), (0, 0), (0, 0), (false, false));
2650 } else if messages_delivered == 5 {
2651 // nodes[1] still wants its final RAA
2652 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, true));
2653 } else if messages_delivered == 6 {
2654 // Everything was delivered...
2655 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2658 let events_1 = nodes[1].node.get_and_clear_pending_events();
2659 assert_eq!(events_1.len(), 1);
2661 Event::PendingHTLCsForwardable { .. } => { },
2662 _ => panic!("Unexpected event"),
2665 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2666 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2667 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2669 nodes[1].node.channel_state.lock().unwrap().next_forward = Instant::now();
2670 nodes[1].node.process_pending_htlc_forwards();
2672 let events_2 = nodes[1].node.get_and_clear_pending_events();
2673 assert_eq!(events_2.len(), 1);
2675 Event::PaymentReceived { ref payment_hash, amt } => {
2676 assert_eq!(payment_hash_1, *payment_hash);
2677 assert_eq!(amt, 1000000);
2679 _ => panic!("Unexpected event"),
2682 nodes[1].node.claim_funds(payment_preimage_1);
2683 check_added_monitors!(nodes[1], 1);
2685 let events_3 = nodes[1].node.get_and_clear_pending_msg_events();
2686 assert_eq!(events_3.len(), 1);
2687 let (update_fulfill_htlc, commitment_signed) = match events_3[0] {
2688 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
2689 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2690 assert!(updates.update_add_htlcs.is_empty());
2691 assert!(updates.update_fail_htlcs.is_empty());
2692 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
2693 assert!(updates.update_fail_malformed_htlcs.is_empty());
2694 assert!(updates.update_fee.is_none());
2695 (updates.update_fulfill_htlcs[0].clone(), updates.commitment_signed.clone())
2697 _ => panic!("Unexpected event"),
2700 if messages_delivered >= 1 {
2701 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlc).unwrap();
2703 let events_4 = nodes[0].node.get_and_clear_pending_events();
2704 assert_eq!(events_4.len(), 1);
2706 Event::PaymentSent { ref payment_preimage } => {
2707 assert_eq!(payment_preimage_1, *payment_preimage);
2709 _ => panic!("Unexpected event"),
2712 if messages_delivered >= 2 {
2713 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &commitment_signed).unwrap();
2714 check_added_monitors!(nodes[0], 1);
2715 let (as_revoke_and_ack, as_commitment_signed) = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2717 if messages_delivered >= 3 {
2718 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2719 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2720 check_added_monitors!(nodes[1], 1);
2722 if messages_delivered >= 4 {
2723 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed).unwrap();
2724 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2725 // No commitment_signed so get_event_msg's assert(len == 1) passes
2726 check_added_monitors!(nodes[1], 1);
2728 if messages_delivered >= 5 {
2729 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2730 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2731 check_added_monitors!(nodes[0], 1);
2738 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2739 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2740 if messages_delivered < 2 {
2741 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (1, 0), (0, 0), (0, 0), (false, false));
2742 //TODO: Deduplicate PaymentSent events, then enable this if:
2743 //if messages_delivered < 1 {
2744 let events_4 = nodes[0].node.get_and_clear_pending_events();
2745 assert_eq!(events_4.len(), 1);
2747 Event::PaymentSent { ref payment_preimage } => {
2748 assert_eq!(payment_preimage_1, *payment_preimage);
2750 _ => panic!("Unexpected event"),
2753 } else if messages_delivered == 2 {
2754 // nodes[0] still wants its RAA + commitment_signed
2755 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, true));
2756 } else if messages_delivered == 3 {
2757 // nodes[0] still wants its commitment_signed
2758 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, -1), (0, 0), (0, 0), (0, 0), (false, false));
2759 } else if messages_delivered == 4 {
2760 // nodes[1] still wants its final RAA
2761 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (true, false));
2762 } else if messages_delivered == 5 {
2763 // Everything was delivered...
2764 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2767 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2768 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2769 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2771 // Channel should still work fine...
2772 let payment_preimage_2 = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000).0;
2773 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
2777 fn test_drop_messages_peer_disconnect_a() {
2778 do_test_drop_messages_peer_disconnect(0);
2779 do_test_drop_messages_peer_disconnect(1);
2780 do_test_drop_messages_peer_disconnect(2);
2781 do_test_drop_messages_peer_disconnect(3);
2785 fn test_drop_messages_peer_disconnect_b() {
2786 do_test_drop_messages_peer_disconnect(4);
2787 do_test_drop_messages_peer_disconnect(5);
2788 do_test_drop_messages_peer_disconnect(6);
2792 fn test_funding_peer_disconnect() {
2793 // Test that we can lock in our funding tx while disconnected
2794 let nodes = create_network(2);
2795 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
2797 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2798 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2800 confirm_transaction(&nodes[0].chain_monitor, &tx, tx.version);
2801 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
2802 assert_eq!(events_1.len(), 1);
2804 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
2805 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
2807 _ => panic!("Unexpected event"),
2810 reconnect_nodes(&nodes[0], &nodes[1], (false, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2812 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2813 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2815 confirm_transaction(&nodes[1].chain_monitor, &tx, tx.version);
2816 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
2817 assert_eq!(events_2.len(), 2);
2819 MessageSendEvent::SendFundingLocked { ref node_id, msg: _ } => {
2820 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2822 _ => panic!("Unexpected event"),
2825 MessageSendEvent::SendAnnouncementSignatures { ref node_id, msg: _ } => {
2826 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2828 _ => panic!("Unexpected event"),
2831 reconnect_nodes(&nodes[0], &nodes[1], (true, true), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
2833 // TODO: We shouldn't need to manually pass list_usable_chanels here once we support
2834 // rebroadcasting announcement_signatures upon reconnect.
2836 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), Some(&nodes[0].node.list_usable_channels()), &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2837 let (payment_preimage, _) = send_along_route(&nodes[0], route, &[&nodes[1]], 1000000);
2838 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage);
2842 fn test_drop_messages_peer_disconnect_dual_htlc() {
2843 // Test that we can handle reconnecting when both sides of a channel have pending
2844 // commitment_updates when we disconnect.
2845 let mut nodes = create_network(2);
2846 create_announced_chan_between_nodes(&nodes, 0, 1);
2848 let (payment_preimage_1, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
2850 // Now try to send a second payment which will fail to send
2851 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
2852 let (payment_preimage_2, payment_hash_2) = get_payment_preimage_hash!(nodes[0]);
2854 nodes[0].node.send_payment(route.clone(), payment_hash_2).unwrap();
2855 check_added_monitors!(nodes[0], 1);
2857 let events_1 = nodes[0].node.get_and_clear_pending_msg_events();
2858 assert_eq!(events_1.len(), 1);
2860 MessageSendEvent::UpdateHTLCs { .. } => {},
2861 _ => panic!("Unexpected event"),
2864 assert!(nodes[1].node.claim_funds(payment_preimage_1));
2865 check_added_monitors!(nodes[1], 1);
2867 let events_2 = nodes[1].node.get_and_clear_pending_msg_events();
2868 assert_eq!(events_2.len(), 1);
2870 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 } } => {
2871 assert_eq!(*node_id, nodes[0].node.get_our_node_id());
2872 assert!(update_add_htlcs.is_empty());
2873 assert_eq!(update_fulfill_htlcs.len(), 1);
2874 assert!(update_fail_htlcs.is_empty());
2875 assert!(update_fail_malformed_htlcs.is_empty());
2876 assert!(update_fee.is_none());
2878 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_htlcs[0]).unwrap();
2879 let events_3 = nodes[0].node.get_and_clear_pending_events();
2880 assert_eq!(events_3.len(), 1);
2882 Event::PaymentSent { ref payment_preimage } => {
2883 assert_eq!(*payment_preimage, payment_preimage_1);
2885 _ => panic!("Unexpected event"),
2888 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), commitment_signed).unwrap();
2889 let _ = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2890 // No commitment_signed so get_event_msg's assert(len == 1) passes
2891 check_added_monitors!(nodes[0], 1);
2893 _ => panic!("Unexpected event"),
2896 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
2897 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
2899 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
2900 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
2901 assert_eq!(reestablish_1.len(), 1);
2902 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
2903 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
2904 assert_eq!(reestablish_2.len(), 1);
2906 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
2907 let as_resp = handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
2908 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
2909 let bs_resp = handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
2911 assert!(as_resp.0.is_none());
2912 assert!(bs_resp.0.is_none());
2914 assert!(bs_resp.1.is_none());
2915 assert!(bs_resp.2.is_none());
2917 assert!(as_resp.3 == RAACommitmentOrder::CommitmentFirst);
2919 assert_eq!(as_resp.2.as_ref().unwrap().update_add_htlcs.len(), 1);
2920 assert!(as_resp.2.as_ref().unwrap().update_fulfill_htlcs.is_empty());
2921 assert!(as_resp.2.as_ref().unwrap().update_fail_htlcs.is_empty());
2922 assert!(as_resp.2.as_ref().unwrap().update_fail_malformed_htlcs.is_empty());
2923 assert!(as_resp.2.as_ref().unwrap().update_fee.is_none());
2924 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().update_add_htlcs[0]).unwrap();
2925 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_resp.2.as_ref().unwrap().commitment_signed).unwrap();
2926 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2927 // No commitment_signed so get_event_msg's assert(len == 1) passes
2928 check_added_monitors!(nodes[1], 1);
2930 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), as_resp.1.as_ref().unwrap()).unwrap();
2931 let bs_second_commitment_signed = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
2932 assert!(bs_second_commitment_signed.update_add_htlcs.is_empty());
2933 assert!(bs_second_commitment_signed.update_fulfill_htlcs.is_empty());
2934 assert!(bs_second_commitment_signed.update_fail_htlcs.is_empty());
2935 assert!(bs_second_commitment_signed.update_fail_malformed_htlcs.is_empty());
2936 assert!(bs_second_commitment_signed.update_fee.is_none());
2937 check_added_monitors!(nodes[1], 1);
2939 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
2940 let as_commitment_signed = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
2941 assert!(as_commitment_signed.update_add_htlcs.is_empty());
2942 assert!(as_commitment_signed.update_fulfill_htlcs.is_empty());
2943 assert!(as_commitment_signed.update_fail_htlcs.is_empty());
2944 assert!(as_commitment_signed.update_fail_malformed_htlcs.is_empty());
2945 assert!(as_commitment_signed.update_fee.is_none());
2946 check_added_monitors!(nodes[0], 1);
2948 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_second_commitment_signed.commitment_signed).unwrap();
2949 let as_revoke_and_ack = get_event_msg!(nodes[0], MessageSendEvent::SendRevokeAndACK, nodes[1].node.get_our_node_id());
2950 // No commitment_signed so get_event_msg's assert(len == 1) passes
2951 check_added_monitors!(nodes[0], 1);
2953 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_commitment_signed.commitment_signed).unwrap();
2954 let bs_second_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
2955 // No commitment_signed so get_event_msg's assert(len == 1) passes
2956 check_added_monitors!(nodes[1], 1);
2958 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_revoke_and_ack).unwrap();
2959 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
2960 check_added_monitors!(nodes[1], 1);
2962 expect_pending_htlcs_forwardable!(nodes[1]);
2964 let events_5 = nodes[1].node.get_and_clear_pending_events();
2965 assert_eq!(events_5.len(), 1);
2967 Event::PaymentReceived { ref payment_hash, amt: _ } => {
2968 assert_eq!(payment_hash_2, *payment_hash);
2970 _ => panic!("Unexpected event"),
2973 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_second_revoke_and_ack).unwrap();
2974 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
2975 check_added_monitors!(nodes[0], 1);
2977 claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
2981 fn test_invalid_channel_announcement() {
2982 //Test BOLT 7 channel_announcement msg requirement for final node, gather data to build customed channel_announcement msgs
2983 let secp_ctx = Secp256k1::new();
2984 let nodes = create_network(2);
2986 let chan_announcement = create_chan_between_nodes(&nodes[0], &nodes[1]);
2988 let a_channel_lock = nodes[0].node.channel_state.lock().unwrap();
2989 let b_channel_lock = nodes[1].node.channel_state.lock().unwrap();
2990 let as_chan = a_channel_lock.by_id.get(&chan_announcement.3).unwrap();
2991 let bs_chan = b_channel_lock.by_id.get(&chan_announcement.3).unwrap();
2993 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
2995 let as_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &as_chan.get_local_keys().funding_key);
2996 let bs_bitcoin_key = PublicKey::from_secret_key(&secp_ctx, &bs_chan.get_local_keys().funding_key);
2998 let as_network_key = nodes[0].node.get_our_node_id();
2999 let bs_network_key = nodes[1].node.get_our_node_id();
3001 let were_node_one = as_bitcoin_key.serialize()[..] < bs_bitcoin_key.serialize()[..];
3003 let mut chan_announcement;
3005 macro_rules! dummy_unsigned_msg {
3007 msgs::UnsignedChannelAnnouncement {
3008 features: msgs::GlobalFeatures::new(),
3009 chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
3010 short_channel_id: as_chan.get_short_channel_id().unwrap(),
3011 node_id_1: if were_node_one { as_network_key } else { bs_network_key },
3012 node_id_2: if were_node_one { bs_network_key } else { as_network_key },
3013 bitcoin_key_1: if were_node_one { as_bitcoin_key } else { bs_bitcoin_key },
3014 bitcoin_key_2: if were_node_one { bs_bitcoin_key } else { as_bitcoin_key },
3015 excess_data: Vec::new(),
3020 macro_rules! sign_msg {
3021 ($unsigned_msg: expr) => {
3022 let msghash = Message::from_slice(&Sha256dHash::hash(&$unsigned_msg.encode()[..])[..]).unwrap();
3023 let as_bitcoin_sig = secp_ctx.sign(&msghash, &as_chan.get_local_keys().funding_key);
3024 let bs_bitcoin_sig = secp_ctx.sign(&msghash, &bs_chan.get_local_keys().funding_key);
3025 let as_node_sig = secp_ctx.sign(&msghash, &nodes[0].keys_manager.get_node_secret());
3026 let bs_node_sig = secp_ctx.sign(&msghash, &nodes[1].keys_manager.get_node_secret());
3027 chan_announcement = msgs::ChannelAnnouncement {
3028 node_signature_1 : if were_node_one { as_node_sig } else { bs_node_sig},
3029 node_signature_2 : if were_node_one { bs_node_sig } else { as_node_sig},
3030 bitcoin_signature_1: if were_node_one { as_bitcoin_sig } else { bs_bitcoin_sig },
3031 bitcoin_signature_2 : if were_node_one { bs_bitcoin_sig } else { as_bitcoin_sig },
3032 contents: $unsigned_msg
3037 let unsigned_msg = dummy_unsigned_msg!();
3038 sign_msg!(unsigned_msg);
3039 assert_eq!(nodes[0].router.handle_channel_announcement(&chan_announcement).unwrap(), true);
3040 let _ = nodes[0].router.handle_htlc_fail_channel_update(&msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id : as_chan.get_short_channel_id().unwrap(), is_permanent: false } );
3042 // Configured with Network::Testnet
3043 let mut unsigned_msg = dummy_unsigned_msg!();
3044 unsigned_msg.chain_hash = genesis_block(Network::Bitcoin).header.bitcoin_hash();
3045 sign_msg!(unsigned_msg);
3046 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3048 let mut unsigned_msg = dummy_unsigned_msg!();
3049 unsigned_msg.chain_hash = Sha256dHash::hash(&[1,2,3,4,5,6,7,8,9]);
3050 sign_msg!(unsigned_msg);
3051 assert!(nodes[0].router.handle_channel_announcement(&chan_announcement).is_err());
3055 fn test_no_txn_manager_serialize_deserialize() {
3056 let mut nodes = create_network(2);
3058 let tx = create_chan_between_nodes_with_value_init(&nodes[0], &nodes[1], 100000, 10001);
3060 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3062 let nodes_0_serialized = nodes[0].node.encode();
3063 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3064 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3066 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
3067 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3068 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3069 assert!(chan_0_monitor_read.is_empty());
3071 let mut nodes_0_read = &nodes_0_serialized[..];
3072 let config = UserConfig::new();
3073 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3074 let (_, nodes_0_deserialized) = {
3075 let mut channel_monitors = HashMap::new();
3076 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3077 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3078 default_config: config,
3080 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3081 monitor: nodes[0].chan_monitor.clone(),
3082 chain_monitor: nodes[0].chain_monitor.clone(),
3083 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3084 logger: Arc::new(test_utils::TestLogger::new()),
3085 channel_monitors: &channel_monitors,
3088 assert!(nodes_0_read.is_empty());
3090 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3091 nodes[0].node = Arc::new(nodes_0_deserialized);
3092 let nodes_0_as_listener: Arc<ChainListener> = nodes[0].node.clone();
3093 nodes[0].chain_monitor.register_listener(Arc::downgrade(&nodes_0_as_listener));
3094 assert_eq!(nodes[0].node.list_channels().len(), 1);
3095 check_added_monitors!(nodes[0], 1);
3097 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
3098 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
3099 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
3100 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
3102 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
3103 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
3104 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
3105 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3107 let (funding_locked, _) = create_chan_between_nodes_with_value_confirm(&nodes[0], &nodes[1], &tx);
3108 let (announcement, as_update, bs_update) = create_chan_between_nodes_with_value_b(&nodes[0], &nodes[1], &funding_locked);
3109 for node in nodes.iter() {
3110 assert!(node.router.handle_channel_announcement(&announcement).unwrap());
3111 node.router.handle_channel_update(&as_update).unwrap();
3112 node.router.handle_channel_update(&bs_update).unwrap();
3115 send_payment(&nodes[0], &[&nodes[1]], 1000000);
3119 fn test_simple_manager_serialize_deserialize() {
3120 let mut nodes = create_network(2);
3121 create_announced_chan_between_nodes(&nodes, 0, 1);
3123 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3124 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], 1000000);
3126 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3128 let nodes_0_serialized = nodes[0].node.encode();
3129 let mut chan_0_monitor_serialized = test_utils::TestVecWriter(Vec::new());
3130 nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter().next().unwrap().1.write_for_disk(&mut chan_0_monitor_serialized).unwrap();
3132 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
3133 let mut chan_0_monitor_read = &chan_0_monitor_serialized.0[..];
3134 let (_, chan_0_monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut chan_0_monitor_read, Arc::new(test_utils::TestLogger::new())).unwrap();
3135 assert!(chan_0_monitor_read.is_empty());
3137 let mut nodes_0_read = &nodes_0_serialized[..];
3138 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3139 let (_, nodes_0_deserialized) = {
3140 let mut channel_monitors = HashMap::new();
3141 channel_monitors.insert(chan_0_monitor.get_funding_txo().unwrap(), &chan_0_monitor);
3142 <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3143 default_config: UserConfig::new(),
3145 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3146 monitor: nodes[0].chan_monitor.clone(),
3147 chain_monitor: nodes[0].chain_monitor.clone(),
3148 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3149 logger: Arc::new(test_utils::TestLogger::new()),
3150 channel_monitors: &channel_monitors,
3153 assert!(nodes_0_read.is_empty());
3155 assert!(nodes[0].chan_monitor.add_update_monitor(chan_0_monitor.get_funding_txo().unwrap(), chan_0_monitor).is_ok());
3156 nodes[0].node = Arc::new(nodes_0_deserialized);
3157 check_added_monitors!(nodes[0], 1);
3159 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3161 fail_payment(&nodes[0], &[&nodes[1]], our_payment_hash);
3162 claim_payment(&nodes[0], &[&nodes[1]], our_payment_preimage);
3166 fn test_manager_serialize_deserialize_inconsistent_monitor() {
3167 // Test deserializing a ChannelManager with an out-of-date ChannelMonitor
3168 let mut nodes = create_network(4);
3169 create_announced_chan_between_nodes(&nodes, 0, 1);
3170 create_announced_chan_between_nodes(&nodes, 2, 0);
3171 let (_, _, channel_id, funding_tx) = create_announced_chan_between_nodes(&nodes, 0, 3);
3173 let (our_payment_preimage, _) = route_payment(&nodes[2], &[&nodes[0], &nodes[1]], 1000000);
3175 // Serialize the ChannelManager here, but the monitor we keep up-to-date
3176 let nodes_0_serialized = nodes[0].node.encode();
3178 route_payment(&nodes[0], &[&nodes[3]], 1000000);
3179 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3180 nodes[2].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3181 nodes[3].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
3183 // Now the ChannelMonitor (which is now out-of-sync with ChannelManager for channel w/
3185 let mut node_0_monitors_serialized = Vec::new();
3186 for monitor in nodes[0].chan_monitor.simple_monitor.monitors.lock().unwrap().iter() {
3187 let mut writer = test_utils::TestVecWriter(Vec::new());
3188 monitor.1.write_for_disk(&mut writer).unwrap();
3189 node_0_monitors_serialized.push(writer.0);
3192 nodes[0].chan_monitor = Arc::new(test_utils::TestChannelMonitor::new(nodes[0].chain_monitor.clone(), nodes[0].tx_broadcaster.clone(), Arc::new(test_utils::TestLogger::new())));
3193 let mut node_0_monitors = Vec::new();
3194 for serialized in node_0_monitors_serialized.iter() {
3195 let mut read = &serialized[..];
3196 let (_, monitor) = <(Sha256dHash, ChannelMonitor)>::read(&mut read, Arc::new(test_utils::TestLogger::new())).unwrap();
3197 assert!(read.is_empty());
3198 node_0_monitors.push(monitor);
3201 let mut nodes_0_read = &nodes_0_serialized[..];
3202 let keys_manager = Arc::new(keysinterface::KeysManager::new(&nodes[0].node_seed, Network::Testnet, Arc::new(test_utils::TestLogger::new())));
3203 let (_, nodes_0_deserialized) = <(Sha256dHash, ChannelManager)>::read(&mut nodes_0_read, ChannelManagerReadArgs {
3204 default_config: UserConfig::new(),
3206 fee_estimator: Arc::new(test_utils::TestFeeEstimator { sat_per_kw: 253 }),
3207 monitor: nodes[0].chan_monitor.clone(),
3208 chain_monitor: nodes[0].chain_monitor.clone(),
3209 tx_broadcaster: nodes[0].tx_broadcaster.clone(),
3210 logger: Arc::new(test_utils::TestLogger::new()),
3211 channel_monitors: &node_0_monitors.iter().map(|monitor| { (monitor.get_funding_txo().unwrap(), monitor) }).collect(),
3213 assert!(nodes_0_read.is_empty());
3215 { // Channel close should result in a commitment tx and an HTLC tx
3216 let txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3217 assert_eq!(txn.len(), 2);
3218 assert_eq!(txn[0].input[0].previous_output.txid, funding_tx.txid());
3219 assert_eq!(txn[1].input[0].previous_output.txid, txn[0].txid());
3222 for monitor in node_0_monitors.drain(..) {
3223 assert!(nodes[0].chan_monitor.add_update_monitor(monitor.get_funding_txo().unwrap(), monitor).is_ok());
3224 check_added_monitors!(nodes[0], 1);
3226 nodes[0].node = Arc::new(nodes_0_deserialized);
3228 // nodes[1] and nodes[2] have no lost state with nodes[0]...
3229 reconnect_nodes(&nodes[0], &nodes[1], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3230 reconnect_nodes(&nodes[0], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
3231 //... and we can even still claim the payment!
3232 claim_payment(&nodes[2], &[&nodes[0], &nodes[1]], our_payment_preimage);
3234 nodes[3].node.peer_connected(&nodes[0].node.get_our_node_id());
3235 let reestablish = get_event_msg!(nodes[3], MessageSendEvent::SendChannelReestablish, nodes[0].node.get_our_node_id());
3236 nodes[0].node.peer_connected(&nodes[3].node.get_our_node_id());
3237 if let Err(msgs::HandleError { action: Some(msgs::ErrorAction::SendErrorMessage { msg }), .. }) = nodes[0].node.handle_channel_reestablish(&nodes[3].node.get_our_node_id(), &reestablish) {
3238 assert_eq!(msg.channel_id, channel_id);
3239 } else { panic!("Unexpected result"); }
3242 macro_rules! check_spendable_outputs {
3243 ($node: expr, $der_idx: expr) => {
3245 let events = $node.chan_monitor.simple_monitor.get_and_clear_pending_events();
3246 let mut txn = Vec::new();
3247 for event in events {
3249 Event::SpendableOutputs { ref outputs } => {
3250 for outp in outputs {
3252 SpendableOutputDescriptor::DynamicOutputP2WPKH { ref outpoint, ref key, ref output } => {
3254 previous_output: outpoint.clone(),
3255 script_sig: Script::new(),
3257 witness: Vec::new(),
3260 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3261 value: output.value,
3263 let mut spend_tx = Transaction {
3269 let secp_ctx = Secp256k1::new();
3270 let remotepubkey = PublicKey::from_secret_key(&secp_ctx, &key);
3271 let witness_script = Address::p2pkh(&::bitcoin::PublicKey{compressed: true, key: remotepubkey}, Network::Testnet).script_pubkey();
3272 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3273 let remotesig = secp_ctx.sign(&sighash, key);
3274 spend_tx.input[0].witness.push(remotesig.serialize_der().to_vec());
3275 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3276 spend_tx.input[0].witness.push(remotepubkey.serialize().to_vec());
3279 SpendableOutputDescriptor::DynamicOutputP2WSH { ref outpoint, ref key, ref witness_script, ref to_self_delay, ref output } => {
3281 previous_output: outpoint.clone(),
3282 script_sig: Script::new(),
3283 sequence: *to_self_delay as u32,
3284 witness: Vec::new(),
3287 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3288 value: output.value,
3290 let mut spend_tx = Transaction {
3296 let secp_ctx = Secp256k1::new();
3297 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], witness_script, output.value)[..]).unwrap();
3298 let local_delaysig = secp_ctx.sign(&sighash, key);
3299 spend_tx.input[0].witness.push(local_delaysig.serialize_der().to_vec());
3300 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3301 spend_tx.input[0].witness.push(vec!(0));
3302 spend_tx.input[0].witness.push(witness_script.clone().into_bytes());
3305 SpendableOutputDescriptor::StaticOutput { ref outpoint, ref output } => {
3306 let secp_ctx = Secp256k1::new();
3308 previous_output: outpoint.clone(),
3309 script_sig: Script::new(),
3311 witness: Vec::new(),
3314 script_pubkey: Builder::new().push_opcode(opcodes::all::OP_RETURN).into_script(),
3315 value: output.value,
3317 let mut spend_tx = Transaction {
3321 output: vec![outp.clone()],
3324 match ExtendedPrivKey::new_master(Network::Testnet, &$node.node_seed) {
3326 match master_key.ckd_priv(&secp_ctx, ChildNumber::from_hardened_idx($der_idx).expect("key space exhausted")) {
3328 Err(_) => panic!("Your RNG is busted"),
3331 Err(_) => panic!("Your rng is busted"),
3334 let pubkey = ExtendedPubKey::from_private(&secp_ctx, &secret).public_key;
3335 let witness_script = Address::p2pkh(&pubkey, Network::Testnet).script_pubkey();
3336 let sighash = Message::from_slice(&bip143::SighashComponents::new(&spend_tx).sighash_all(&spend_tx.input[0], &witness_script, output.value)[..]).unwrap();
3337 let sig = secp_ctx.sign(&sighash, &secret.private_key.key);
3338 spend_tx.input[0].witness.push(sig.serialize_der().to_vec());
3339 spend_tx.input[0].witness[0].push(SigHashType::All as u8);
3340 spend_tx.input[0].witness.push(pubkey.key.serialize().to_vec());
3346 _ => panic!("Unexpected event"),
3355 fn test_claim_sizeable_push_msat() {
3356 // Incidentally test SpendableOutput event generation due to detection of to_local output on commitment tx
3357 let nodes = create_network(2);
3359 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
3360 nodes[1].node.force_close_channel(&chan.2);
3361 check_closed_broadcast!(nodes[1]);
3362 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3363 assert_eq!(node_txn.len(), 1);
3364 check_spends!(node_txn[0], chan.3.clone());
3365 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
3367 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3368 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3369 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3370 assert_eq!(spend_txn.len(), 1);
3371 check_spends!(spend_txn[0], node_txn[0].clone());
3375 fn test_claim_on_remote_sizeable_push_msat() {
3376 // Same test as previous, just test on remote commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3377 // to_remote output is encumbered by a P2WPKH
3379 let nodes = create_network(2);
3381 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 99000000);
3382 nodes[0].node.force_close_channel(&chan.2);
3383 check_closed_broadcast!(nodes[0]);
3385 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3386 assert_eq!(node_txn.len(), 1);
3387 check_spends!(node_txn[0], chan.3.clone());
3388 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
3390 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3391 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![node_txn[0].clone()] }, 0);
3392 check_closed_broadcast!(nodes[1]);
3393 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3394 assert_eq!(spend_txn.len(), 2);
3395 assert_eq!(spend_txn[0], spend_txn[1]);
3396 check_spends!(spend_txn[0], node_txn[0].clone());
3400 fn test_claim_on_remote_revoked_sizeable_push_msat() {
3401 // Same test as previous, just test on remote revoked commitment tx, as per_commitment_point registration changes following you're funder/fundee and
3402 // to_remote output is encumbered by a P2WPKH
3404 let nodes = create_network(2);
3406 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 59000000);
3407 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3408 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
3409 assert_eq!(revoked_local_txn[0].input.len(), 1);
3410 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan.3.txid());
3412 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3413 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3414 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3415 check_closed_broadcast!(nodes[1]);
3417 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3418 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3419 assert_eq!(spend_txn.len(), 4);
3420 assert_eq!(spend_txn[0], spend_txn[2]); // to_remote output on revoked remote commitment_tx
3421 check_spends!(spend_txn[0], revoked_local_txn[0].clone());
3422 assert_eq!(spend_txn[1], spend_txn[3]); // to_local output on local commitment tx
3423 check_spends!(spend_txn[1], node_txn[0].clone());
3427 fn test_static_spendable_outputs_preimage_tx() {
3428 let nodes = create_network(2);
3430 // Create some initial channels
3431 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3433 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3435 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3436 assert_eq!(commitment_tx[0].input.len(), 1);
3437 assert_eq!(commitment_tx[0].input[0].previous_output.txid, chan_1.3.txid());
3439 // Settle A's commitment tx on B's chain
3440 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3441 assert!(nodes[1].node.claim_funds(payment_preimage));
3442 check_added_monitors!(nodes[1], 1);
3443 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()] }, 1);
3444 let events = nodes[1].node.get_and_clear_pending_msg_events();
3446 MessageSendEvent::UpdateHTLCs { .. } => {},
3447 _ => panic!("Unexpected event"),
3450 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3451 _ => panic!("Unexepected event"),
3454 // Check B's monitor was able to send back output descriptor event for preimage tx on A's commitment tx
3455 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap(); // ChannelManager : 1 (local commitment tx), ChannelMonitor: 2 (1 preimage tx) * 2 (block-rescan)
3456 check_spends!(node_txn[0], commitment_tx[0].clone());
3457 assert_eq!(node_txn[0], node_txn[2]);
3458 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3459 check_spends!(node_txn[1], chan_1.3.clone());
3461 let spend_txn = check_spendable_outputs!(nodes[1], 1); // , 0, 0, 1, 1);
3462 assert_eq!(spend_txn.len(), 2);
3463 assert_eq!(spend_txn[0], spend_txn[1]);
3464 check_spends!(spend_txn[0], node_txn[0].clone());
3468 fn test_static_spendable_outputs_justice_tx_revoked_commitment_tx() {
3469 let nodes = create_network(2);
3471 // Create some initial channels
3472 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3474 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3475 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.iter().next().unwrap().1.last_local_commitment_txn.clone();
3476 assert_eq!(revoked_local_txn[0].input.len(), 1);
3477 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3479 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3481 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3482 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3483 check_closed_broadcast!(nodes[1]);
3485 let mut node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3486 assert_eq!(node_txn.len(), 3);
3487 assert_eq!(node_txn.pop().unwrap(), node_txn[0]);
3488 assert_eq!(node_txn[0].input.len(), 2);
3489 check_spends!(node_txn[0], revoked_local_txn[0].clone());
3491 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3492 assert_eq!(spend_txn.len(), 2);
3493 assert_eq!(spend_txn[0], spend_txn[1]);
3494 check_spends!(spend_txn[0], node_txn[0].clone());
3498 fn test_static_spendable_outputs_justice_tx_revoked_htlc_timeout_tx() {
3499 let nodes = create_network(2);
3501 // Create some initial channels
3502 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3504 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3505 let revoked_local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3506 assert_eq!(revoked_local_txn[0].input.len(), 1);
3507 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3509 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3511 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3512 // A will generate HTLC-Timeout from revoked commitment tx
3513 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3514 check_closed_broadcast!(nodes[0]);
3516 let revoked_htlc_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3517 assert_eq!(revoked_htlc_txn.len(), 3);
3518 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3519 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3520 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3521 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3522 check_spends!(revoked_htlc_txn[1], chan_1.3.clone());
3524 // B will generate justice tx from A's revoked commitment/HTLC tx
3525 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3526 check_closed_broadcast!(nodes[1]);
3528 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3529 assert_eq!(node_txn.len(), 4);
3530 assert_eq!(node_txn[3].input.len(), 1);
3531 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3533 // Check B's ChannelMonitor was able to generate the right spendable output descriptor
3534 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3535 assert_eq!(spend_txn.len(), 3);
3536 assert_eq!(spend_txn[0], spend_txn[1]);
3537 check_spends!(spend_txn[0], node_txn[0].clone());
3538 check_spends!(spend_txn[2], node_txn[3].clone());
3542 fn test_static_spendable_outputs_justice_tx_revoked_htlc_success_tx() {
3543 let nodes = create_network(2);
3545 // Create some initial channels
3546 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3548 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 3000000).0;
3549 let revoked_local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3550 assert_eq!(revoked_local_txn[0].input.len(), 1);
3551 assert_eq!(revoked_local_txn[0].input[0].previous_output.txid, chan_1.3.txid());
3553 claim_payment(&nodes[0], &vec!(&nodes[1])[..], payment_preimage);
3555 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3556 // B will generate HTLC-Success from revoked commitment tx
3557 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone()] }, 1);
3558 check_closed_broadcast!(nodes[1]);
3559 let revoked_htlc_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3561 assert_eq!(revoked_htlc_txn.len(), 3);
3562 assert_eq!(revoked_htlc_txn[0], revoked_htlc_txn[2]);
3563 assert_eq!(revoked_htlc_txn[0].input.len(), 1);
3564 assert_eq!(revoked_htlc_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3565 check_spends!(revoked_htlc_txn[0], revoked_local_txn[0].clone());
3567 // A will generate justice tx from B's revoked commitment/HTLC tx
3568 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![revoked_local_txn[0].clone(), revoked_htlc_txn[0].clone()] }, 1);
3569 check_closed_broadcast!(nodes[0]);
3571 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
3572 assert_eq!(node_txn.len(), 4);
3573 assert_eq!(node_txn[3].input.len(), 1);
3574 check_spends!(node_txn[3], revoked_htlc_txn[0].clone());
3576 // Check A's ChannelMonitor was able to generate the right spendable output descriptor
3577 let spend_txn = check_spendable_outputs!(nodes[0], 1);
3578 assert_eq!(spend_txn.len(), 5);
3579 assert_eq!(spend_txn[0], spend_txn[2]);
3580 assert_eq!(spend_txn[1], spend_txn[3]);
3581 check_spends!(spend_txn[0], revoked_local_txn[0].clone()); // spending to_remote output from revoked local tx
3582 check_spends!(spend_txn[1], node_txn[2].clone()); // spending justice tx output from revoked local tx htlc received output
3583 check_spends!(spend_txn[4], node_txn[3].clone()); // spending justice tx output on htlc success tx
3587 fn test_onchain_to_onchain_claim() {
3588 // Test that in case of channel closure, we detect the state of output thanks to
3589 // ChainWatchInterface and claim HTLC on downstream peer's remote commitment tx.
3590 // First, have C claim an HTLC against its own latest commitment transaction.
3591 // Then, broadcast these to B, which should update the monitor downstream on the A<->B
3593 // Finally, check that B will claim the HTLC output if A's latest commitment transaction
3596 let nodes = create_network(3);
3598 // Create some initial channels
3599 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3600 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3602 // Rebalance the network a bit by relaying one payment through all the channels ...
3603 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3604 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 8000000);
3606 let (payment_preimage, _payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2]), 3000000);
3607 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42};
3608 let commitment_tx = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3609 check_spends!(commitment_tx[0], chan_2.3.clone());
3610 nodes[2].node.claim_funds(payment_preimage);
3611 check_added_monitors!(nodes[2], 1);
3612 let updates = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
3613 assert!(updates.update_add_htlcs.is_empty());
3614 assert!(updates.update_fail_htlcs.is_empty());
3615 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3616 assert!(updates.update_fail_malformed_htlcs.is_empty());
3618 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3619 check_closed_broadcast!(nodes[2]);
3621 let c_txn = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone(); // ChannelManager : 2 (commitment tx, HTLC-Success tx), ChannelMonitor : 1 (HTLC-Success tx)
3622 assert_eq!(c_txn.len(), 3);
3623 assert_eq!(c_txn[0], c_txn[2]);
3624 assert_eq!(commitment_tx[0], c_txn[1]);
3625 check_spends!(c_txn[1], chan_2.3.clone());
3626 check_spends!(c_txn[2], c_txn[1].clone());
3627 assert_eq!(c_txn[1].input[0].witness.clone().last().unwrap().len(), 71);
3628 assert_eq!(c_txn[2].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3629 assert!(c_txn[0].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3630 assert_eq!(c_txn[0].lock_time, 0); // Success tx
3632 // 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
3633 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![c_txn[1].clone(), c_txn[2].clone()]}, 1);
3635 let mut b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3636 assert_eq!(b_txn.len(), 4);
3637 assert_eq!(b_txn[0], b_txn[3]);
3638 check_spends!(b_txn[1], chan_2.3); // B local commitment tx, issued by ChannelManager
3639 check_spends!(b_txn[2], b_txn[1].clone()); // HTLC-Timeout on B local commitment tx, issued by ChannelManager
3640 assert_eq!(b_txn[2].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3641 assert!(b_txn[2].output[0].script_pubkey.is_v0_p2wsh()); // revokeable output
3642 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3643 check_spends!(b_txn[0], c_txn[1].clone()); // timeout tx on C remote commitment tx, issued by ChannelMonitor, * 2 due to block rescan
3644 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3645 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3646 assert_ne!(b_txn[2].lock_time, 0); // Timeout tx
3649 let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
3650 check_added_monitors!(nodes[1], 1);
3651 match msg_events[0] {
3652 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3653 _ => panic!("Unexpected event"),
3655 match msg_events[1] {
3656 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, .. } } => {
3657 assert!(update_add_htlcs.is_empty());
3658 assert!(update_fail_htlcs.is_empty());
3659 assert_eq!(update_fulfill_htlcs.len(), 1);
3660 assert!(update_fail_malformed_htlcs.is_empty());
3661 assert_eq!(nodes[0].node.get_our_node_id(), *node_id);
3663 _ => panic!("Unexpected event"),
3665 // Broadcast A's commitment tx on B's chain to see if we are able to claim inbound HTLC with our HTLC-Success tx
3666 let commitment_tx = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3667 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_tx[0].clone()]}, 1);
3668 let b_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3669 assert_eq!(b_txn.len(), 3);
3670 check_spends!(b_txn[1], chan_1.3); // Local commitment tx, issued by ChannelManager
3671 assert_eq!(b_txn[0], b_txn[2]); // HTLC-Success tx, issued by ChannelMonitor, * 2 due to block rescan
3672 check_spends!(b_txn[0], commitment_tx[0].clone());
3673 assert_eq!(b_txn[0].input[0].witness.clone().last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
3674 assert!(b_txn[0].output[0].script_pubkey.is_v0_p2wpkh()); // direct payment
3675 assert_eq!(b_txn[2].lock_time, 0); // Success tx
3677 check_closed_broadcast!(nodes[1]);
3681 fn test_duplicate_payment_hash_one_failure_one_success() {
3682 // Topology : A --> B --> C
3683 // We route 2 payments with same hash between B and C, one will be timeout, the other successfully claim
3684 let mut nodes = create_network(3);
3686 create_announced_chan_between_nodes(&nodes, 0, 1);
3687 let chan_2 = create_announced_chan_between_nodes(&nodes, 1, 2);
3689 let (our_payment_preimage, duplicate_payment_hash) = route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000);
3690 *nodes[0].network_payment_count.borrow_mut() -= 1;
3691 assert_eq!(route_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 900000).1, duplicate_payment_hash);
3693 let commitment_txn = nodes[2].node.channel_state.lock().unwrap().by_id.get(&chan_2.2).unwrap().last_local_commitment_txn.clone();
3694 assert_eq!(commitment_txn[0].input.len(), 1);
3695 check_spends!(commitment_txn[0], chan_2.3.clone());
3697 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3698 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
3699 check_closed_broadcast!(nodes[1]);
3701 let htlc_timeout_tx;
3702 { // Extract one of the two HTLC-Timeout transaction
3703 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3704 assert_eq!(node_txn.len(), 7);
3705 assert_eq!(node_txn[0], node_txn[5]);
3706 assert_eq!(node_txn[1], node_txn[6]);
3707 check_spends!(node_txn[0], commitment_txn[0].clone());
3708 assert_eq!(node_txn[0].input.len(), 1);
3709 check_spends!(node_txn[1], commitment_txn[0].clone());
3710 assert_eq!(node_txn[1].input.len(), 1);
3711 assert_ne!(node_txn[0].input[0], node_txn[1].input[0]);
3712 check_spends!(node_txn[2], chan_2.3.clone());
3713 check_spends!(node_txn[3], node_txn[2].clone());
3714 check_spends!(node_txn[4], node_txn[2].clone());
3715 htlc_timeout_tx = node_txn[1].clone();
3718 nodes[2].node.claim_funds(our_payment_preimage);
3719 nodes[2].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![commitment_txn[0].clone()] }, 1);
3720 check_added_monitors!(nodes[2], 2);
3721 let events = nodes[2].node.get_and_clear_pending_msg_events();
3723 MessageSendEvent::UpdateHTLCs { .. } => {},
3724 _ => panic!("Unexpected event"),
3727 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3728 _ => panic!("Unexepected event"),
3730 let htlc_success_txn: Vec<_> = nodes[2].tx_broadcaster.txn_broadcasted.lock().unwrap().clone();
3731 assert_eq!(htlc_success_txn.len(), 5);
3732 check_spends!(htlc_success_txn[2], chan_2.3.clone());
3733 assert_eq!(htlc_success_txn[0], htlc_success_txn[3]);
3734 assert_eq!(htlc_success_txn[0].input.len(), 1);
3735 assert_eq!(htlc_success_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3736 assert_eq!(htlc_success_txn[1], htlc_success_txn[4]);
3737 assert_eq!(htlc_success_txn[1].input.len(), 1);
3738 assert_eq!(htlc_success_txn[1].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3739 assert_ne!(htlc_success_txn[0].input[0], htlc_success_txn[1].input[0]);
3740 check_spends!(htlc_success_txn[0], commitment_txn[0].clone());
3741 check_spends!(htlc_success_txn[1], commitment_txn[0].clone());
3743 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_timeout_tx] }, 200);
3744 expect_pending_htlcs_forwardable!(nodes[1]);
3745 let htlc_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3746 assert!(htlc_updates.update_add_htlcs.is_empty());
3747 assert_eq!(htlc_updates.update_fail_htlcs.len(), 1);
3748 assert_eq!(htlc_updates.update_fail_htlcs[0].htlc_id, 1);
3749 assert!(htlc_updates.update_fulfill_htlcs.is_empty());
3750 assert!(htlc_updates.update_fail_malformed_htlcs.is_empty());
3751 check_added_monitors!(nodes[1], 1);
3753 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &htlc_updates.update_fail_htlcs[0]).unwrap();
3754 assert!(nodes[0].node.get_and_clear_pending_msg_events().is_empty());
3756 commitment_signed_dance!(nodes[0], nodes[1], &htlc_updates.commitment_signed, false, true);
3757 let events = nodes[0].node.get_and_clear_pending_msg_events();
3758 assert_eq!(events.len(), 1);
3760 MessageSendEvent::PaymentFailureNetworkUpdate { update: msgs::HTLCFailChannelUpdate::ChannelClosed { .. } } => {
3762 _ => { panic!("Unexpected event"); }
3765 let events = nodes[0].node.get_and_clear_pending_events();
3767 Event::PaymentFailed { ref payment_hash, .. } => {
3768 assert_eq!(*payment_hash, duplicate_payment_hash);
3770 _ => panic!("Unexpected event"),
3773 // Solve 2nd HTLC by broadcasting on B's chain HTLC-Success Tx from C
3774 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![htlc_success_txn[0].clone()] }, 200);
3775 let updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
3776 assert!(updates.update_add_htlcs.is_empty());
3777 assert!(updates.update_fail_htlcs.is_empty());
3778 assert_eq!(updates.update_fulfill_htlcs.len(), 1);
3779 assert_eq!(updates.update_fulfill_htlcs[0].htlc_id, 0);
3780 assert!(updates.update_fail_malformed_htlcs.is_empty());
3781 check_added_monitors!(nodes[1], 1);
3783 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &updates.update_fulfill_htlcs[0]).unwrap();
3784 commitment_signed_dance!(nodes[0], nodes[1], &updates.commitment_signed, false);
3786 let events = nodes[0].node.get_and_clear_pending_events();
3788 Event::PaymentSent { ref payment_preimage } => {
3789 assert_eq!(*payment_preimage, our_payment_preimage);
3791 _ => panic!("Unexpected event"),
3796 fn test_dynamic_spendable_outputs_local_htlc_success_tx() {
3797 let nodes = create_network(2);
3799 // Create some initial channels
3800 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
3802 let payment_preimage = route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
3803 let local_txn = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
3804 assert_eq!(local_txn[0].input.len(), 1);
3805 check_spends!(local_txn[0], chan_1.3.clone());
3807 // Give B knowledge of preimage to be able to generate a local HTLC-Success Tx
3808 nodes[1].node.claim_funds(payment_preimage);
3809 check_added_monitors!(nodes[1], 1);
3810 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3811 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 1);
3812 let events = nodes[1].node.get_and_clear_pending_msg_events();
3814 MessageSendEvent::UpdateHTLCs { .. } => {},
3815 _ => panic!("Unexpected event"),
3818 MessageSendEvent::BroadcastChannelUpdate { .. } => {},
3819 _ => panic!("Unexepected event"),
3821 let node_txn = nodes[1].tx_broadcaster.txn_broadcasted.lock().unwrap();
3822 assert_eq!(node_txn[0].input.len(), 1);
3823 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), ACCEPTED_HTLC_SCRIPT_WEIGHT);
3824 check_spends!(node_txn[0], local_txn[0].clone());
3826 // Verify that B is able to spend its own HTLC-Success tx thanks to spendable output event given back by its ChannelMonitor
3827 let spend_txn = check_spendable_outputs!(nodes[1], 1);
3828 assert_eq!(spend_txn.len(), 2);
3829 check_spends!(spend_txn[0], node_txn[0].clone());
3830 check_spends!(spend_txn[1], node_txn[2].clone());
3833 fn do_test_fail_backwards_unrevoked_remote_announce(deliver_last_raa: bool, announce_latest: bool) {
3834 // Test that we fail backwards the full set of HTLCs we need to when remote broadcasts an
3835 // unrevoked commitment transaction.
3836 // This includes HTLCs which were below the dust threshold as well as HTLCs which were awaiting
3837 // a remote RAA before they could be failed backwards (and combinations thereof).
3838 // We also test duplicate-hash HTLCs by adding two nodes on each side of the target nodes which
3839 // use the same payment hashes.
3840 // Thus, we use a six-node network:
3845 // And test where C fails back to A/B when D announces its latest commitment transaction
3846 let nodes = create_network(6);
3848 create_announced_chan_between_nodes(&nodes, 0, 2);
3849 create_announced_chan_between_nodes(&nodes, 1, 2);
3850 let chan = create_announced_chan_between_nodes(&nodes, 2, 3);
3851 create_announced_chan_between_nodes(&nodes, 3, 4);
3852 create_announced_chan_between_nodes(&nodes, 3, 5);
3854 // Rebalance and check output sanity...
3855 send_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 500000);
3856 send_payment(&nodes[1], &[&nodes[2], &nodes[3], &nodes[5]], 500000);
3857 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 2);
3859 let ds_dust_limit = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().our_dust_limit_satoshis;
3861 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
3863 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
3864 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
3866 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
3868 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
3870 let (_, payment_hash_3) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
3872 let (_, payment_hash_4) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
3873 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3875 send_along_route_with_hash(&nodes[1], route.clone(), &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_3);
3877 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_4);
3880 let (_, payment_hash_5) = route_payment(&nodes[0], &[&nodes[2], &nodes[3], &nodes[4]], 1000000);
3882 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), ds_dust_limit*1000, TEST_FINAL_CLTV).unwrap();
3883 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
3886 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
3888 let route = nodes[1].router.get_route(&nodes[5].node.get_our_node_id(), None, &Vec::new(), 1000000, TEST_FINAL_CLTV).unwrap();
3889 send_along_route_with_hash(&nodes[1], route, &[&nodes[2], &nodes[3], &nodes[5]], 1000000, payment_hash_6);
3891 // Double-check that six of the new HTLC were added
3892 // We now have six HTLCs pending over the dust limit and six HTLCs under the dust limit (ie,
3893 // with to_local and to_remote outputs, 8 outputs and 6 HTLCs not included).
3894 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.len(), 1);
3895 assert_eq!(nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn[0].output.len(), 8);
3897 // Now fail back three of the over-dust-limit and three of the under-dust-limit payments in one go.
3898 // Fail 0th below-dust, 4th above-dust, 8th above-dust, 10th below-dust HTLCs
3899 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_1));
3900 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_3));
3901 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_5));
3902 assert!(nodes[4].node.fail_htlc_backwards(&payment_hash_6));
3903 check_added_monitors!(nodes[4], 0);
3904 expect_pending_htlcs_forwardable!(nodes[4]);
3905 check_added_monitors!(nodes[4], 1);
3907 let four_removes = get_htlc_update_msgs!(nodes[4], nodes[3].node.get_our_node_id());
3908 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[0]).unwrap();
3909 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[1]).unwrap();
3910 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[2]).unwrap();
3911 nodes[3].node.handle_update_fail_htlc(&nodes[4].node.get_our_node_id(), &four_removes.update_fail_htlcs[3]).unwrap();
3912 commitment_signed_dance!(nodes[3], nodes[4], four_removes.commitment_signed, false);
3914 // Fail 3rd below-dust and 7th above-dust HTLCs
3915 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_2));
3916 assert!(nodes[5].node.fail_htlc_backwards(&payment_hash_4));
3917 check_added_monitors!(nodes[5], 0);
3918 expect_pending_htlcs_forwardable!(nodes[5]);
3919 check_added_monitors!(nodes[5], 1);
3921 let two_removes = get_htlc_update_msgs!(nodes[5], nodes[3].node.get_our_node_id());
3922 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[0]).unwrap();
3923 nodes[3].node.handle_update_fail_htlc(&nodes[5].node.get_our_node_id(), &two_removes.update_fail_htlcs[1]).unwrap();
3924 commitment_signed_dance!(nodes[3], nodes[5], two_removes.commitment_signed, false);
3926 let ds_prev_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
3928 expect_pending_htlcs_forwardable!(nodes[3]);
3929 check_added_monitors!(nodes[3], 1);
3930 let six_removes = get_htlc_update_msgs!(nodes[3], nodes[2].node.get_our_node_id());
3931 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[0]).unwrap();
3932 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[1]).unwrap();
3933 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[2]).unwrap();
3934 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[3]).unwrap();
3935 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[4]).unwrap();
3936 nodes[2].node.handle_update_fail_htlc(&nodes[3].node.get_our_node_id(), &six_removes.update_fail_htlcs[5]).unwrap();
3937 if deliver_last_raa {
3938 commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false);
3940 let _cs_last_raa = commitment_signed_dance!(nodes[2], nodes[3], six_removes.commitment_signed, false, true, false, true);
3943 // D's latest commitment transaction now contains 1st + 2nd + 9th HTLCs (implicitly, they're
3944 // below the dust limit) and the 5th + 6th + 11th HTLCs. It has failed back the 0th, 3rd, 4th,
3945 // 7th, 8th, and 10th, but as we haven't yet delivered the final RAA to C, the fails haven't
3946 // propagated back to A/B yet (and D has two unrevoked commitment transactions).
3948 // We now broadcast the latest commitment transaction, which *should* result in failures for
3949 // the 0th, 1st, 2nd, 3rd, 4th, 7th, 8th, 9th, and 10th HTLCs, ie all the below-dust HTLCs and
3950 // the non-broadcast above-dust HTLCs.
3952 // Alternatively, we may broadcast the previous commitment transaction, which should only
3953 // result in failures for the below-dust HTLCs, ie the 0th, 1st, 2nd, 3rd, 9th, and 10th HTLCs.
3954 let ds_last_commitment_tx = nodes[3].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().last_local_commitment_txn.clone();
3956 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
3957 if announce_latest {
3958 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_last_commitment_tx[0]], &[1; 1]);
3960 nodes[2].chain_monitor.block_connected_checked(&header, 1, &[&ds_prev_commitment_tx[0]], &[1; 1]);
3962 check_closed_broadcast!(nodes[2]);
3963 expect_pending_htlcs_forwardable!(nodes[2]);
3964 check_added_monitors!(nodes[2], 2);
3966 let cs_msgs = nodes[2].node.get_and_clear_pending_msg_events();
3967 assert_eq!(cs_msgs.len(), 2);
3968 let mut a_done = false;
3969 for msg in cs_msgs {
3971 MessageSendEvent::UpdateHTLCs { ref node_id, ref updates } => {
3972 // Both under-dust HTLCs and the one above-dust HTLC that we had already failed
3973 // should be failed-backwards here.
3974 let target = if *node_id == nodes[0].node.get_our_node_id() {
3975 // If announce_latest, expect 0th, 1st, 4th, 8th, 10th HTLCs, else only 0th, 1st, 10th below-dust HTLCs
3976 for htlc in &updates.update_fail_htlcs {
3977 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 });
3979 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 5 } else { 3 });
3984 // If announce_latest, expect 2nd, 3rd, 7th, 9th HTLCs, else only 2nd, 3rd, 9th below-dust HTLCs
3985 for htlc in &updates.update_fail_htlcs {
3986 assert!(htlc.htlc_id == 1 || htlc.htlc_id == 2 || htlc.htlc_id == 5 || if announce_latest { htlc.htlc_id == 4 } else { false });
3988 assert_eq!(*node_id, nodes[1].node.get_our_node_id());
3989 assert_eq!(updates.update_fail_htlcs.len(), if announce_latest { 4 } else { 3 });
3992 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[0]).unwrap();
3993 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[1]).unwrap();
3994 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[2]).unwrap();
3995 if announce_latest {
3996 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[3]).unwrap();
3997 if *node_id == nodes[0].node.get_our_node_id() {
3998 target.node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &updates.update_fail_htlcs[4]).unwrap();
4001 commitment_signed_dance!(target, nodes[2], updates.commitment_signed, false, true);
4003 _ => panic!("Unexpected event"),
4007 let as_events = nodes[0].node.get_and_clear_pending_events();
4008 assert_eq!(as_events.len(), if announce_latest { 5 } else { 3 });
4009 let mut as_failds = HashSet::new();
4010 for event in as_events.iter() {
4011 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4012 assert!(as_failds.insert(*payment_hash));
4013 if *payment_hash != payment_hash_2 {
4014 assert_eq!(*rejected_by_dest, deliver_last_raa);
4016 assert!(!rejected_by_dest);
4018 } else { panic!("Unexpected event"); }
4020 assert!(as_failds.contains(&payment_hash_1));
4021 assert!(as_failds.contains(&payment_hash_2));
4022 if announce_latest {
4023 assert!(as_failds.contains(&payment_hash_3));
4024 assert!(as_failds.contains(&payment_hash_5));
4026 assert!(as_failds.contains(&payment_hash_6));
4028 let bs_events = nodes[1].node.get_and_clear_pending_events();
4029 assert_eq!(bs_events.len(), if announce_latest { 4 } else { 3 });
4030 let mut bs_failds = HashSet::new();
4031 for event in bs_events.iter() {
4032 if let &Event::PaymentFailed { ref payment_hash, ref rejected_by_dest, .. } = event {
4033 assert!(bs_failds.insert(*payment_hash));
4034 if *payment_hash != payment_hash_1 && *payment_hash != payment_hash_5 {
4035 assert_eq!(*rejected_by_dest, deliver_last_raa);
4037 assert!(!rejected_by_dest);
4039 } else { panic!("Unexpected event"); }
4041 assert!(bs_failds.contains(&payment_hash_1));
4042 assert!(bs_failds.contains(&payment_hash_2));
4043 if announce_latest {
4044 assert!(bs_failds.contains(&payment_hash_4));
4046 assert!(bs_failds.contains(&payment_hash_5));
4048 // For each HTLC which was not failed-back by normal process (ie deliver_last_raa), we should
4049 // get a PaymentFailureNetworkUpdate. A should have gotten 4 HTLCs which were failed-back due
4050 // to unknown-preimage-etc, B should have gotten 2. Thus, in the
4051 // announce_latest && deliver_last_raa case, we should have 5-4=1 and 4-2=2
4052 // PaymentFailureNetworkUpdates.
4053 let as_msg_events = nodes[0].node.get_and_clear_pending_msg_events();
4054 assert_eq!(as_msg_events.len(), if deliver_last_raa { 1 } else if !announce_latest { 3 } else { 5 });
4055 let bs_msg_events = nodes[1].node.get_and_clear_pending_msg_events();
4056 assert_eq!(bs_msg_events.len(), if deliver_last_raa { 2 } else if !announce_latest { 3 } else { 4 });
4057 for event in as_msg_events.iter().chain(bs_msg_events.iter()) {
4059 &MessageSendEvent::PaymentFailureNetworkUpdate { .. } => {},
4060 _ => panic!("Unexpected event"),
4066 fn test_fail_backwards_latest_remote_announce_a() {
4067 do_test_fail_backwards_unrevoked_remote_announce(false, true);
4071 fn test_fail_backwards_latest_remote_announce_b() {
4072 do_test_fail_backwards_unrevoked_remote_announce(true, true);
4076 fn test_fail_backwards_previous_remote_announce() {
4077 do_test_fail_backwards_unrevoked_remote_announce(false, false);
4078 // Note that true, true doesn't make sense as it implies we announce a revoked state, which is
4079 // tested for in test_commitment_revoked_fail_backward_exhaustive()
4083 fn test_dynamic_spendable_outputs_local_htlc_timeout_tx() {
4084 let nodes = create_network(2);
4086 // Create some initial channels
4087 let chan_1 = create_announced_chan_between_nodes(&nodes, 0, 1);
4089 route_payment(&nodes[0], &vec!(&nodes[1])[..], 9000000).0;
4090 let local_txn = nodes[0].node.channel_state.lock().unwrap().by_id.get(&chan_1.2).unwrap().last_local_commitment_txn.clone();
4091 assert_eq!(local_txn[0].input.len(), 1);
4092 check_spends!(local_txn[0], chan_1.3.clone());
4094 // Timeout HTLC on A's chain and so it can generate a HTLC-Timeout tx
4095 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4096 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![local_txn[0].clone()] }, 200);
4097 check_closed_broadcast!(nodes[0]);
4099 let node_txn = nodes[0].tx_broadcaster.txn_broadcasted.lock().unwrap();
4100 assert_eq!(node_txn[0].input.len(), 1);
4101 assert_eq!(node_txn[0].input[0].witness.last().unwrap().len(), OFFERED_HTLC_SCRIPT_WEIGHT);
4102 check_spends!(node_txn[0], local_txn[0].clone());
4104 // Verify that A is able to spend its own HTLC-Timeout tx thanks to spendable output event given back by its ChannelMonitor
4105 let spend_txn = check_spendable_outputs!(nodes[0], 1);
4106 assert_eq!(spend_txn.len(), 8);
4107 assert_eq!(spend_txn[0], spend_txn[2]);
4108 assert_eq!(spend_txn[0], spend_txn[4]);
4109 assert_eq!(spend_txn[0], spend_txn[6]);
4110 assert_eq!(spend_txn[1], spend_txn[3]);
4111 assert_eq!(spend_txn[1], spend_txn[5]);
4112 assert_eq!(spend_txn[1], spend_txn[7]);
4113 check_spends!(spend_txn[0], local_txn[0].clone());
4114 check_spends!(spend_txn[1], node_txn[0].clone());
4118 fn test_static_output_closing_tx() {
4119 let nodes = create_network(2);
4121 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4123 send_payment(&nodes[0], &vec!(&nodes[1])[..], 8000000);
4124 let closing_tx = close_channel(&nodes[0], &nodes[1], &chan.2, chan.3, true).2;
4126 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4127 nodes[0].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4128 let spend_txn = check_spendable_outputs!(nodes[0], 2);
4129 assert_eq!(spend_txn.len(), 1);
4130 check_spends!(spend_txn[0], closing_tx.clone());
4132 nodes[1].chain_monitor.block_connected_with_filtering(&Block { header, txdata: vec![closing_tx.clone()] }, 1);
4133 let spend_txn = check_spendable_outputs!(nodes[1], 2);
4134 assert_eq!(spend_txn.len(), 1);
4135 check_spends!(spend_txn[0], closing_tx);
4138 fn do_htlc_claim_local_commitment_only(use_dust: bool) {
4139 let nodes = create_network(2);
4140 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4142 let (our_payment_preimage, _) = route_payment(&nodes[0], &[&nodes[1]], if use_dust { 50000 } else { 3000000 });
4144 // Claim the payment, but don't deliver A's commitment_signed, resulting in the HTLC only being
4145 // present in B's local commitment transaction, but none of A's commitment transactions.
4146 assert!(nodes[1].node.claim_funds(our_payment_preimage));
4147 check_added_monitors!(nodes[1], 1);
4149 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4150 nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fulfill_htlcs[0]).unwrap();
4151 let events = nodes[0].node.get_and_clear_pending_events();
4152 assert_eq!(events.len(), 1);
4154 Event::PaymentSent { payment_preimage } => {
4155 assert_eq!(payment_preimage, our_payment_preimage);
4157 _ => panic!("Unexpected event"),
4160 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4161 check_added_monitors!(nodes[0], 1);
4162 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4163 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4164 check_added_monitors!(nodes[1], 1);
4166 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4167 for i in 1..TEST_FINAL_CLTV - CLTV_CLAIM_BUFFER + CHAN_CONFIRM_DEPTH + 1 {
4168 nodes[1].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4169 header.prev_blockhash = header.bitcoin_hash();
4171 test_txn_broadcast(&nodes[1], &chan, None, if use_dust { HTLCType::NONE } else { HTLCType::SUCCESS });
4172 check_closed_broadcast!(nodes[1]);
4175 fn do_htlc_claim_current_remote_commitment_only(use_dust: bool) {
4176 let mut nodes = create_network(2);
4177 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4179 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &Vec::new(), if use_dust { 50000 } else { 3000000 }, TEST_FINAL_CLTV).unwrap();
4180 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4181 nodes[0].node.send_payment(route, payment_hash).unwrap();
4182 check_added_monitors!(nodes[0], 1);
4184 let _as_update = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4186 // As far as A is concerned, the HTLC is now present only in the latest remote commitment
4187 // transaction, however it is not in A's latest local commitment, so we can just broadcast that
4188 // to "time out" the HTLC.
4190 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4191 for i in 1..TEST_FINAL_CLTV + HTLC_FAIL_TIMEOUT_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4192 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4193 header.prev_blockhash = header.bitcoin_hash();
4195 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4196 check_closed_broadcast!(nodes[0]);
4199 fn do_htlc_claim_previous_remote_commitment_only(use_dust: bool, check_revoke_no_close: bool) {
4200 let nodes = create_network(3);
4201 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
4203 // Fail the payment, but don't deliver A's final RAA, resulting in the HTLC only being present
4204 // in B's previous (unrevoked) commitment transaction, but none of A's commitment transactions.
4205 // Also optionally test that we *don't* fail the channel in case the commitment transaction was
4206 // actually revoked.
4207 let htlc_value = if use_dust { 50000 } else { 3000000 };
4208 let (_, our_payment_hash) = route_payment(&nodes[0], &[&nodes[1]], htlc_value);
4209 assert!(nodes[1].node.fail_htlc_backwards(&our_payment_hash));
4210 expect_pending_htlcs_forwardable!(nodes[1]);
4211 check_added_monitors!(nodes[1], 1);
4213 let bs_updates = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4214 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_updates.update_fail_htlcs[0]).unwrap();
4215 nodes[0].node.handle_commitment_signed(&nodes[1].node.get_our_node_id(), &bs_updates.commitment_signed).unwrap();
4216 check_added_monitors!(nodes[0], 1);
4217 let as_updates = get_revoke_commit_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4218 nodes[1].node.handle_revoke_and_ack(&nodes[0].node.get_our_node_id(), &as_updates.0).unwrap();
4219 check_added_monitors!(nodes[1], 1);
4220 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &as_updates.1).unwrap();
4221 check_added_monitors!(nodes[1], 1);
4222 let bs_revoke_and_ack = get_event_msg!(nodes[1], MessageSendEvent::SendRevokeAndACK, nodes[0].node.get_our_node_id());
4224 if check_revoke_no_close {
4225 nodes[0].node.handle_revoke_and_ack(&nodes[1].node.get_our_node_id(), &bs_revoke_and_ack).unwrap();
4226 check_added_monitors!(nodes[0], 1);
4229 let mut header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4230 for i in 1..TEST_FINAL_CLTV + HTLC_FAIL_TIMEOUT_BLOCKS + CHAN_CONFIRM_DEPTH + 1 {
4231 nodes[0].chain_monitor.block_connected_checked(&header, i, &Vec::new(), &Vec::new());
4232 header.prev_blockhash = header.bitcoin_hash();
4234 if !check_revoke_no_close {
4235 test_txn_broadcast(&nodes[0], &chan, None, HTLCType::NONE);
4236 check_closed_broadcast!(nodes[0]);
4238 let events = nodes[0].node.get_and_clear_pending_events();
4239 assert_eq!(events.len(), 1);
4241 Event::PaymentFailed { payment_hash, rejected_by_dest, .. } => {
4242 assert_eq!(payment_hash, our_payment_hash);
4243 assert!(rejected_by_dest);
4245 _ => panic!("Unexpected event"),
4250 // Test that we close channels on-chain when broadcastable HTLCs reach their timeout window.
4251 // There are only a few cases to test here:
4252 // * its not really normative behavior, but we test that below-dust HTLCs "included" in
4253 // broadcastable commitment transactions result in channel closure,
4254 // * its included in an unrevoked-but-previous remote commitment transaction,
4255 // * its included in the latest remote or local commitment transactions.
4256 // We test each of the three possible commitment transactions individually and use both dust and
4258 // Note that we don't bother testing both outbound and inbound HTLC failures for each case, and we
4259 // assume they are handled the same across all six cases, as both outbound and inbound failures are
4260 // tested for at least one of the cases in other tests.
4262 fn htlc_claim_single_commitment_only_a() {
4263 do_htlc_claim_local_commitment_only(true);
4264 do_htlc_claim_local_commitment_only(false);
4266 do_htlc_claim_current_remote_commitment_only(true);
4267 do_htlc_claim_current_remote_commitment_only(false);
4271 fn htlc_claim_single_commitment_only_b() {
4272 do_htlc_claim_previous_remote_commitment_only(true, false);
4273 do_htlc_claim_previous_remote_commitment_only(false, false);
4274 do_htlc_claim_previous_remote_commitment_only(true, true);
4275 do_htlc_claim_previous_remote_commitment_only(false, true);
4278 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>)
4279 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4282 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);
4286 // 0: node1 fails backward
4287 // 1: final node fails backward
4288 // 2: payment completed but the user rejects the payment
4289 // 3: final node fails backward (but tamper onion payloads from node0)
4290 // 100: trigger error in the intermediate node and tamper returning fail_htlc
4291 // 200: trigger error in the final node and tamper returning fail_htlc
4292 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>)
4293 where F1: for <'a> FnMut(&'a mut msgs::UpdateAddHTLC),
4294 F2: for <'a> FnMut(&'a mut msgs::UpdateFailHTLC),
4297 use ln::msgs::HTLCFailChannelUpdate;
4299 // reset block height
4300 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4301 for ix in 0..nodes.len() {
4302 nodes[ix].chain_monitor.block_connected_checked(&header, 1, &Vec::new()[..], &[0; 0]);
4305 macro_rules! expect_event {
4306 ($node: expr, $event_type: path) => {{
4307 let events = $node.node.get_and_clear_pending_events();
4308 assert_eq!(events.len(), 1);
4310 $event_type { .. } => {},
4311 _ => panic!("Unexpected event"),
4316 macro_rules! expect_htlc_forward {
4318 expect_event!($node, Event::PendingHTLCsForwardable);
4319 $node.node.channel_state.lock().unwrap().next_forward = Instant::now();
4320 $node.node.process_pending_htlc_forwards();
4324 // 0 ~~> 2 send payment
4325 nodes[0].node.send_payment(route.clone(), payment_hash.clone()).unwrap();
4326 check_added_monitors!(nodes[0], 1);
4327 let update_0 = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4328 // temper update_add (0 => 1)
4329 let mut update_add_0 = update_0.update_add_htlcs[0].clone();
4330 if test_case == 0 || test_case == 3 || test_case == 100 {
4331 callback_msg(&mut update_add_0);
4334 // 0 => 1 update_add & CS
4335 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &update_add_0).unwrap();
4336 commitment_signed_dance!(nodes[1], nodes[0], &update_0.commitment_signed, false, true);
4338 let update_1_0 = match test_case {
4339 0|100 => { // intermediate node failure; fail backward to 0
4340 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4341 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));
4344 1|2|3|200 => { // final node failure; forwarding to 2
4345 assert!(nodes[1].node.get_and_clear_pending_msg_events().is_empty());
4347 if test_case != 200 {
4350 expect_htlc_forward!(&nodes[1]);
4352 let update_1 = get_htlc_update_msgs!(nodes[1], nodes[2].node.get_our_node_id());
4353 check_added_monitors!(&nodes[1], 1);
4354 assert_eq!(update_1.update_add_htlcs.len(), 1);
4355 // tamper update_add (1 => 2)
4356 let mut update_add_1 = update_1.update_add_htlcs[0].clone();
4357 if test_case != 3 && test_case != 200 {
4358 callback_msg(&mut update_add_1);
4362 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &update_add_1).unwrap();
4363 commitment_signed_dance!(nodes[2], nodes[1], update_1.commitment_signed, false, true);
4365 if test_case == 2 || test_case == 200 {
4366 expect_htlc_forward!(&nodes[2]);
4367 expect_event!(&nodes[2], Event::PaymentReceived);
4369 expect_pending_htlcs_forwardable!(nodes[2]);
4372 let update_2_1 = get_htlc_update_msgs!(nodes[2], nodes[1].node.get_our_node_id());
4373 if test_case == 2 || test_case == 200 {
4374 check_added_monitors!(&nodes[2], 1);
4376 assert!(update_2_1.update_fail_htlcs.len() == 1);
4378 let mut fail_msg = update_2_1.update_fail_htlcs[0].clone();
4379 if test_case == 200 {
4380 callback_fail(&mut fail_msg);
4384 nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &fail_msg).unwrap();
4385 commitment_signed_dance!(nodes[1], nodes[2], update_2_1.commitment_signed, true);
4387 // backward fail on 1
4388 let update_1_0 = get_htlc_update_msgs!(nodes[1], nodes[0].node.get_our_node_id());
4389 assert!(update_1_0.update_fail_htlcs.len() == 1);
4392 _ => unreachable!(),
4395 // 1 => 0 commitment_signed_dance
4396 if update_1_0.update_fail_htlcs.len() > 0 {
4397 let mut fail_msg = update_1_0.update_fail_htlcs[0].clone();
4398 if test_case == 100 {
4399 callback_fail(&mut fail_msg);
4401 nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &fail_msg).unwrap();
4403 nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_1_0.update_fail_malformed_htlcs[0]).unwrap();
4406 commitment_signed_dance!(nodes[0], nodes[1], update_1_0.commitment_signed, false, true);
4408 let events = nodes[0].node.get_and_clear_pending_events();
4409 assert_eq!(events.len(), 1);
4410 if let &Event::PaymentFailed { payment_hash:_, ref rejected_by_dest, ref error_code } = &events[0] {
4411 assert_eq!(*rejected_by_dest, !expected_retryable);
4412 assert_eq!(*error_code, expected_error_code);
4414 panic!("Uexpected event");
4417 let events = nodes[0].node.get_and_clear_pending_msg_events();
4418 if expected_channel_update.is_some() {
4419 assert_eq!(events.len(), 1);
4421 MessageSendEvent::PaymentFailureNetworkUpdate { ref update } => {
4423 &HTLCFailChannelUpdate::ChannelUpdateMessage { .. } => {
4424 if let HTLCFailChannelUpdate::ChannelUpdateMessage { .. } = expected_channel_update.unwrap() {} else {
4425 panic!("channel_update not found!");
4428 &HTLCFailChannelUpdate::ChannelClosed { ref short_channel_id, ref is_permanent } => {
4429 if let HTLCFailChannelUpdate::ChannelClosed { short_channel_id: ref expected_short_channel_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4430 assert!(*short_channel_id == *expected_short_channel_id);
4431 assert!(*is_permanent == *expected_is_permanent);
4433 panic!("Unexpected message event");
4436 &HTLCFailChannelUpdate::NodeFailure { ref node_id, ref is_permanent } => {
4437 if let HTLCFailChannelUpdate::NodeFailure { node_id: ref expected_node_id, is_permanent: ref expected_is_permanent } = expected_channel_update.unwrap() {
4438 assert!(*node_id == *expected_node_id);
4439 assert!(*is_permanent == *expected_is_permanent);
4441 panic!("Unexpected message event");
4446 _ => panic!("Unexpected message event"),
4449 assert_eq!(events.len(), 0);
4453 impl msgs::ChannelUpdate {
4454 fn dummy() -> msgs::ChannelUpdate {
4455 use secp256k1::ffi::Signature as FFISignature;
4456 use secp256k1::Signature;
4457 msgs::ChannelUpdate {
4458 signature: Signature::from(FFISignature::new()),
4459 contents: msgs::UnsignedChannelUpdate {
4460 chain_hash: Sha256dHash::hash(&vec![0u8][..]),
4461 short_channel_id: 0,
4464 cltv_expiry_delta: 0,
4465 htlc_minimum_msat: 0,
4467 fee_proportional_millionths: 0,
4468 excess_data: vec![],
4475 fn test_onion_failure() {
4476 use ln::msgs::ChannelUpdate;
4477 use ln::channelmanager::CLTV_FAR_FAR_AWAY;
4480 const BADONION: u16 = 0x8000;
4481 const PERM: u16 = 0x4000;
4482 const NODE: u16 = 0x2000;
4483 const UPDATE: u16 = 0x1000;
4485 let mut nodes = create_network(3);
4486 for node in nodes.iter() {
4487 *node.keys_manager.override_session_priv.lock().unwrap() = Some(SecretKey::from_slice(&[3; 32]).unwrap());
4489 let channels = [create_announced_chan_between_nodes(&nodes, 0, 1), create_announced_chan_between_nodes(&nodes, 1, 2)];
4490 let (_, payment_hash) = get_payment_preimage_hash!(nodes[0]);
4491 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 40000, TEST_FINAL_CLTV).unwrap();
4493 send_payment(&nodes[0], &vec!(&nodes[1], &nodes[2])[..], 40000);
4495 // intermediate node failure
4496 run_onion_failure_test("invalid_realm", 0, &nodes, &route, &payment_hash, |msg| {
4497 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4498 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4499 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4500 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4501 onion_payloads[0].realm = 3;
4502 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4503 }, ||{}, true, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));//XXX incremented channels idx here
4505 // final node failure
4506 run_onion_failure_test("invalid_realm", 3, &nodes, &route, &payment_hash, |msg| {
4507 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4508 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4509 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4510 let (mut onion_payloads, _htlc_msat, _htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4511 onion_payloads[1].realm = 3;
4512 msg.onion_routing_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4513 }, ||{}, false, Some(PERM|1), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4515 // the following three with run_onion_failure_test_with_fail_intercept() test only the origin node
4516 // receiving simulated fail messages
4517 // intermediate node failure
4518 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4520 msg.amount_msat -= 1;
4522 // and tamper returning error message
4523 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4524 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4525 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], NODE|2, &[0;0]);
4526 }, ||{}, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: false}));
4528 // final node failure
4529 run_onion_failure_test_with_fail_intercept("temporary_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4530 // and tamper returning error message
4531 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4532 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4533 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], NODE|2, &[0;0]);
4535 nodes[2].node.fail_htlc_backwards(&payment_hash);
4536 }, true, Some(NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: false}));
4538 // intermediate node failure
4539 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 100, &nodes, &route, &payment_hash, |msg| {
4540 msg.amount_msat -= 1;
4542 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4543 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4544 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|2, &[0;0]);
4545 }, ||{}, true, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4547 // final node failure
4548 run_onion_failure_test_with_fail_intercept("permanent_node_failure", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4549 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4550 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4551 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|2, &[0;0]);
4553 nodes[2].node.fail_htlc_backwards(&payment_hash);
4554 }, false, Some(PERM|NODE|2), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4556 // intermediate node failure
4557 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4558 msg.amount_msat -= 1;
4560 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4561 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4562 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|NODE|3, &[0;0]);
4564 nodes[2].node.fail_htlc_backwards(&payment_hash);
4565 }, true, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[0].pubkey, is_permanent: true}));
4567 // final node failure
4568 run_onion_failure_test_with_fail_intercept("required_node_feature_missing", 200, &nodes, &route, &payment_hash, |_msg| {}, |msg| {
4569 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4570 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4571 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[1].shared_secret[..], PERM|NODE|3, &[0;0]);
4573 nodes[2].node.fail_htlc_backwards(&payment_hash);
4574 }, false, Some(PERM|NODE|3), Some(msgs::HTLCFailChannelUpdate::NodeFailure{node_id: route.hops[1].pubkey, is_permanent: true}));
4576 run_onion_failure_test("invalid_onion_version", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.version = 1; }, ||{}, true,
4577 Some(BADONION|PERM|4), None);
4579 run_onion_failure_test("invalid_onion_hmac", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.hmac = [3; 32]; }, ||{}, true,
4580 Some(BADONION|PERM|5), None);
4582 run_onion_failure_test("invalid_onion_key", 0, &nodes, &route, &payment_hash, |msg| { msg.onion_routing_packet.public_key = Err(secp256k1::Error::InvalidPublicKey);}, ||{}, true,
4583 Some(BADONION|PERM|6), None);
4585 run_onion_failure_test_with_fail_intercept("temporary_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4586 msg.amount_msat -= 1;
4588 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4589 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4590 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], UPDATE|7, &ChannelUpdate::dummy().encode_with_len()[..]);
4591 }, ||{}, true, Some(UPDATE|7), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4593 run_onion_failure_test_with_fail_intercept("permanent_channel_failure", 100, &nodes, &route, &payment_hash, |msg| {
4594 msg.amount_msat -= 1;
4596 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4597 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4598 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|8, &[0;0]);
4599 // short_channel_id from the processing node
4600 }, ||{}, true, Some(PERM|8), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4602 run_onion_failure_test_with_fail_intercept("required_channel_feature_missing", 100, &nodes, &route, &payment_hash, |msg| {
4603 msg.amount_msat -= 1;
4605 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4606 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4607 msg.reason = onion_utils::build_first_hop_failure_packet(&onion_keys[0].shared_secret[..], PERM|9, &[0;0]);
4608 // short_channel_id from the processing node
4609 }, ||{}, true, Some(PERM|9), Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: channels[1].0.contents.short_channel_id, is_permanent: true}));
4611 let mut bogus_route = route.clone();
4612 bogus_route.hops[1].short_channel_id -= 1;
4613 run_onion_failure_test("unknown_next_peer", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(PERM|10),
4614 Some(msgs::HTLCFailChannelUpdate::ChannelClosed{short_channel_id: bogus_route.hops[1].short_channel_id, is_permanent:true}));
4616 let amt_to_forward = nodes[1].node.channel_state.lock().unwrap().by_id.get(&channels[1].2).unwrap().get_their_htlc_minimum_msat() - 1;
4617 let mut bogus_route = route.clone();
4618 let route_len = bogus_route.hops.len();
4619 bogus_route.hops[route_len-1].fee_msat = amt_to_forward;
4620 run_onion_failure_test("amount_below_minimum", 0, &nodes, &bogus_route, &payment_hash, |_| {}, ||{}, true, Some(UPDATE|11), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4622 //TODO: with new config API, we will be able to generate both valid and
4623 //invalid channel_update cases.
4624 run_onion_failure_test("fee_insufficient", 0, &nodes, &route, &payment_hash, |msg| {
4625 msg.amount_msat -= 1;
4626 }, || {}, true, Some(UPDATE|12), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4628 run_onion_failure_test("incorrect_cltv_expiry", 0, &nodes, &route, &payment_hash, |msg| {
4629 // need to violate: cltv_expiry - cltv_expiry_delta >= outgoing_cltv_value
4630 msg.cltv_expiry -= 1;
4631 }, || {}, true, Some(UPDATE|13), Some(msgs::HTLCFailChannelUpdate::ChannelClosed { short_channel_id: channels[0].0.contents.short_channel_id, is_permanent: true}));
4633 run_onion_failure_test("expiry_too_soon", 0, &nodes, &route, &payment_hash, |msg| {
4634 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
4635 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4636 nodes[1].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
4637 }, ||{}, true, Some(UPDATE|14), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4639 run_onion_failure_test("unknown_payment_hash", 2, &nodes, &route, &payment_hash, |_| {}, || {
4640 nodes[2].node.fail_htlc_backwards(&payment_hash);
4641 }, false, Some(PERM|15), None);
4643 run_onion_failure_test("final_expiry_too_soon", 1, &nodes, &route, &payment_hash, |msg| {
4644 let height = msg.cltv_expiry - CLTV_CLAIM_BUFFER - HTLC_FAIL_TIMEOUT_BLOCKS + 1;
4645 let header = BlockHeader { version: 0x20000000, prev_blockhash: Default::default(), merkle_root: Default::default(), time: 42, bits: 42, nonce: 42 };
4646 nodes[2].chain_monitor.block_connected_checked(&header, height, &Vec::new()[..], &[0; 0]);
4647 }, || {}, true, Some(17), None);
4649 run_onion_failure_test("final_incorrect_cltv_expiry", 1, &nodes, &route, &payment_hash, |_| {}, || {
4650 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4651 for f in pending_forwards.iter_mut() {
4653 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4654 forward_info.outgoing_cltv_value += 1,
4659 }, true, Some(18), None);
4661 run_onion_failure_test("final_incorrect_htlc_amount", 1, &nodes, &route, &payment_hash, |_| {}, || {
4662 // violate amt_to_forward > msg.amount_msat
4663 for (_, pending_forwards) in nodes[1].node.channel_state.lock().unwrap().borrow_parts().forward_htlcs.iter_mut() {
4664 for f in pending_forwards.iter_mut() {
4666 &mut HTLCForwardInfo::AddHTLC { ref mut forward_info, .. } =>
4667 forward_info.amt_to_forward -= 1,
4672 }, true, Some(19), None);
4674 run_onion_failure_test("channel_disabled", 0, &nodes, &route, &payment_hash, |_| {}, || {
4675 // disconnect event to the channel between nodes[1] ~ nodes[2]
4676 nodes[1].node.peer_disconnected(&nodes[2].node.get_our_node_id(), false);
4677 nodes[2].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
4678 }, true, Some(UPDATE|20), Some(msgs::HTLCFailChannelUpdate::ChannelUpdateMessage{msg: ChannelUpdate::dummy()}));
4679 reconnect_nodes(&nodes[1], &nodes[2], (false, false), (0, 0), (0, 0), (0, 0), (0, 0), (false, false));
4681 run_onion_failure_test("expiry_too_far", 0, &nodes, &route, &payment_hash, |msg| {
4682 let session_priv = SecretKey::from_slice(&[3; 32]).unwrap();
4683 let mut route = route.clone();
4685 route.hops[1].cltv_expiry_delta += CLTV_FAR_FAR_AWAY + route.hops[0].cltv_expiry_delta + 1;
4686 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::new(), &route, &session_priv).unwrap();
4687 let (onion_payloads, _, htlc_cltv) = onion_utils::build_onion_payloads(&route, height).unwrap();
4688 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &payment_hash);
4689 msg.cltv_expiry = htlc_cltv;
4690 msg.onion_routing_packet = onion_packet;
4691 }, ||{}, true, Some(21), None);
4696 fn bolt2_open_channel_sending_node_checks_part1() { //This test needs to be on its own as we are catching a panic
4697 let nodes = create_network(2);
4698 //Force duplicate channel ids
4699 for node in nodes.iter() {
4700 *node.keys_manager.override_channel_id_priv.lock().unwrap() = Some([0; 32]);
4703 // BOLT #2 spec: Sending node must ensure temporary_channel_id is unique from any other channel ID with the same peer.
4704 let channel_value_satoshis=10000;
4705 let push_msat=10001;
4706 nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).unwrap();
4707 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
4708 nodes[1].node.handle_open_channel(&nodes[0].node.get_our_node_id(), &node0_to_1_send_open_channel).unwrap();
4710 //Create a second channel with a channel_id collision
4711 assert!(nodes[0].node.create_channel(nodes[0].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4715 fn bolt2_open_channel_sending_node_checks_part2() {
4716 let nodes = create_network(2);
4718 // BOLT #2 spec: Sending node must set funding_satoshis to less than 2^24 satoshis
4719 let channel_value_satoshis=2^24;
4720 let push_msat=10001;
4721 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4723 // BOLT #2 spec: Sending node must set push_msat to equal or less than 1000 * funding_satoshis
4724 let channel_value_satoshis=10000;
4725 // Test when push_msat is equal to 1000 * funding_satoshis.
4726 let push_msat=1000*channel_value_satoshis+1;
4727 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_err());
4729 // BOLT #2 spec: Sending node must set set channel_reserve_satoshis greater than or equal to dust_limit_satoshis
4730 let channel_value_satoshis=10000;
4731 let push_msat=10001;
4732 assert!(nodes[0].node.create_channel(nodes[1].node.get_our_node_id(), channel_value_satoshis, push_msat, 42).is_ok()); //Create a valid channel
4733 let node0_to_1_send_open_channel = get_event_msg!(nodes[0], MessageSendEvent::SendOpenChannel, nodes[1].node.get_our_node_id());
4734 assert!(node0_to_1_send_open_channel.channel_reserve_satoshis>=node0_to_1_send_open_channel.dust_limit_satoshis);
4736 // BOLT #2 spec: Sending node must set undefined bits in channel_flags to 0
4737 // 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
4738 assert!(node0_to_1_send_open_channel.channel_flags<=1);
4740 // 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.
4741 assert!(BREAKDOWN_TIMEOUT>0);
4742 assert!(node0_to_1_send_open_channel.to_self_delay==BREAKDOWN_TIMEOUT);
4744 // BOLT #2 spec: Sending node must ensure the chain_hash value identifies the chain it wishes to open the channel within.
4745 let chain_hash=genesis_block(Network::Testnet).header.bitcoin_hash();
4746 assert_eq!(node0_to_1_send_open_channel.chain_hash,chain_hash);
4748 // 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.
4749 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.funding_pubkey.serialize()).is_ok());
4750 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.revocation_basepoint.serialize()).is_ok());
4751 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.htlc_basepoint.serialize()).is_ok());
4752 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.payment_basepoint.serialize()).is_ok());
4753 assert!(PublicKey::from_slice(&node0_to_1_send_open_channel.delayed_payment_basepoint.serialize()).is_ok());
4756 // BOLT 2 Requirements for the Sender when constructing and sending an update_add_htlc message.
4757 // 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.
4758 //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.
4761 fn test_update_add_htlc_bolt2_sender_value_below_minimum_msat() {
4762 //BOLT2 Requirement: MUST offer amount_msat greater than 0.
4763 //BOLT2 Requirement: MUST NOT offer amount_msat below the receiving node's htlc_minimum_msat (same validation check catches both of these)
4764 let mut nodes = create_network(2);
4765 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
4766 let mut route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4767 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4769 route.hops[0].fee_msat = 0;
4771 let err = nodes[0].node.send_payment(route, our_payment_hash);
4773 if let Err(APIError::ChannelUnavailable{err}) = err {
4774 assert_eq!(err, "Cannot send less than their minimum HTLC value");
4781 fn test_update_add_htlc_bolt2_sender_cltv_expiry_too_high() {
4782 //BOLT 2 Requirement: MUST set cltv_expiry less than 500000000.
4783 //It is enforced when constructing a route.
4784 let mut nodes = create_network(2);
4785 let _chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 0);
4786 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000000, 500000001).unwrap();
4787 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4789 let err = nodes[0].node.send_payment(route, our_payment_hash);
4791 if let Err(APIError::RouteError{err}) = err {
4792 assert_eq!(err, "Channel CLTV overflowed?!");
4799 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_num_and_htlc_id_increment() {
4800 //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.
4801 //BOLT 2 Requirement: for the first HTLC it offers MUST set id to 0.
4802 //BOLT 2 Requirement: MUST increase the value of id by 1 for each successive offer.
4803 let mut nodes = create_network(2);
4804 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 0);
4805 let max_accepted_htlcs = nodes[1].node.channel_state.lock().unwrap().by_id.get(&chan.2).unwrap().their_max_accepted_htlcs as u64;
4807 for i in 0..max_accepted_htlcs {
4808 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4809 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4810 let payment_event = {
4811 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4812 check_added_monitors!(nodes[0], 1);
4814 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
4815 assert_eq!(events.len(), 1);
4816 if let MessageSendEvent::UpdateHTLCs { node_id: _, updates: msgs::CommitmentUpdate{ update_add_htlcs: ref htlcs, .. }, } = events[0] {
4817 assert_eq!(htlcs[0].htlc_id, i);
4821 SendEvent::from_event(events.remove(0))
4823 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
4824 check_added_monitors!(nodes[1], 0);
4825 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
4827 expect_pending_htlcs_forwardable!(nodes[1]);
4828 expect_payment_received!(nodes[1], our_payment_hash, 100000);
4830 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 100000, TEST_FINAL_CLTV).unwrap();
4831 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4832 let err = nodes[0].node.send_payment(route, our_payment_hash);
4834 if let Err(APIError::ChannelUnavailable{err}) = err {
4835 assert_eq!(err, "Cannot push more than their max accepted HTLCs");
4842 fn test_update_add_htlc_bolt2_sender_exceed_max_htlc_value_in_flight() {
4843 //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.
4844 let mut nodes = create_network(2);
4845 let channel_value = 100000;
4846 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, channel_value, 0);
4847 let max_in_flight = get_channel_value_stat!(nodes[0], chan.2).their_max_htlc_value_in_flight_msat;
4849 send_payment(&nodes[0], &vec!(&nodes[1])[..], max_in_flight);
4851 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], max_in_flight+1, TEST_FINAL_CLTV).unwrap();
4852 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4853 let err = nodes[0].node.send_payment(route, our_payment_hash);
4855 if let Err(APIError::ChannelUnavailable{err}) = err {
4856 assert_eq!(err, "Cannot send value that would put us over the max HTLC value in flight");
4861 send_payment(&nodes[0], &[&nodes[1]], max_in_flight);
4864 // BOLT 2 Requirements for the Receiver when handling an update_add_htlc message.
4866 fn test_update_add_htlc_bolt2_receiver_check_amount_received_more_than_min() {
4867 //BOLT2 Requirement: receiving an amount_msat equal to 0, OR less than its own htlc_minimum_msat -> SHOULD fail the channel.
4868 let mut nodes = create_network(2);
4869 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
4870 let htlc_minimum_msat: u64;
4872 let chan_lock = nodes[0].node.channel_state.lock().unwrap();
4873 let channel = chan_lock.by_id.get(&chan.2).unwrap();
4874 htlc_minimum_msat = channel.get_our_htlc_minimum_msat();
4876 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], htlc_minimum_msat, TEST_FINAL_CLTV).unwrap();
4877 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4878 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4879 check_added_monitors!(nodes[0], 1);
4880 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4881 updates.update_add_htlcs[0].amount_msat = htlc_minimum_msat-1;
4882 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
4883 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
4884 assert_eq!(err, "Remote side tried to send less than our minimum HTLC value");
4888 assert!(nodes[1].node.list_channels().is_empty());
4889 check_closed_broadcast!(nodes[1]);
4893 fn test_update_add_htlc_bolt2_receiver_sender_can_afford_amount_sent() {
4894 //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
4895 let mut nodes = create_network(2);
4896 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
4898 let their_channel_reserve = get_channel_value_stat!(nodes[0], chan.2).channel_reserve_msat;
4900 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 5000000-their_channel_reserve, TEST_FINAL_CLTV).unwrap();
4901 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4902 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4903 check_added_monitors!(nodes[0], 1);
4904 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4906 updates.update_add_htlcs[0].amount_msat = 5000000-their_channel_reserve+1;
4907 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
4909 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
4910 assert_eq!(err, "Remote HTLC add would put them over their reserve value");
4915 assert!(nodes[1].node.list_channels().is_empty());
4916 check_closed_broadcast!(nodes[1]);
4920 fn test_update_add_htlc_bolt2_receiver_check_max_htlc_limit() {
4921 //BOLT 2 Requirement: if a sending node adds more than its max_accepted_htlcs HTLCs to its local commitment transaction: SHOULD fail the channel
4922 //BOLT 2 Requirement: MUST allow multiple HTLCs with the same payment_hash.
4923 let mut nodes = create_network(2);
4924 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
4925 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
4926 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4928 let session_priv = SecretKey::from_slice(&{
4929 let mut session_key = [0; 32];
4930 rng::fill_bytes(&mut session_key);
4932 }).expect("RNG is bad!");
4934 let cur_height = nodes[0].node.latest_block_height.load(Ordering::Acquire) as u32 + 1;
4935 let onion_keys = onion_utils::construct_onion_keys(&Secp256k1::signing_only(), &route, &session_priv).unwrap();
4936 let (onion_payloads, _htlc_msat, htlc_cltv) = onion_utils::build_onion_payloads(&route, cur_height).unwrap();
4937 let onion_packet = onion_utils::construct_onion_packet(onion_payloads, onion_keys, &our_payment_hash);
4939 let mut msg = msgs::UpdateAddHTLC {
4943 payment_hash: our_payment_hash,
4944 cltv_expiry: htlc_cltv,
4945 onion_routing_packet: onion_packet.clone(),
4948 for i in 0..super::channel::OUR_MAX_HTLCS {
4949 msg.htlc_id = i as u64;
4950 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg).unwrap();
4952 msg.htlc_id = (super::channel::OUR_MAX_HTLCS) as u64;
4953 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &msg);
4955 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
4956 assert_eq!(err, "Remote tried to push more than our max accepted HTLCs");
4961 assert!(nodes[1].node.list_channels().is_empty());
4962 check_closed_broadcast!(nodes[1]);
4966 fn test_update_add_htlc_bolt2_receiver_check_max_in_flight_msat() {
4967 //OR adds more than its max_htlc_value_in_flight_msat worth of offered HTLCs to its local commitment transaction: SHOULD fail the channel
4968 let mut nodes = create_network(2);
4969 let chan = create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
4970 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
4971 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4972 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4973 check_added_monitors!(nodes[0], 1);
4974 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4975 updates.update_add_htlcs[0].amount_msat = get_channel_value_stat!(nodes[1], chan.2).their_max_htlc_value_in_flight_msat + 1;
4976 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
4978 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
4979 assert_eq!(err,"Remote HTLC add would put them over their max HTLC value in flight");
4984 assert!(nodes[1].node.list_channels().is_empty());
4985 check_closed_broadcast!(nodes[1]);
4989 fn test_update_add_htlc_bolt2_receiver_check_cltv_expiry() {
4990 //BOLT2 Requirement: if sending node sets cltv_expiry to greater or equal to 500000000: SHOULD fail the channel.
4991 let mut nodes = create_network(2);
4992 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 100000, 95000000);
4993 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 3999999, TEST_FINAL_CLTV).unwrap();
4994 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
4995 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
4996 check_added_monitors!(nodes[0], 1);
4997 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
4998 updates.update_add_htlcs[0].cltv_expiry = 500000000;
4999 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5001 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5002 assert_eq!(err,"Remote provided CLTV expiry in seconds instead of block height");
5007 assert!(nodes[1].node.list_channels().is_empty());
5008 check_closed_broadcast!(nodes[1]);
5012 fn test_update_add_htlc_bolt2_receiver_check_repeated_id_ignore() {
5013 //BOLT 2 requirement: if the sender did not previously acknowledge the commitment of that HTLC: MUST ignore a repeated id value after a reconnection.
5014 // We test this by first testing that that repeated HTLCs pass commitment signature checks
5015 // after disconnect and that non-sequential htlc_ids result in a channel failure.
5016 let mut nodes = create_network(2);
5017 create_announced_chan_between_nodes(&nodes, 0, 1);
5018 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5019 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5020 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5021 check_added_monitors!(nodes[0], 1);
5022 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5023 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5025 //Disconnect and Reconnect
5026 nodes[0].node.peer_disconnected(&nodes[1].node.get_our_node_id(), false);
5027 nodes[1].node.peer_disconnected(&nodes[0].node.get_our_node_id(), false);
5028 nodes[0].node.peer_connected(&nodes[1].node.get_our_node_id());
5029 let reestablish_1 = get_chan_reestablish_msgs!(nodes[0], nodes[1]);
5030 assert_eq!(reestablish_1.len(), 1);
5031 nodes[1].node.peer_connected(&nodes[0].node.get_our_node_id());
5032 let reestablish_2 = get_chan_reestablish_msgs!(nodes[1], nodes[0]);
5033 assert_eq!(reestablish_2.len(), 1);
5034 nodes[0].node.handle_channel_reestablish(&nodes[1].node.get_our_node_id(), &reestablish_2[0]).unwrap();
5035 handle_chan_reestablish_msgs!(nodes[0], nodes[1]);
5036 nodes[1].node.handle_channel_reestablish(&nodes[0].node.get_our_node_id(), &reestablish_1[0]).unwrap();
5037 handle_chan_reestablish_msgs!(nodes[1], nodes[0]);
5040 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5041 assert_eq!(updates.commitment_signed.htlc_signatures.len(), 1);
5042 nodes[1].node.handle_commitment_signed(&nodes[0].node.get_our_node_id(), &updates.commitment_signed).unwrap();
5043 check_added_monitors!(nodes[1], 1);
5044 let _bs_responses = get_revoke_commit_msgs!(nodes[1], nodes[0].node.get_our_node_id());
5046 let err = nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]);
5047 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5048 assert_eq!(err, "Remote skipped HTLC ID");
5053 assert!(nodes[1].node.list_channels().is_empty());
5054 check_closed_broadcast!(nodes[1]);
5058 fn test_update_fulfill_htlc_bolt2_update_fulfill_htlc_before_commitment() {
5059 //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.
5061 let mut nodes = create_network(2);
5062 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5064 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5065 let (our_payment_preimage, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5066 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5067 check_added_monitors!(nodes[0], 1);
5068 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5069 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5071 let update_msg = msgs::UpdateFulfillHTLC{
5074 payment_preimage: our_payment_preimage,
5077 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5079 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5080 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5085 assert!(nodes[0].node.list_channels().is_empty());
5086 check_closed_broadcast!(nodes[0]);
5090 fn test_update_fulfill_htlc_bolt2_update_fail_htlc_before_commitment() {
5091 //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.
5093 let mut nodes = create_network(2);
5094 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5096 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5097 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5098 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5099 check_added_monitors!(nodes[0], 1);
5100 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5101 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5103 let update_msg = msgs::UpdateFailHTLC{
5106 reason: msgs::OnionErrorPacket { data: Vec::new()},
5109 let err = nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5111 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5112 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5117 assert!(nodes[0].node.list_channels().is_empty());
5118 check_closed_broadcast!(nodes[0]);
5122 fn test_update_fulfill_htlc_bolt2_update_fail_malformed_htlc_before_commitment() {
5123 //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.
5125 let mut nodes = create_network(2);
5126 let chan = create_announced_chan_between_nodes(&nodes, 0, 1);
5128 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5129 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5130 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5131 check_added_monitors!(nodes[0], 1);
5132 let updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5133 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5135 let update_msg = msgs::UpdateFailMalformedHTLC{
5138 sha256_of_onion: [1; 32],
5139 failure_code: 0x8000,
5142 let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5144 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5145 assert_eq!(err, "Remote tried to fulfill/fail HTLC before it had been committed");
5150 assert!(nodes[0].node.list_channels().is_empty());
5151 check_closed_broadcast!(nodes[0]);
5155 fn test_update_fulfill_htlc_bolt2_incorrect_htlc_id() {
5156 //BOLT 2 Requirement: A receiving node: if the id does not correspond to an HTLC in its current commitment transaction MUST fail the channel.
5158 let nodes = create_network(2);
5159 create_announced_chan_between_nodes(&nodes, 0, 1);
5161 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5163 nodes[1].node.claim_funds(our_payment_preimage);
5164 check_added_monitors!(nodes[1], 1);
5166 let events = nodes[1].node.get_and_clear_pending_msg_events();
5167 assert_eq!(events.len(), 1);
5168 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5170 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, .. } } => {
5171 assert!(update_add_htlcs.is_empty());
5172 assert_eq!(update_fulfill_htlcs.len(), 1);
5173 assert!(update_fail_htlcs.is_empty());
5174 assert!(update_fail_malformed_htlcs.is_empty());
5175 assert!(update_fee.is_none());
5176 update_fulfill_htlcs[0].clone()
5178 _ => panic!("Unexpected event"),
5182 update_fulfill_msg.htlc_id = 1;
5184 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5185 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5186 assert_eq!(err, "Remote tried to fulfill/fail an HTLC we couldn't find");
5191 assert!(nodes[0].node.list_channels().is_empty());
5192 check_closed_broadcast!(nodes[0]);
5196 fn test_update_fulfill_htlc_bolt2_wrong_preimage() {
5197 //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.
5199 let nodes = create_network(2);
5200 create_announced_chan_between_nodes(&nodes, 0, 1);
5202 let our_payment_preimage = route_payment(&nodes[0], &[&nodes[1]], 100000).0;
5204 nodes[1].node.claim_funds(our_payment_preimage);
5205 check_added_monitors!(nodes[1], 1);
5207 let events = nodes[1].node.get_and_clear_pending_msg_events();
5208 assert_eq!(events.len(), 1);
5209 let mut update_fulfill_msg: msgs::UpdateFulfillHTLC = {
5211 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, .. } } => {
5212 assert!(update_add_htlcs.is_empty());
5213 assert_eq!(update_fulfill_htlcs.len(), 1);
5214 assert!(update_fail_htlcs.is_empty());
5215 assert!(update_fail_malformed_htlcs.is_empty());
5216 assert!(update_fee.is_none());
5217 update_fulfill_htlcs[0].clone()
5219 _ => panic!("Unexpected event"),
5223 update_fulfill_msg.payment_preimage = PaymentPreimage([1; 32]);
5225 let err = nodes[0].node.handle_update_fulfill_htlc(&nodes[1].node.get_our_node_id(), &update_fulfill_msg);
5226 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5227 assert_eq!(err, "Remote tried to fulfill HTLC with an incorrect preimage");
5232 assert!(nodes[0].node.list_channels().is_empty());
5233 check_closed_broadcast!(nodes[0]);
5238 fn test_update_fulfill_htlc_bolt2_missing_badonion_bit_for_malformed_htlc_message() {
5239 //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.
5241 let mut nodes = create_network(2);
5242 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
5243 let route = nodes[0].router.get_route(&nodes[1].node.get_our_node_id(), None, &[], 1000000, TEST_FINAL_CLTV).unwrap();
5244 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5245 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5246 check_added_monitors!(nodes[0], 1);
5248 let mut updates = get_htlc_update_msgs!(nodes[0], nodes[1].node.get_our_node_id());
5249 updates.update_add_htlcs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5251 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &updates.update_add_htlcs[0]).unwrap();
5252 check_added_monitors!(nodes[1], 0);
5253 commitment_signed_dance!(nodes[1], nodes[0], updates.commitment_signed, false, true);
5255 let events = nodes[1].node.get_and_clear_pending_msg_events();
5257 let mut update_msg: msgs::UpdateFailMalformedHTLC = {
5259 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, .. } } => {
5260 assert!(update_add_htlcs.is_empty());
5261 assert!(update_fulfill_htlcs.is_empty());
5262 assert!(update_fail_htlcs.is_empty());
5263 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5264 assert!(update_fee.is_none());
5265 update_fail_malformed_htlcs[0].clone()
5267 _ => panic!("Unexpected event"),
5270 update_msg.failure_code &= !0x8000;
5271 let err = nodes[0].node.handle_update_fail_malformed_htlc(&nodes[1].node.get_our_node_id(), &update_msg);
5272 if let Err(msgs::HandleError{err, action: Some(msgs::ErrorAction::SendErrorMessage {..})}) = err {
5273 assert_eq!(err, "Got update_fail_malformed_htlc with BADONION not set");
5278 assert!(nodes[0].node.list_channels().is_empty());
5279 check_closed_broadcast!(nodes[0]);
5283 fn test_update_fulfill_htlc_bolt2_after_malformed_htlc_message_must_forward_update_fail_htlc() {
5284 //BOLT 2 Requirement: a receiving node which has an outgoing HTLC canceled by update_fail_malformed_htlc:
5285 // * 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.
5287 let mut nodes = create_network(3);
5288 create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1000000, 1000000);
5289 create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1000000, 1000000);
5291 let route = nodes[0].router.get_route(&nodes[2].node.get_our_node_id(), None, &Vec::new(), 100000, TEST_FINAL_CLTV).unwrap();
5292 let (_, our_payment_hash) = get_payment_preimage_hash!(nodes[0]);
5295 let mut payment_event = {
5296 nodes[0].node.send_payment(route, our_payment_hash).unwrap();
5297 check_added_monitors!(nodes[0], 1);
5298 let mut events = nodes[0].node.get_and_clear_pending_msg_events();
5299 assert_eq!(events.len(), 1);
5300 SendEvent::from_event(events.remove(0))
5302 nodes[1].node.handle_update_add_htlc(&nodes[0].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5303 check_added_monitors!(nodes[1], 0);
5304 commitment_signed_dance!(nodes[1], nodes[0], payment_event.commitment_msg, false);
5305 expect_pending_htlcs_forwardable!(nodes[1]);
5306 let mut events_2 = nodes[1].node.get_and_clear_pending_msg_events();
5307 assert_eq!(events_2.len(), 1);
5308 check_added_monitors!(nodes[1], 1);
5309 payment_event = SendEvent::from_event(events_2.remove(0));
5310 assert_eq!(payment_event.msgs.len(), 1);
5313 payment_event.msgs[0].onion_routing_packet.version = 1; //Produce a malformed HTLC message
5314 nodes[2].node.handle_update_add_htlc(&nodes[1].node.get_our_node_id(), &payment_event.msgs[0]).unwrap();
5315 check_added_monitors!(nodes[2], 0);
5316 commitment_signed_dance!(nodes[2], nodes[1], payment_event.commitment_msg, false, true);
5318 let events_3 = nodes[2].node.get_and_clear_pending_msg_events();
5319 assert_eq!(events_3.len(), 1);
5320 let update_msg : (msgs::UpdateFailMalformedHTLC, msgs::CommitmentSigned) = {
5322 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 } } => {
5323 assert!(update_add_htlcs.is_empty());
5324 assert!(update_fulfill_htlcs.is_empty());
5325 assert!(update_fail_htlcs.is_empty());
5326 assert_eq!(update_fail_malformed_htlcs.len(), 1);
5327 assert!(update_fee.is_none());
5328 (update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
5330 _ => panic!("Unexpected event"),
5334 nodes[1].node.handle_update_fail_malformed_htlc(&nodes[2].node.get_our_node_id(), &update_msg.0).unwrap();
5336 check_added_monitors!(nodes[1], 0);
5337 commitment_signed_dance!(nodes[1], nodes[2], update_msg.1, false, true);
5338 expect_pending_htlcs_forwardable!(nodes[1]);
5339 let events_4 = nodes[1].node.get_and_clear_pending_msg_events();
5340 assert_eq!(events_4.len(), 1);
5342 //Confirm that handlinge the update_malformed_htlc message produces an update_fail_htlc message to be forwarded back along the route
5344 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, .. } } => {
5345 assert!(update_add_htlcs.is_empty());
5346 assert!(update_fulfill_htlcs.is_empty());
5347 assert_eq!(update_fail_htlcs.len(), 1);
5348 assert!(update_fail_malformed_htlcs.is_empty());
5349 assert!(update_fee.is_none());
5351 _ => panic!("Unexpected event"),
5354 check_added_monitors!(nodes[1], 1);