Skip to content

Commit 604eb91

Browse files
committed
Merge remote-tracking branch 'upstream/main' into replace-our-max-htlcs-constant
2 parents 52e19de + e1e3819 commit 604eb91

12 files changed

+216
-88
lines changed

lightning-invoice/src/lib.rs

Lines changed: 29 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,29 @@ pub enum Currency {
390390
Signet,
391391
}
392392

393+
impl From<Network> for Currency {
394+
fn from(network: Network) -> Self {
395+
match network {
396+
Network::Bitcoin => Currency::Bitcoin,
397+
Network::Testnet => Currency::BitcoinTestnet,
398+
Network::Regtest => Currency::Regtest,
399+
Network::Signet => Currency::Signet,
400+
}
401+
}
402+
}
403+
404+
impl From<Currency> for Network {
405+
fn from(currency: Currency) -> Self {
406+
match currency {
407+
Currency::Bitcoin => Network::Bitcoin,
408+
Currency::BitcoinTestnet => Network::Testnet,
409+
Currency::Regtest => Network::Regtest,
410+
Currency::Simnet => Network::Regtest,
411+
Currency::Signet => Network::Signet,
412+
}
413+
}
414+
}
415+
393416
/// Tagged field which may have an unknown tag
394417
///
395418
/// This is not exported to bindings users as we don't currently support TaggedField
@@ -1303,14 +1326,6 @@ impl Invoice {
13031326
/// Returns a list of all fallback addresses as [`Address`]es
13041327
pub fn fallback_addresses(&self) -> Vec<Address> {
13051328
self.fallbacks().iter().map(|fallback| {
1306-
let network = match self.currency() {
1307-
Currency::Bitcoin => Network::Bitcoin,
1308-
Currency::BitcoinTestnet => Network::Testnet,
1309-
Currency::Regtest => Network::Regtest,
1310-
Currency::Simnet => Network::Regtest,
1311-
Currency::Signet => Network::Signet,
1312-
};
1313-
13141329
let payload = match fallback {
13151330
Fallback::SegWitProgram { version, program } => {
13161331
Payload::WitnessProgram { version: *version, program: program.to_vec() }
@@ -1323,7 +1338,7 @@ impl Invoice {
13231338
}
13241339
};
13251340

1326-
Address { payload, network }
1341+
Address { payload, network: self.network() }
13271342
}).collect()
13281343
}
13291344

@@ -1344,6 +1359,11 @@ impl Invoice {
13441359
self.signed_invoice.currency()
13451360
}
13461361

1362+
/// Returns the network for which the invoice was issued
1363+
pub fn network(&self) -> Network {
1364+
self.signed_invoice.currency().into()
1365+
}
1366+
13471367
/// Returns the amount if specified in the invoice as millisatoshis.
13481368
pub fn amount_milli_satoshis(&self) -> Option<u64> {
13491369
self.signed_invoice.amount_pico_btc().map(|v| v / 10)

lightning/src/events/mod.rs

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,6 +272,43 @@ impl_writeable_tlv_based_enum!(InterceptNextHop,
272272
};
273273
);
274274

275+
/// The reason the payment failed. Used in [`Event::PaymentFailed`].
276+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
277+
pub enum PaymentFailureReason {
278+
/// The intended recipient rejected our payment.
279+
RecipientRejected,
280+
/// The user chose to abandon this payment by calling [`ChannelManager::abandon_payment`].
281+
///
282+
/// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
283+
UserAbandoned,
284+
/// We exhausted all of our retry attempts while trying to send the payment, or we
285+
/// exhausted the [`Retry::Timeout`] if the user set one. If at any point a retry
286+
/// attempt failed while being forwarded along the path, an [`Event::PaymentPathFailed`] will
287+
/// have come before this.
288+
///
289+
/// [`Retry::Timeout`]: crate::ln::channelmanager::Retry::Timeout
290+
RetriesExhausted,
291+
/// The payment expired while retrying, based on the provided
292+
/// [`PaymentParameters::expiry_time`].
293+
///
294+
/// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
295+
PaymentExpired,
296+
/// We failed to find a route while retrying the payment.
297+
RouteNotFound,
298+
/// This error should generally never happen. This likely means that there is a problem with
299+
/// your router.
300+
UnexpectedError,
301+
}
302+
303+
impl_writeable_tlv_based_enum!(PaymentFailureReason,
304+
(0, RecipientRejected) => {},
305+
(2, UserAbandoned) => {},
306+
(4, RetriesExhausted) => {},
307+
(6, PaymentExpired) => {},
308+
(8, RouteNotFound) => {},
309+
(10, UnexpectedError) => {}, ;
310+
);
311+
275312
/// An Event which you should probably take some action in response to.
276313
///
277314
/// Note that while Writeable and Readable are implemented for Event, you probably shouldn't use
@@ -438,6 +475,9 @@ pub enum Event {
438475
///
439476
/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
440477
payment_hash: PaymentHash,
478+
/// The reason the payment failed. This is only `None` for events generated or serialized
479+
/// by versions prior to 0.0.115.
480+
reason: Option<PaymentFailureReason>,
441481
},
442482
/// Indicates that a path for an outbound payment was successful.
443483
///
@@ -903,10 +943,11 @@ impl Writeable for Event {
903943
(4, *path, vec_type)
904944
})
905945
},
906-
&Event::PaymentFailed { ref payment_id, ref payment_hash } => {
946+
&Event::PaymentFailed { ref payment_id, ref payment_hash, ref reason } => {
907947
15u8.write(writer)?;
908948
write_tlv_fields!(writer, {
909949
(0, payment_id, required),
950+
(1, reason, option),
910951
(2, payment_hash, required),
911952
})
912953
},
@@ -1208,13 +1249,16 @@ impl MaybeReadable for Event {
12081249
let f = || {
12091250
let mut payment_hash = PaymentHash([0; 32]);
12101251
let mut payment_id = PaymentId([0; 32]);
1252+
let mut reason = None;
12111253
read_tlv_fields!(reader, {
12121254
(0, payment_id, required),
1255+
(1, reason, upgradable_option),
12131256
(2, payment_hash, required),
12141257
});
12151258
Ok(Some(Event::PaymentFailed {
12161259
payment_id,
12171260
payment_hash,
1261+
reason,
12181262
}))
12191263
};
12201264
f()

lightning/src/ln/channelmanager.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, Fee
3636
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
3737
use crate::chain::transaction::{OutPoint, TransactionData};
3838
use crate::events;
39-
use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination};
39+
use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason};
4040
// Since this struct is returned in `list_channels` methods, expose it here in case users want to
4141
// construct one themselves.
4242
use crate::ln::{inbound_payment, PaymentHash, PaymentPreimage, PaymentSecret};
@@ -1588,7 +1588,7 @@ macro_rules! handle_new_monitor_update {
15881588
($self: ident, $update_res: expr, $update_id: expr, $peer_state_lock: expr, $peer_state: expr, $per_peer_state_lock: expr, $chan: expr, MANUALLY_REMOVING, $remove: expr) => { {
15891589
// update_maps_on_chan_removal needs to be able to take id_to_peer, so make sure we can in
15901590
// any case so that it won't deadlock.
1591-
debug_assert!($self.id_to_peer.try_lock().is_ok());
1591+
debug_assert_ne!($self.id_to_peer.held_by_thread(), LockHeldState::HeldByThread);
15921592
match $update_res {
15931593
ChannelMonitorUpdateStatus::InProgress => {
15941594
log_debug!($self.logger, "ChannelMonitor update for {} in flight, holding messages until the update completes.",
@@ -2711,7 +2711,7 @@ where
27112711
/// [`Event::PaymentSent`]: events::Event::PaymentSent
27122712
pub fn abandon_payment(&self, payment_id: PaymentId) {
27132713
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(&self.total_consistency_lock, &self.persistence_notifier);
2714-
self.pending_outbound_payments.abandon_payment(payment_id, &self.pending_events);
2714+
self.pending_outbound_payments.abandon_payment(payment_id, PaymentFailureReason::UserAbandoned, &self.pending_events);
27152715
}
27162716

27172717
/// Send a spontaneous payment, which is a payment that does not require the recipient to have

lightning/src/ln/functional_test_utils.rs

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
use crate::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen, Watch, keysinterface::EntropySource};
1414
use crate::chain::channelmonitor::ChannelMonitor;
1515
use crate::chain::transaction::OutPoint;
16-
use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose};
16+
use crate::events::{ClosureReason, Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, PaymentFailureReason};
1717
use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
1818
use crate::ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, PaymentId, MIN_CLTV_EXPIRY_DELTA};
1919
use crate::routing::gossip::{P2PGossipSync, NetworkGraph, NetworkUpdate};
@@ -1937,9 +1937,14 @@ pub fn expect_payment_failed_conditions_event<'a, 'b, 'c, 'd, 'e>(
19371937
};
19381938
if !conditions.expected_mpp_parts_remain {
19391939
match &payment_failed_events[1] {
1940-
Event::PaymentFailed { ref payment_hash, ref payment_id } => {
1940+
Event::PaymentFailed { ref payment_hash, ref payment_id, ref reason } => {
19411941
assert_eq!(*payment_hash, expected_payment_hash, "unexpected second payment_hash");
19421942
assert_eq!(*payment_id, expected_payment_id);
1943+
assert_eq!(reason.unwrap(), if expected_payment_failed_permanently {
1944+
PaymentFailureReason::RecipientRejected
1945+
} else {
1946+
PaymentFailureReason::RetriesExhausted
1947+
});
19431948
}
19441949
_ => panic!("Unexpected second event"),
19451950
}
@@ -2240,10 +2245,10 @@ pub fn fail_payment_along_route<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expe
22402245
let expected_destinations: Vec<HTLCDestination> = repeat(HTLCDestination::FailedPayment { payment_hash: our_payment_hash }).take(expected_paths.len()).collect();
22412246
expect_pending_htlcs_forwardable_and_htlc_handling_failed!(expected_paths[0].last().unwrap(), expected_destinations);
22422247

2243-
pass_failed_payment_back(origin_node, expected_paths, skip_last, our_payment_hash);
2248+
pass_failed_payment_back(origin_node, expected_paths, skip_last, our_payment_hash, PaymentFailureReason::RecipientRejected);
22442249
}
22452250

2246-
pub fn pass_failed_payment_back<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths_slice: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash) {
2251+
pub fn pass_failed_payment_back<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expected_paths_slice: &[&[&Node<'a, 'b, 'c>]], skip_last: bool, our_payment_hash: PaymentHash, expected_fail_reason: PaymentFailureReason) {
22472252
let mut expected_paths: Vec<_> = expected_paths_slice.iter().collect();
22482253
check_added_monitors!(expected_paths[0].last().unwrap(), expected_paths.len());
22492254

@@ -2329,9 +2334,10 @@ pub fn pass_failed_payment_back<'a, 'b, 'c>(origin_node: &Node<'a, 'b, 'c>, expe
23292334
};
23302335
if i == expected_paths.len() - 1 {
23312336
match events[1] {
2332-
Event::PaymentFailed { ref payment_hash, ref payment_id } => {
2337+
Event::PaymentFailed { ref payment_hash, ref payment_id, ref reason } => {
23332338
assert_eq!(*payment_hash, our_payment_hash, "unexpected second payment_hash");
23342339
assert_eq!(*payment_id, expected_payment_id);
2340+
assert_eq!(reason.unwrap(), expected_fail_reason);
23352341
}
23362342
_ => panic!("Unexpected second event"),
23372343
}

lightning/src/ln/functional_tests.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ use crate::chain::channelmonitor;
1818
use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY};
1919
use crate::chain::transaction::OutPoint;
2020
use crate::chain::keysinterface::{ChannelSigner, EcdsaChannelSigner, EntropySource};
21-
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination};
21+
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentPurpose, ClosureReason, HTLCDestination, PaymentFailureReason};
2222
use crate::ln::{PaymentPreimage, PaymentSecret, PaymentHash};
2323
use crate::ln::channel::{commitment_tx_base_weight, COMMITMENT_TX_WEIGHT_PER_HTLC, CONCURRENT_INBOUND_HTLC_FEE_BUFFER, FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_AFFORDABLE_HTLC_COUNT};
2424
use crate::ln::channelmanager::{self, PaymentId, RAACommitmentOrder, PaymentSendFailure, RecipientOnionFields, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA};
@@ -9608,7 +9608,7 @@ fn test_double_partial_claim() {
96089608
];
96099609
expect_pending_htlcs_forwardable_and_htlc_handling_failed!(nodes[3], failed_destinations);
96109610

9611-
pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash);
9611+
pass_failed_payment_back(&nodes[0], &[&[&nodes[1], &nodes[3]], &[&nodes[2], &nodes[3]]], false, payment_hash, PaymentFailureReason::RecipientRejected);
96129612

96139613
// nodes[1] now retries one of the two paths...
96149614
nodes[0].node.send_payment_with_route(&route, payment_hash,

lightning/src/ln/msgs.rs

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ use crate::util::ser::{LengthReadable, Readable, ReadableArgs, Writeable, Writer
4646

4747
use crate::ln::{PaymentPreimage, PaymentHash, PaymentSecret};
4848

49-
use crate::routing::gossip::NodeId;
49+
use crate::routing::gossip::{NodeAlias, NodeId};
5050

5151
/// 21 million * 10^8 * 1000
5252
pub(crate) const MAX_VALUE_MSAT: u64 = 21_000_000_0000_0000_000;
@@ -694,7 +694,7 @@ pub struct UnsignedNodeAnnouncement {
694694
/// An alias, for UI purposes.
695695
///
696696
/// This should be sanitized before use. There is no guarantee of uniqueness.
697-
pub alias: [u8; 32],
697+
pub alias: NodeAlias,
698698
/// List of addresses on which this node is reachable
699699
pub addresses: Vec<NetAddress>,
700700
pub(crate) excess_address_data: Vec<u8>,
@@ -1931,7 +1931,7 @@ impl Readable for UnsignedNodeAnnouncement {
19311931
let node_id: NodeId = Readable::read(r)?;
19321932
let mut rgb = [0; 3];
19331933
r.read_exact(&mut rgb)?;
1934-
let alias: [u8; 32] = Readable::read(r)?;
1934+
let alias: NodeAlias = Readable::read(r)?;
19351935

19361936
let addr_len: u16 = Readable::read(r)?;
19371937
let mut addresses: Vec<NetAddress> = Vec::new();
@@ -2138,7 +2138,7 @@ mod tests {
21382138
use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
21392139
use crate::ln::msgs;
21402140
use crate::ln::msgs::{FinalOnionHopData, OptionalField, OnionErrorPacket, OnionHopDataFormat};
2141-
use crate::routing::gossip::NodeId;
2141+
use crate::routing::gossip::{NodeAlias, NodeId};
21422142
use crate::util::ser::{Writeable, Readable, Hostname};
21432143

21442144
use bitcoin::hashes::hex::FromHex;
@@ -2333,7 +2333,7 @@ mod tests {
23332333
timestamp: 20190119,
23342334
node_id: NodeId::from_pubkey(&pubkey_1),
23352335
rgb: [32; 3],
2336-
alias: [16;32],
2336+
alias: NodeAlias([16;32]),
23372337
addresses,
23382338
excess_address_data: if excess_address_data { vec![33, 108, 40, 11, 83, 149, 162, 84, 110, 126, 75, 38, 99, 224, 79, 129, 22, 34, 241, 90, 79, 146, 232, 58, 162, 233, 43, 162, 165, 115, 193, 57, 20, 44, 84, 174, 99, 7, 42, 30, 193, 238, 125, 192, 192, 75, 222, 92, 132, 120, 6, 23, 42, 160, 92, 146, 194, 42, 232, 227, 8, 209, 210, 105] } else { Vec::new() },
23392339
excess_data: if excess_data { vec![59, 18, 204, 25, 92, 224, 162, 209, 189, 166, 168, 139, 239, 161, 159, 160, 127, 81, 202, 167, 92, 232, 56, 55, 242, 137, 101, 96, 11, 138, 172, 171, 8, 85, 255, 176, 231, 65, 236, 95, 124, 65, 66, 30, 152, 41, 169, 212, 134, 17, 200, 200, 49, 247, 27, 229, 234, 115, 230, 101, 148, 151, 127, 253] } else { Vec::new() },

lightning/src/ln/onion_route_tests.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
1414
use crate::chain::channelmonitor::{CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS};
1515
use crate::chain::keysinterface::{EntropySource, NodeSigner, Recipient};
16-
use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure};
16+
use crate::events::{Event, HTLCDestination, MessageSendEvent, MessageSendEventsProvider, PathFailure, PaymentFailureReason};
1717
use crate::ln::{PaymentHash, PaymentSecret};
1818
use crate::ln::channel::EXPIRE_PREV_CONFIG_TICKS;
1919
use crate::ln::channelmanager::{HTLCForwardInfo, FailureCode, CLTV_FAR_FAR_AWAY, MIN_CLTV_EXPIRY_DELTA, PendingAddHTLCInfo, PendingHTLCInfo, PendingHTLCRouting, PaymentId, RecipientOnionFields};
@@ -213,9 +213,14 @@ fn run_onion_failure_test_with_fail_intercept<F1,F2,F3>(_name: &str, test_case:
213213
panic!("Unexpected event");
214214
}
215215
match events[1] {
216-
Event::PaymentFailed { payment_hash: ev_payment_hash, payment_id: ev_payment_id } => {
216+
Event::PaymentFailed { payment_hash: ev_payment_hash, payment_id: ev_payment_id, reason: ref ev_reason } => {
217217
assert_eq!(*payment_hash, ev_payment_hash);
218218
assert_eq!(payment_id, ev_payment_id);
219+
assert_eq!(if expected_retryable {
220+
PaymentFailureReason::RetriesExhausted
221+
} else {
222+
PaymentFailureReason::RecipientRejected
223+
}, ev_reason.unwrap());
219224
}
220225
_ => panic!("Unexpected second event"),
221226
}

0 commit comments

Comments
 (0)