Skip to content

Commit 3173487

Browse files
committed
Move create_offer_builder to OffersMessageFlow
1 parent 25e861f commit 3173487

File tree

8 files changed

+236
-166
lines changed

8 files changed

+236
-166
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,8 +47,8 @@ use lightning::events::MessageSendEventsProvider;
4747
use lightning::ln::channel::FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE;
4848
use lightning::ln::channel_state::ChannelDetails;
4949
use lightning::ln::channelmanager::{
50-
ChainParameters, ChannelManager, ChannelManagerReadArgs, PaymentId, PaymentSendFailure,
51-
RecipientOnionFields,
50+
ChainParameters, ChannelManager, ChannelManagerReadArgs, OffersMessageCommons, PaymentId,
51+
PaymentSendFailure, RecipientOnionFields,
5252
};
5353
use lightning::ln::functional_test_utils::*;
5454
use lightning::ln::msgs::{

fuzz/src/full_stack.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,8 @@ use lightning::chain::{BestBlock, ChannelMonitorUpdateStatus, Confirm, Listen};
4040
use lightning::events::Event;
4141
use lightning::ln::channel_state::ChannelDetails;
4242
use lightning::ln::channelmanager::{
43-
ChainParameters, ChannelManager, InterceptId, PaymentId, RecipientOnionFields, Retry,
43+
ChainParameters, ChannelManager, InterceptId, OffersMessageCommons, PaymentId,
44+
RecipientOnionFields, Retry,
4445
};
4546
use lightning::ln::functional_test_utils::*;
4647
use lightning::ln::msgs::{self, DecodeError};

lightning-dns-resolver/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -391,7 +391,7 @@ mod test {
391391
let name = HumanReadableName::from_encoded("[email protected]").unwrap();
392392

393393
// When we get the proof back, override its contents to an offer from nodes[1]
394-
let bs_offer = nodes[1].node.create_offer_builder(None).unwrap().build().unwrap();
394+
let bs_offer = nodes[1].offers_handler.create_offer_builder(None).unwrap().build().unwrap();
395395
nodes[0]
396396
.node
397397
.testing_dnssec_proof_offer_resolution_override

lightning/src/ln/channelmanager.rs

Lines changed: 39 additions & 132 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ use crate::ln::wire::Encode;
6767
use crate::offers::invoice::{Bolt12Invoice, DerivedSigningPubkey, InvoiceBuilder, UnsignedBolt12Invoice, DEFAULT_RELATIVE_EXPIRY};
6868
use crate::offers::invoice_request::{InvoiceRequest, InvoiceRequestBuilder};
6969
use crate::offers::nonce::Nonce;
70-
use crate::offers::offer::{Offer, OfferBuilder};
70+
use crate::offers::offer::Offer;
7171
use crate::offers::parse::Bolt12SemanticError;
7272
use crate::offers::refund::{Refund, RefundBuilder};
7373
use crate::offers::signer;
@@ -94,7 +94,6 @@ use crate::onion_message::dns_resolution::{DNSResolverMessage, DNSResolverMessag
9494

9595
#[cfg(not(c_bindings))]
9696
use {
97-
crate::offers::offer::DerivedMetadata,
9897
crate::onion_message::messenger::DefaultMessageRouter,
9998
crate::routing::router::DefaultRouter,
10099
crate::routing::gossip::NetworkGraph,
@@ -1899,7 +1898,7 @@ where
18991898
///
19001899
/// ```
19011900
/// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
1902-
/// # use lightning::ln::channelmanager::{AChannelManager, Bolt11InvoiceParameters};
1901+
/// # use lightning::ln::channelmanager::{AChannelManager, Bolt11InvoiceParameters, OffersMessageCommons};
19031902
/// #
19041903
/// # fn example<T: AChannelManager>(channel_manager: T) {
19051904
/// # let channel_manager = channel_manager.get_cm();
@@ -2001,55 +2000,7 @@ where
20012000
///
20022001
/// ## BOLT 12 Offers
20032002
///
2004-
/// The [`offers`] module is useful for creating BOLT 12 offers. An [`Offer`] is a precursor to a
2005-
/// [`Bolt12Invoice`], which must first be requested by the payer. The interchange of these messages
2006-
/// as defined in the specification is handled by [`ChannelManager`]. However, this only works with
2007-
/// an [`Offer`] created using a builder returned by [`create_offer_builder`]. With this approach,
2008-
/// BOLT 12 offers and invoices are stateless just as BOLT 11 invoices are.
2009-
///
2010-
/// ```
2011-
/// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
2012-
/// # use lightning::ln::channelmanager::AChannelManager;
2013-
/// # use lightning::offers::parse::Bolt12SemanticError;
2014-
/// #
2015-
/// # fn example<T: AChannelManager>(channel_manager: T) -> Result<(), Bolt12SemanticError> {
2016-
/// # let channel_manager = channel_manager.get_cm();
2017-
/// # let absolute_expiry = None;
2018-
/// let offer = channel_manager
2019-
/// .create_offer_builder(absolute_expiry)?
2020-
/// # ;
2021-
/// # // Needed for compiling for c_bindings
2022-
/// # let builder: lightning::offers::offer::OfferBuilder<_, _> = offer.into();
2023-
/// # let offer = builder
2024-
/// .description("coffee".to_string())
2025-
/// .amount_msats(10_000_000)
2026-
/// .build()?;
2027-
/// let bech32_offer = offer.to_string();
2028-
///
2029-
/// // On the event processing thread
2030-
/// channel_manager.process_pending_events(&|event| {
2031-
/// match event {
2032-
/// Event::PaymentClaimable { payment_hash, purpose, .. } => match purpose {
2033-
/// PaymentPurpose::Bolt12OfferPayment { payment_preimage: Some(payment_preimage), .. } => {
2034-
/// println!("Claiming payment {}", payment_hash);
2035-
/// channel_manager.claim_funds(payment_preimage);
2036-
/// },
2037-
/// PaymentPurpose::Bolt12OfferPayment { payment_preimage: None, .. } => {
2038-
/// println!("Unknown payment hash: {}", payment_hash);
2039-
/// }
2040-
/// # _ => {},
2041-
/// },
2042-
/// Event::PaymentClaimed { payment_hash, amount_msat, .. } => {
2043-
/// println!("Claimed {} msats", amount_msat);
2044-
/// },
2045-
/// // ...
2046-
/// # _ => {},
2047-
/// }
2048-
/// Ok(())
2049-
/// });
2050-
/// # Ok(())
2051-
/// # }
2052-
/// ```
2003+
/// For more information on creating offers, see [`create_offer_builder`].
20532004
///
20542005
/// Use [`pay_for_offer`] to initiated payment, which sends an [`InvoiceRequest`] for an [`Offer`]
20552006
/// and pays the [`Bolt12Invoice`] response.
@@ -2170,7 +2121,7 @@ where
21702121
///
21712122
/// ```
21722123
/// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
2173-
/// # use lightning::ln::channelmanager::AChannelManager;
2124+
/// # use lightning::ln::channelmanager::{AChannelManager, OffersMessageCommons};
21742125
/// # use lightning::offers::refund::Refund;
21752126
/// #
21762127
/// # fn example<T: AChannelManager>(channel_manager: T, refund: &Refund) {
@@ -2289,7 +2240,6 @@ where
22892240
/// [`claim_funds`]: Self::claim_funds
22902241
/// [`send_payment`]: Self::send_payment
22912242
/// [`offers`]: crate::offers
2292-
/// [`create_offer_builder`]: Self::create_offer_builder
22932243
/// [`pay_for_offer`]: Self::pay_for_offer
22942244
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
22952245
/// [`create_refund_builder`]: Self::create_refund_builder
@@ -2301,6 +2251,7 @@ where
23012251
/// [`update_channel`]: chain::Watch::update_channel
23022252
/// [`ChannelUpdate`]: msgs::ChannelUpdate
23032253
/// [`read`]: ReadableArgs::read
2254+
/// [`create_offer_builder`]: crate::offers::flow::OffersMessageFlow::create_offer_builder
23042255
//
23052256
// Lock order:
23062257
// The tree structure below illustrates the lock order requirements for the different locks of the
@@ -2791,11 +2742,13 @@ const MAX_NO_CHANNEL_PEERS: usize = 250;
27912742
/// The maximum expiration from the current time where an [`Offer`] or [`Refund`] is considered
27922743
/// short-lived, while anything with a greater expiration is considered long-lived.
27932744
///
2794-
/// Using [`ChannelManager::create_offer_builder`] or [`ChannelManager::create_refund_builder`],
2745+
/// Using [`OffersMessageFlow::create_offer_builder`] or [`ChannelManager::create_refund_builder`],
27952746
/// will included a [`BlindedMessagePath`] created using:
27962747
/// - [`MessageRouter::create_compact_blinded_paths`] when short-lived, and
27972748
/// - [`MessageRouter::create_blinded_paths`] when long-lived.
27982749
///
2750+
/// [`OffersMessageFlow::create_offer_builder`]: crate::offers::flow::OffersMessageFlow::create_offer_builder
2751+
///
27992752
/// Using compact [`BlindedMessagePath`]s may provide better privacy as the [`MessageRouter`] could select
28002753
/// more hops. However, since they use short channel ids instead of pubkeys, they are more likely to
28012754
/// become invalid over time as channels are closed. Thus, they are only suitable for short-term use.
@@ -6818,7 +6771,7 @@ where
68186771
/// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
68196772
/// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
68206773
/// [`process_pending_events`]: EventsProvider::process_pending_events
6821-
/// [`create_inbound_payment`]: Self::create_inbound_payment
6774+
/// [`create_inbound_payment`]: ChannelManager::create_inbound_payment
68226775
/// [`create_inbound_payment_for_hash`]: ChannelManager::create_inbound_payment_for_hash
68236776
/// [`claim_funds_with_known_custom_tlvs`]: ChannelManager::claim_funds_with_known_custom_tlvs
68246777
pub fn claim_funds(&self, payment_preimage: PaymentPreimage) {
@@ -9386,57 +9339,6 @@ impl Default for Bolt11InvoiceParameters {
93869339
}
93879340
}
93889341

9389-
macro_rules! create_offer_builder { ($self: ident, $builder: ty) => {
9390-
/// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
9391-
/// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer's
9392-
/// expiration will be `absolute_expiry` if `Some`, otherwise it will not expire.
9393-
///
9394-
/// # Privacy
9395-
///
9396-
/// Uses [`MessageRouter`] to construct a [`BlindedMessagePath`] for the offer based on the given
9397-
/// `absolute_expiry` according to [`MAX_SHORT_LIVED_RELATIVE_EXPIRY`]. See those docs for
9398-
/// privacy implications as well as those of the parameterized [`Router`], which implements
9399-
/// [`MessageRouter`].
9400-
///
9401-
/// Also, uses a derived signing pubkey in the offer for recipient privacy.
9402-
///
9403-
/// # Limitations
9404-
///
9405-
/// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
9406-
/// reply path.
9407-
///
9408-
/// # Errors
9409-
///
9410-
/// Errors if the parameterized [`Router`] is unable to create a blinded path for the offer.
9411-
///
9412-
/// [`Offer`]: crate::offers::offer::Offer
9413-
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
9414-
pub fn create_offer_builder(
9415-
&$self, absolute_expiry: Option<Duration>
9416-
) -> Result<$builder, Bolt12SemanticError> {
9417-
let node_id = $self.get_our_node_id();
9418-
let expanded_key = &$self.inbound_payment_key;
9419-
let entropy = &*$self.entropy_source;
9420-
let secp_ctx = &$self.secp_ctx;
9421-
9422-
let nonce = Nonce::from_entropy_source(entropy);
9423-
let context = OffersContext::InvoiceRequest { nonce };
9424-
let path = $self.create_blinded_paths_using_absolute_expiry(context, absolute_expiry)
9425-
.and_then(|paths| paths.into_iter().next().ok_or(()))
9426-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9427-
let builder = OfferBuilder::deriving_signing_pubkey(node_id, expanded_key, nonce, secp_ctx)
9428-
.chain_hash($self.chain_hash)
9429-
.path(path);
9430-
9431-
let builder = match absolute_expiry {
9432-
None => builder,
9433-
Some(absolute_expiry) => builder.absolute_expiry(absolute_expiry),
9434-
};
9435-
9436-
Ok(builder.into())
9437-
}
9438-
} }
9439-
94409342
macro_rules! create_refund_builder { ($self: ident, $builder: ty) => {
94419343
/// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
94429344
/// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
@@ -9519,7 +9421,7 @@ macro_rules! create_refund_builder { ($self: ident, $builder: ty) => {
95199421
} }
95209422

95219423
/// Functions commonly shared in usage between [`ChannelManager`] & [`OffersMessageFlow`]
9522-
///
9424+
///
95239425
/// [`OffersMessageFlow`]: crate::offers::flow::OffersMessageFlow
95249426
pub trait OffersMessageCommons {
95259427
/// Get pending offers messages
@@ -9621,7 +9523,18 @@ pub trait OffersMessageCommons {
96219523
/// Get the current time determined by highest seen timestamp
96229524
fn get_current_blocktime(&self) -> Duration;
96239525

9526+
/// Creates a collection of blinded paths by delegating to [`MessageRouter`] based on
9527+
/// the path's intended lifetime.
9528+
///
9529+
/// Whether or not the path is compact depends on whether the path is short-lived or long-lived,
9530+
/// respectively, based on the given `absolute_expiry` as seconds since the Unix epoch. See
9531+
/// [`MAX_SHORT_LIVED_RELATIVE_EXPIRY`].
9532+
fn create_blinded_paths_using_absolute_expiry(
9533+
&self, context: OffersContext, absolute_expiry: Option<Duration>,
9534+
) -> Result<Vec<BlindedMessagePath>, ()>;
96249535

9536+
/// Get the [`ChainHash`] of the chain
9537+
fn get_chain_hash(&self) -> ChainHash;
96259538
}
96269539

96279540
impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref> OffersMessageCommons for ChannelManager<M, T, ES, NS, SP, F, R, MR, L>
@@ -9786,6 +9699,23 @@ where
97869699
fn get_current_blocktime(&self) -> Duration {
97879700
Duration::from_secs(self.highest_seen_timestamp.load(Ordering::Acquire) as u64)
97889701
}
9702+
9703+
fn create_blinded_paths_using_absolute_expiry(
9704+
&self, context: OffersContext, absolute_expiry: Option<Duration>,
9705+
) -> Result<Vec<BlindedMessagePath>, ()> {
9706+
let now = self.duration_since_epoch();
9707+
let max_short_lived_absolute_expiry = now.saturating_add(MAX_SHORT_LIVED_RELATIVE_EXPIRY);
9708+
9709+
if absolute_expiry.unwrap_or(Duration::MAX) <= max_short_lived_absolute_expiry {
9710+
self.create_compact_blinded_paths(context)
9711+
} else {
9712+
self.create_blinded_paths(MessageContext::Offers(context))
9713+
}
9714+
}
9715+
9716+
fn get_chain_hash(&self) -> ChainHash {
9717+
self.chain_hash
9718+
}
97899719
}
97909720

97919721
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
@@ -9807,13 +9737,9 @@ where
98079737
MR::Target: MessageRouter,
98089738
L::Target: Logger,
98099739
{
9810-
#[cfg(not(c_bindings))]
9811-
create_offer_builder!(self, OfferBuilder<DerivedMetadata, secp256k1::All>);
98129740
#[cfg(not(c_bindings))]
98139741
create_refund_builder!(self, RefundBuilder<secp256k1::All>);
98149742

9815-
#[cfg(c_bindings)]
9816-
create_offer_builder!(self, OfferWithDerivedMetadataBuilder);
98179743
#[cfg(c_bindings)]
98189744
create_refund_builder!(self, RefundMaybeWithDerivedMetadataBuilder);
98199745

@@ -10165,25 +10091,6 @@ where
1016510091
inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
1016610092
}
1016710093

10168-
/// Creates a collection of blinded paths by delegating to [`MessageRouter`] based on
10169-
/// the path's intended lifetime.
10170-
///
10171-
/// Whether or not the path is compact depends on whether the path is short-lived or long-lived,
10172-
/// respectively, based on the given `absolute_expiry` as seconds since the Unix epoch. See
10173-
/// [`MAX_SHORT_LIVED_RELATIVE_EXPIRY`].
10174-
fn create_blinded_paths_using_absolute_expiry(
10175-
&self, context: OffersContext, absolute_expiry: Option<Duration>,
10176-
) -> Result<Vec<BlindedMessagePath>, ()> {
10177-
let now = self.duration_since_epoch();
10178-
let max_short_lived_absolute_expiry = now.saturating_add(MAX_SHORT_LIVED_RELATIVE_EXPIRY);
10179-
10180-
if absolute_expiry.unwrap_or(Duration::MAX) <= max_short_lived_absolute_expiry {
10181-
self.create_compact_blinded_paths(context)
10182-
} else {
10183-
self.create_blinded_paths(MessageContext::Offers(context))
10184-
}
10185-
}
10186-
1018710094
pub(super) fn duration_since_epoch(&self) -> Duration {
1018810095
#[cfg(not(feature = "std"))]
1018910096
let now = Duration::from_secs(
@@ -15158,7 +15065,7 @@ pub mod bench {
1515815065
use crate::chain::chainmonitor::{ChainMonitor, Persist};
1515915066
use crate::sign::{KeysManager, InMemorySigner};
1516015067
use crate::events::{Event, MessageSendEvent, MessageSendEventsProvider};
15161-
use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
15068+
use crate::ln::channelmanager::{BestBlock, ChainParameters, ChannelManager, OffersMessageCommons, PaymentHash, PaymentPreimage, PaymentId, RecipientOnionFields, Retry};
1516215069
use crate::ln::functional_test_utils::*;
1516315070
use crate::ln::msgs::{ChannelMessageHandler, Init};
1516415071
use crate::routing::gossip::NetworkGraph;

lightning/src/ln/max_payment_path_len_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ fn bolt12_invoice_too_large_blinded_paths() {
385385
)
386386
]);
387387

388-
let offer = nodes[1].node.create_offer_builder(None).unwrap().build().unwrap();
388+
let offer = nodes[1].offers_handler.create_offer_builder(None).unwrap().build().unwrap();
389389
let payment_id = PaymentId([1; 32]);
390390
nodes[0].node.pay_for_offer(&offer, None, Some(5000), None, payment_id, Retry::Attempts(0), None).unwrap();
391391
let invreq_om = nodes[0].onion_messenger.next_onion_message_for_peer(nodes[1].node.get_our_node_id()).unwrap();

0 commit comments

Comments
 (0)