Skip to content

Commit 0ca544e

Browse files
Correctly fail back blinded HTLCs when they're failed back to us
1 parent 0254890 commit 0ca544e

File tree

4 files changed

+278
-34
lines changed

4 files changed

+278
-34
lines changed

lightning/src/ln/blinded_payment_tests.rs

Lines changed: 124 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,14 @@
1010
use bitcoin::secp256k1::Secp256k1;
1111
use crate::blinded_path::BlindedPath;
1212
use crate::blinded_path::payment::{ForwardTlvs, PaymentConstraints, PaymentRelay, ReceiveTlvs};
13-
use crate::events::MessageSendEventsProvider;
13+
use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider};
1414
use crate::ln::channelmanager;
1515
use crate::ln::channelmanager::{PaymentId, RecipientOnionFields, RetryableSendFailure};
1616
use crate::ln::features::{BlindedHopFeatures, Bolt12InvoiceFeatures};
1717
use crate::ln::functional_test_utils::*;
18+
use crate::ln::msgs;
1819
use crate::ln::msgs::ChannelMessageHandler;
20+
use crate::ln::onion_utils::INVALID_ONION_BLINDING;
1921
use crate::ln::outbound_payment::Retry;
2022
use crate::prelude::*;
2123
use crate::routing::router::{PaymentParameters, RouteParameters};
@@ -439,3 +441,124 @@ fn high_prop_fees() {
439441
pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3], &nodes[4]]], amt_msat, payment_hash, payment_secret);
440442
claim_payment(&nodes[0], &[&nodes[1], &nodes[2], &nodes[3], &nodes[4]], payment_preimage);
441443
}
444+
445+
#[test]
446+
fn fail_blinded_payment() {
447+
let chanmon_cfgs = create_chanmon_cfgs(4);
448+
let node_cfgs = create_node_cfgs(4, &chanmon_cfgs);
449+
let node_chanmgrs = create_node_chanmgrs(4, &node_cfgs, &[None, None, None, None]);
450+
let nodes = create_network(4, &node_cfgs, &node_chanmgrs);
451+
create_announced_chan_between_nodes_with_value(&nodes, 0, 1, 1_000_000, 0);
452+
create_announced_chan_between_nodes_with_value(&nodes, 1, 2, 1_000_000, 0);
453+
let chan_upd = create_announced_chan_between_nodes_with_value(&nodes, 2, 3, 1_000_000, 0).0.contents;
454+
455+
let amt_msat = 5000;
456+
let (_, payment_hash, payment_secret) = get_payment_preimage_hash(&nodes[3], Some(amt_msat), None);
457+
let intermediate_nodes = vec![(nodes[2].node.get_our_node_id(), ForwardTlvs {
458+
short_channel_id: chan_upd.short_channel_id,
459+
payment_relay: PaymentRelay {
460+
cltv_expiry_delta: chan_upd.cltv_expiry_delta,
461+
fee_proportional_millionths: chan_upd.fee_proportional_millionths,
462+
fee_base_msat: chan_upd.fee_base_msat,
463+
},
464+
payment_constraints: PaymentConstraints {
465+
max_cltv_expiry: u32::max_value(),
466+
htlc_minimum_msat: chan_upd.htlc_minimum_msat,
467+
},
468+
features: BlindedHopFeatures::empty(),
469+
})];
470+
let payee_tlvs = ReceiveTlvs {
471+
payment_secret,
472+
payment_constraints: PaymentConstraints {
473+
max_cltv_expiry: u32::max_value(),
474+
htlc_minimum_msat: chan_upd.htlc_minimum_msat,
475+
},
476+
};
477+
let mut secp_ctx = Secp256k1::new();
478+
let blinded_path = BlindedPath::new_for_payment(
479+
&intermediate_nodes[..], nodes[3].node.get_our_node_id(), payee_tlvs,
480+
chan_upd.htlc_maximum_msat, &chanmon_cfgs[3].keys_manager, &secp_ctx
481+
).unwrap();
482+
483+
let route_params = RouteParameters {
484+
payment_params: PaymentParameters::blinded(vec![blinded_path]),
485+
final_value_msat: amt_msat
486+
};
487+
nodes[0].node.send_payment(payment_hash, RecipientOnionFields::spontaneous_empty(),
488+
PaymentId(payment_hash.0), route_params, Retry::Attempts(0)).unwrap();
489+
check_added_monitors(&nodes[0], 1);
490+
pass_along_route(&nodes[0], &[&[&nodes[1], &nodes[2], &nodes[3]]], amt_msat, payment_hash,
491+
payment_secret);
492+
493+
nodes[3].node.fail_htlc_backwards(&payment_hash);
494+
expect_pending_htlcs_forwardable_conditions(nodes[3].node.get_and_clear_pending_events(),
495+
&[HTLCDestination::FailedPayment { payment_hash }]);
496+
nodes[3].node.process_pending_htlc_forwards();
497+
498+
// The last node should fail back with malformed since it's not the intro node.
499+
check_added_monitors!(nodes[3], 1);
500+
let (update_fail_malformed, commitment_signed) = {
501+
let msg_events = nodes[3].node.get_and_clear_pending_msg_events();
502+
assert_eq!(msg_events.len(), 1);
503+
match msg_events[0] {
504+
MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate {
505+
ref update_fail_malformed_htlcs, ref commitment_signed, ..
506+
}, .. } => {
507+
assert_eq!(update_fail_malformed_htlcs.len(), 1);
508+
(update_fail_malformed_htlcs[0].clone(), commitment_signed.clone())
509+
},
510+
_ => panic!("Unexpected event"),
511+
}
512+
};
513+
assert_eq!(update_fail_malformed.sha256_of_onion, [0; 32]);
514+
assert_eq!(update_fail_malformed.failure_code, INVALID_ONION_BLINDING);
515+
nodes[2].node.handle_update_fail_malformed_htlc(&nodes[3].node.get_our_node_id(), &update_fail_malformed);
516+
do_commitment_signed_dance(&nodes[2], &nodes[3], &commitment_signed, true, false);
517+
518+
// The intro node fails back with the invalid_onion_blinding error.
519+
let (update_fail, commitment_signed) = {
520+
let msg_events = nodes[2].node.get_and_clear_pending_msg_events();
521+
assert_eq!(msg_events.len(), 1);
522+
match msg_events[0] {
523+
MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate {
524+
ref update_fail_htlcs, ref commitment_signed, ..
525+
}, .. } => {
526+
assert_eq!(update_fail_htlcs.len(), 1);
527+
(update_fail_htlcs[0].clone(), commitment_signed.clone())
528+
},
529+
_ => panic!("Unexpected event"),
530+
}
531+
};
532+
nodes[1].node.handle_update_fail_htlc(&nodes[2].node.get_our_node_id(), &update_fail);
533+
do_commitment_signed_dance(&nodes[1], &nodes[2], &commitment_signed, true, false);
534+
535+
let (final_update_fail, commitment_signed) = {
536+
let msg_events = nodes[1].node.get_and_clear_pending_msg_events();
537+
assert_eq!(msg_events.len(), 1);
538+
match msg_events[0] {
539+
MessageSendEvent::UpdateHTLCs { updates: msgs::CommitmentUpdate {
540+
ref update_fail_htlcs, ref commitment_signed, ..
541+
}, .. } => {
542+
assert_eq!(update_fail_htlcs.len(), 1);
543+
(update_fail_htlcs[0].clone(), commitment_signed.clone())
544+
},
545+
_ => panic!("Unexpected event"),
546+
}
547+
};
548+
nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &final_update_fail);
549+
do_commitment_signed_dance(&nodes[0], &nodes[1], &commitment_signed, false, false);
550+
let failure_evs = nodes[0].node.get_and_clear_pending_events();
551+
assert_eq!(failure_evs.len(), 2);
552+
match &failure_evs[0] {
553+
Event::PaymentPathFailed {
554+
payment_hash: ref ev_payment_hash, payment_failed_permanently, ref error_code, ref error_data,
555+
..
556+
} => {
557+
assert_eq!(payment_hash, *ev_payment_hash);
558+
assert!(!payment_failed_permanently);
559+
assert_eq!(error_code, &Some(INVALID_ONION_BLINDING));
560+
assert_eq!(error_data, &Some(vec![0; 32]));
561+
},
562+
_ => panic!("Unexpected event"),
563+
}
564+
}

lightning/src/ln/channel.rs

Lines changed: 89 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use crate::ln::script::{self, ShutdownScript};
3030
use crate::ln::channelmanager::{self, CounterpartyForwardingInfo, PendingHTLCStatus, HTLCSource, SentHTLCId, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT, ChannelShutdownState};
3131
use crate::ln::chan_utils::{CounterpartyCommitmentSecrets, TxCreationKeys, HTLCOutputInCommitment, htlc_success_tx_weight, htlc_timeout_tx_weight, make_funding_redeemscript, ChannelPublicKeys, CommitmentTransaction, HolderCommitmentTransaction, ChannelTransactionParameters, CounterpartyChannelTransactionParameters, MAX_HTLCS, get_commitment_transaction_number_obscure_factor, ClosingTransaction};
3232
use crate::ln::chan_utils;
33-
use crate::ln::onion_utils::HTLCFailReason;
33+
use crate::ln::onion_utils::{HTLCFailReason, INVALID_ONION_BLINDING};
3434
use crate::chain::BestBlock;
3535
use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator};
3636
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS, CLOSED_CHANNEL_UPDATE_ID};
@@ -248,6 +248,9 @@ enum HTLCUpdateAwaitingACK {
248248
htlc_id: u64,
249249
err_packet: msgs::OnionErrorPacket,
250250
},
251+
FailMalformedHTLC {
252+
htlc_id: u64,
253+
},
251254
}
252255

253256
/// There are a few "states" and then a number of flags which can be applied:
@@ -2055,6 +2058,25 @@ struct CommitmentTxInfoCached {
20552058
feerate: u32,
20562059
}
20572060

2061+
trait FailHTLCMessage {
2062+
fn new(htlc_id: u64, channel_id: ChannelId, reason: msgs::OnionErrorPacket) -> Self;
2063+
}
2064+
impl FailHTLCMessage for msgs::UpdateFailHTLC {
2065+
fn new(htlc_id: u64, channel_id: ChannelId, reason: msgs::OnionErrorPacket) -> Self {
2066+
msgs::UpdateFailHTLC { htlc_id, channel_id, reason }
2067+
}
2068+
}
2069+
impl FailHTLCMessage for msgs::UpdateFailMalformedHTLC {
2070+
fn new(htlc_id: u64, channel_id: ChannelId, _reason: msgs::OnionErrorPacket) -> Self {
2071+
msgs::UpdateFailMalformedHTLC {
2072+
htlc_id,
2073+
channel_id,
2074+
sha256_of_onion: [0; 32],
2075+
failure_code: INVALID_ONION_BLINDING,
2076+
}
2077+
}
2078+
}
2079+
20582080
impl<SP: Deref> Channel<SP> where
20592081
SP::Target: SignerProvider,
20602082
<SP::Target as SignerProvider>::Signer: WriteableEcdsaChannelSigner
@@ -2279,7 +2301,9 @@ impl<SP: Deref> Channel<SP> where
22792301
return UpdateFulfillFetch::DuplicateClaim {};
22802302
}
22812303
},
2282-
&HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } => {
2304+
&HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } |
2305+
&HTLCUpdateAwaitingACK::FailMalformedHTLC { htlc_id, .. } =>
2306+
{
22832307
if htlc_id_arg == htlc_id {
22842308
log_warn!(logger, "Have preimage and want to fulfill HTLC with pending failure against channel {}", &self.context.channel_id());
22852309
// TODO: We may actually be able to switch to a fulfill here, though its
@@ -2372,7 +2396,15 @@ impl<SP: Deref> Channel<SP> where
23722396
/// [`ChannelError::Ignore`].
23732397
pub fn queue_fail_htlc<L: Deref>(&mut self, htlc_id_arg: u64, err_packet: msgs::OnionErrorPacket, logger: &L)
23742398
-> Result<(), ChannelError> where L::Target: Logger {
2375-
self.fail_htlc(htlc_id_arg, err_packet, true, logger)
2399+
self.fail_htlc::<L, msgs::UpdateFailHTLC>(htlc_id_arg, Some(err_packet), true, logger)
2400+
.map(|msg_opt| assert!(msg_opt.is_none(), "We forced holding cell?"))
2401+
}
2402+
2403+
/// Used for failing back blinded payments if we are not the intro node. See
2404+
/// [`Self::queue_fail_htlc`] for more info.
2405+
pub fn queue_fail_blinded_intermed_htlc<L: Deref>(&mut self, htlc_id_arg: u64, logger: &L)
2406+
-> Result<(), ChannelError> where L::Target: Logger {
2407+
self.fail_htlc::<L, msgs::UpdateFailMalformedHTLC>(htlc_id_arg, None, true, logger)
23762408
.map(|msg_opt| assert!(msg_opt.is_none(), "We forced holding cell?"))
23772409
}
23782410

@@ -2384,8 +2416,10 @@ impl<SP: Deref> Channel<SP> where
23842416
/// If we do fail twice, we `debug_assert!(false)` and return `Ok(None)`. Thus, this will always
23852417
/// return `Ok(_)` if preconditions are met. In any case, `Err`s will only be
23862418
/// [`ChannelError::Ignore`].
2387-
fn fail_htlc<L: Deref>(&mut self, htlc_id_arg: u64, err_packet: msgs::OnionErrorPacket, mut force_holding_cell: bool, logger: &L)
2388-
-> Result<Option<msgs::UpdateFailHTLC>, ChannelError> where L::Target: Logger {
2419+
fn fail_htlc<L: Deref, M: FailHTLCMessage>(
2420+
&mut self, htlc_id_arg: u64, err_packet: Option<msgs::OnionErrorPacket>,
2421+
mut force_holding_cell: bool, logger: &L
2422+
) -> Result<Option<M>, ChannelError> where L::Target: Logger {
23892423
if (self.context.channel_state & (ChannelState::ChannelReady as u32)) != (ChannelState::ChannelReady as u32) {
23902424
panic!("Was asked to fail an HTLC when channel was not in an operational state");
23912425
}
@@ -2439,7 +2473,9 @@ impl<SP: Deref> Channel<SP> where
24392473
return Ok(None);
24402474
}
24412475
},
2442-
&HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } => {
2476+
&HTLCUpdateAwaitingACK::FailHTLC { htlc_id, .. } |
2477+
&HTLCUpdateAwaitingACK::FailMalformedHTLC { htlc_id } =>
2478+
{
24432479
if htlc_id_arg == htlc_id {
24442480
debug_assert!(false, "Tried to fail an HTLC that was already failed");
24452481
return Err(ChannelError::Ignore("Unable to find a pending HTLC which matched the given HTLC ID".to_owned()));
@@ -2448,25 +2484,34 @@ impl<SP: Deref> Channel<SP> where
24482484
_ => {}
24492485
}
24502486
}
2451-
log_trace!(logger, "Placing failure for HTLC ID {} in holding cell in channel {}.", htlc_id_arg, &self.context.channel_id());
2452-
self.context.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::FailHTLC {
2453-
htlc_id: htlc_id_arg,
2454-
err_packet,
2455-
});
2487+
log_trace!(logger, "Placing failure for HTLC ID {} in holding cell in channel {}.", htlc_id_arg, self.context.channel_id());
2488+
if let Some(err_packet) = err_packet {
2489+
self.context.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::FailHTLC {
2490+
htlc_id: htlc_id_arg,
2491+
err_packet,
2492+
});
2493+
} else {
2494+
self.context.holding_cell_htlc_updates.push(HTLCUpdateAwaitingACK::FailMalformedHTLC {
2495+
htlc_id: htlc_id_arg,
2496+
});
2497+
}
24562498
return Ok(None);
24572499
}
24582500

2459-
log_trace!(logger, "Failing HTLC ID {} back with a update_fail_htlc message in channel {}.", htlc_id_arg, &self.context.channel_id());
2501+
log_trace!(logger, "Failing HTLC ID {} back with a update_fail_{}htlc message in channel {}.",
2502+
htlc_id_arg, if err_packet.is_none() { "malformed_" } else { "" }, self.context.channel_id());
24602503
{
24612504
let htlc = &mut self.context.pending_inbound_htlcs[pending_idx];
2462-
htlc.state = InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailRelay(err_packet.clone()));
2505+
if let Some(ref err_packet) = err_packet {
2506+
htlc.state = InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailRelay(err_packet.clone()));
2507+
} else {
2508+
htlc.state = InboundHTLCState::LocalRemoved(
2509+
InboundHTLCRemovalReason::FailMalformed(([0; 32], INVALID_ONION_BLINDING)));
2510+
}
24632511
}
24642512

2465-
Ok(Some(msgs::UpdateFailHTLC {
2466-
channel_id: self.context.channel_id(),
2467-
htlc_id: htlc_id_arg,
2468-
reason: err_packet
2469-
}))
2513+
let err_packet = err_packet.unwrap_or(msgs::OnionErrorPacket { data: Vec::new()});
2514+
Ok(Some(M::new(htlc_id_arg, self.context.channel_id(), err_packet)))
24702515
}
24712516

24722517
// Message handlers:
@@ -3164,7 +3209,9 @@ impl<SP: Deref> Channel<SP> where
31643209
monitor_update.updates.append(&mut additional_monitor_update.updates);
31653210
},
31663211
&HTLCUpdateAwaitingACK::FailHTLC { htlc_id, ref err_packet } => {
3167-
match self.fail_htlc(htlc_id, err_packet.clone(), false, logger) {
3212+
match self.fail_htlc::<L, msgs::UpdateFailHTLC>(
3213+
htlc_id, Some(err_packet.clone()), false, logger)
3214+
{
31683215
Ok(update_fail_msg_option) => {
31693216
// If an HTLC failure was previously added to the holding cell (via
31703217
// `queue_fail_htlc`) then generating the fail message itself must
@@ -3182,6 +3229,22 @@ impl<SP: Deref> Channel<SP> where
31823229
}
31833230
}
31843231
},
3232+
&HTLCUpdateAwaitingACK::FailMalformedHTLC { htlc_id } => {
3233+
match self.fail_htlc::<L, msgs::UpdateFailMalformedHTLC>(
3234+
htlc_id, None, false, logger)
3235+
{
3236+
Ok(update_fail_malformed_opt) => {
3237+
debug_assert!(update_fail_malformed_opt.is_some()); // See above comment
3238+
update_fail_count += 1;
3239+
},
3240+
Err(e) => {
3241+
if let ChannelError::Ignore(_) = e {}
3242+
else {
3243+
panic!("Got a non-IgnoreError action trying to fail holding cell HTLC");
3244+
}
3245+
}
3246+
}
3247+
},
31853248
}
31863249
}
31873250
if update_add_count == 0 && update_fulfill_count == 0 && update_fail_count == 0 && self.context.holding_cell_update_fee.is_none() {
@@ -6853,6 +6916,10 @@ impl<SP: Deref> Writeable for Channel<SP> where SP::Target: SignerProvider {
68536916
htlc_id.write(writer)?;
68546917
err_packet.write(writer)?;
68556918
}
6919+
&HTLCUpdateAwaitingACK::FailMalformedHTLC { ref htlc_id } => {
6920+
3u8.write(writer)?;
6921+
htlc_id.write(writer)?;
6922+
}
68566923
}
68576924
}
68586925

@@ -7148,6 +7215,9 @@ impl<'a, 'b, 'c, ES: Deref, SP: Deref> ReadableArgs<(&'a ES, &'b SP, u32, &'c Ch
71487215
htlc_id: Readable::read(reader)?,
71497216
err_packet: Readable::read(reader)?,
71507217
},
7218+
3 => HTLCUpdateAwaitingACK::FailMalformedHTLC {
7219+
htlc_id: Readable::read(reader)?,
7220+
},
71517221
_ => return Err(DecodeError::InvalidValue),
71527222
});
71537223
}

0 commit comments

Comments
 (0)