1use std::sync::{Arc, RwLock};
11
12use bitcoin::secp256k1::PublicKey;
13use lightning::ln::channelmanager::{PaymentId, RecipientOnionFields, Retry, RetryableSendFailure};
14use lightning::routing::router::{PaymentParameters, RouteParameters, RouteParametersConfig};
15use lightning::sign::EntropySource;
16use lightning_types::payment::{PaymentHash, PaymentPreimage};
17
18use crate::config::{Config, LDK_PAYMENT_RETRY_TIMEOUT};
19use crate::error::Error;
20use crate::logger::{log_error, log_info, LdkLogger, Logger};
21use crate::payment::store::{PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus};
22use crate::types::{ChannelManager, CustomTlvRecord, KeysManager, PaymentStore};
23
24const LDK_DEFAULT_FINAL_CLTV_EXPIRY_DELTA: u32 = 144;
26
27pub struct SpontaneousPayment {
33 channel_manager: Arc<ChannelManager>,
34 keys_manager: Arc<KeysManager>,
35 payment_store: Arc<PaymentStore>,
36 config: Arc<Config>,
37 is_running: Arc<RwLock<bool>>,
38 logger: Arc<Logger>,
39}
40
41impl SpontaneousPayment {
42 pub(crate) fn new(
43 channel_manager: Arc<ChannelManager>, keys_manager: Arc<KeysManager>,
44 payment_store: Arc<PaymentStore>, config: Arc<Config>, is_running: Arc<RwLock<bool>>,
45 logger: Arc<Logger>,
46 ) -> Self {
47 Self { channel_manager, keys_manager, payment_store, config, is_running, logger }
48 }
49
50 pub fn send(
55 &self, amount_msat: u64, node_id: PublicKey,
56 route_parameters: Option<RouteParametersConfig>,
57 ) -> Result<PaymentId, Error> {
58 self.send_inner(amount_msat, node_id, route_parameters, None, None)
59 }
60
61 pub fn send_with_custom_tlvs(
63 &self, amount_msat: u64, node_id: PublicKey,
64 route_parameters: Option<RouteParametersConfig>, custom_tlvs: Vec<CustomTlvRecord>,
65 ) -> Result<PaymentId, Error> {
66 self.send_inner(amount_msat, node_id, route_parameters, Some(custom_tlvs), None)
67 }
68
69 pub fn send_with_preimage(
71 &self, amount_msat: u64, node_id: PublicKey, preimage: PaymentPreimage,
72 route_parameters: Option<RouteParametersConfig>,
73 ) -> Result<PaymentId, Error> {
74 self.send_inner(amount_msat, node_id, route_parameters, None, Some(preimage))
75 }
76
77 pub fn send_with_preimage_and_custom_tlvs(
79 &self, amount_msat: u64, node_id: PublicKey, custom_tlvs: Vec<CustomTlvRecord>,
80 preimage: PaymentPreimage, route_parameters: Option<RouteParametersConfig>,
81 ) -> Result<PaymentId, Error> {
82 self.send_inner(amount_msat, node_id, route_parameters, Some(custom_tlvs), Some(preimage))
83 }
84
85 fn send_inner(
86 &self, amount_msat: u64, node_id: PublicKey,
87 route_parameters: Option<RouteParametersConfig>, custom_tlvs: Option<Vec<CustomTlvRecord>>,
88 preimage: Option<PaymentPreimage>,
89 ) -> Result<PaymentId, Error> {
90 if !*self.is_running.read().unwrap() {
91 return Err(Error::NotRunning);
92 }
93
94 let payment_preimage = preimage
95 .unwrap_or_else(|| PaymentPreimage(self.keys_manager.get_secure_random_bytes()));
96
97 let payment_hash = PaymentHash::from(payment_preimage);
98 let payment_id = PaymentId(payment_hash.0);
99
100 if let Some(payment) = self.payment_store.get(&payment_id) {
101 if payment.status == PaymentStatus::Pending
102 || payment.status == PaymentStatus::Succeeded
103 {
104 log_error!(self.logger, "Payment error: must not send duplicate payments.");
105 return Err(Error::DuplicatePayment);
106 }
107 }
108
109 let mut route_params = RouteParameters::from_payment_params_and_value(
110 PaymentParameters::from_node_id(node_id, LDK_DEFAULT_FINAL_CLTV_EXPIRY_DELTA),
111 amount_msat,
112 );
113
114 if let Some(RouteParametersConfig {
115 max_total_routing_fee_msat,
116 max_total_cltv_expiry_delta,
117 max_path_count,
118 max_channel_saturation_power_of_half,
119 }) = route_parameters.as_ref().or(self.config.route_parameters.as_ref())
120 {
121 route_params.max_total_routing_fee_msat = *max_total_routing_fee_msat;
122 route_params.payment_params.max_total_cltv_expiry_delta = *max_total_cltv_expiry_delta;
123 route_params.payment_params.max_path_count = *max_path_count;
124 route_params.payment_params.max_channel_saturation_power_of_half =
125 *max_channel_saturation_power_of_half;
126 }
127
128 let recipient_fields = match custom_tlvs {
129 Some(tlvs) => RecipientOnionFields::spontaneous_empty()
130 .with_custom_tlvs(tlvs.into_iter().map(|tlv| (tlv.type_num, tlv.value)).collect())
131 .map_err(|e| {
132 log_error!(self.logger, "Failed to send payment with custom TLVs: {:?}", e);
133 Error::InvalidCustomTlvs
134 })?,
135 None => RecipientOnionFields::spontaneous_empty(),
136 };
137
138 match self.channel_manager.send_spontaneous_payment(
139 Some(payment_preimage),
140 recipient_fields,
141 PaymentId(payment_hash.0),
142 route_params,
143 Retry::Timeout(LDK_PAYMENT_RETRY_TIMEOUT),
144 ) {
145 Ok(_hash) => {
146 log_info!(self.logger, "Initiated sending {}msat to {}.", amount_msat, node_id);
147
148 let kind = PaymentKind::Spontaneous {
149 hash: payment_hash,
150 preimage: Some(payment_preimage),
151 };
152 let payment = PaymentDetails::new(
153 payment_id,
154 kind,
155 Some(amount_msat),
156 None,
157 PaymentDirection::Outbound,
158 PaymentStatus::Pending,
159 );
160 self.payment_store.insert(payment)?;
161
162 Ok(payment_id)
163 },
164 Err(e) => {
165 log_error!(self.logger, "Failed to send payment: {:?}", e);
166
167 match e {
168 RetryableSendFailure::DuplicatePayment => Err(Error::DuplicatePayment),
169 _ => {
170 let kind = PaymentKind::Spontaneous {
171 hash: payment_hash,
172 preimage: Some(payment_preimage),
173 };
174 let payment = PaymentDetails::new(
175 payment_id,
176 kind,
177 Some(amount_msat),
178 None,
179 PaymentDirection::Outbound,
180 PaymentStatus::Failed,
181 );
182
183 self.payment_store.insert(payment)?;
184 Err(Error::PaymentSendingFailed)
185 },
186 }
187 },
188 }
189 }
190
191 pub fn send_probes(&self, amount_msat: u64, node_id: PublicKey) -> Result<(), Error> {
198 if !*self.is_running.read().unwrap() {
199 return Err(Error::NotRunning);
200 }
201
202 let liquidity_limit_multiplier = Some(self.config.probing_liquidity_limit_multiplier);
203
204 self.channel_manager
205 .send_spontaneous_preflight_probes(
206 node_id,
207 amount_msat,
208 LDK_DEFAULT_FINAL_CLTV_EXPIRY_DELTA,
209 liquidity_limit_multiplier,
210 )
211 .map_err(|e| {
212 log_error!(self.logger, "Failed to send payment probes: {:?}", e);
213 Error::ProbeSendingFailed
214 })?;
215
216 Ok(())
217 }
218}