-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathspontaneous.rs
More file actions
229 lines (202 loc) · 7.7 KB
/
spontaneous.rs
File metadata and controls
229 lines (202 loc) · 7.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// This file is Copyright its original authors, visible in version control history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. You may not use this file except in
// accordance with one or both of these licenses.
//! Holds a payment handler allowing to send spontaneous ("keysend") payments.
use std::sync::{Arc, RwLock};
use bitcoin::secp256k1::PublicKey;
use lightning::ln::channelmanager::PaymentId;
use lightning::ln::outbound_payment::{
RecipientCustomTlvs, RecipientOnionFields, RetryableSendFailure,
};
use lightning::routing::router::{PaymentParameters, RouteParameters, RouteParametersConfig};
use lightning::sign::EntropySource;
use lightning_types::payment::{PaymentHash, PaymentPreimage};
use crate::config::Config;
use crate::error::Error;
use crate::logger::{log_error, log_info, LdkLogger, Logger};
use crate::payment::store::{PaymentDetails, PaymentDirection, PaymentKind, PaymentStatus};
use crate::types::{ChannelManager, CustomTlvRecord, KeysManager, PaymentStore};
// The default `final_cltv_expiry_delta` we apply when not set.
const LDK_DEFAULT_FINAL_CLTV_EXPIRY_DELTA: u32 = 144;
/// A payment handler allowing to send spontaneous ("keysend") payments.
///
/// Should be retrieved by calling [`Node::spontaneous_payment`].
///
/// [`Node::spontaneous_payment`]: crate::Node::spontaneous_payment
#[cfg_attr(feature = "uniffi", derive(uniffi::Object))]
pub struct SpontaneousPayment {
channel_manager: Arc<ChannelManager>,
keys_manager: Arc<KeysManager>,
payment_store: Arc<PaymentStore>,
config: Arc<Config>,
is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
}
impl SpontaneousPayment {
pub(crate) fn new(
channel_manager: Arc<ChannelManager>, keys_manager: Arc<KeysManager>,
payment_store: Arc<PaymentStore>, config: Arc<Config>, is_running: Arc<RwLock<bool>>,
logger: Arc<Logger>,
) -> Self {
Self { channel_manager, keys_manager, payment_store, config, is_running, logger }
}
fn send_inner(
&self, amount_msat: u64, node_id: PublicKey,
route_parameters: Option<RouteParametersConfig>, custom_tlvs: Option<Vec<CustomTlvRecord>>,
preimage: Option<PaymentPreimage>,
) -> Result<PaymentId, Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
}
let payment_preimage = preimage
.unwrap_or_else(|| PaymentPreimage(self.keys_manager.get_secure_random_bytes()));
let payment_hash = PaymentHash::from(payment_preimage);
let payment_id = PaymentId(payment_hash.0);
if let Some(payment) = self.payment_store.get(&payment_id) {
if payment.status == PaymentStatus::Pending
|| payment.status == PaymentStatus::Succeeded
{
log_error!(self.logger, "Payment error: must not send duplicate payments.");
return Err(Error::DuplicatePayment);
}
}
let mut route_params = RouteParameters::from_payment_params_and_value(
PaymentParameters::from_node_id(node_id, LDK_DEFAULT_FINAL_CLTV_EXPIRY_DELTA),
amount_msat,
);
if let Some(RouteParametersConfig {
max_total_routing_fee_msat,
max_total_cltv_expiry_delta,
max_path_count,
max_channel_saturation_power_of_half,
}) = route_parameters.as_ref().or(self.config.route_parameters.as_ref())
{
route_params.max_total_routing_fee_msat = *max_total_routing_fee_msat;
route_params.payment_params.max_total_cltv_expiry_delta = *max_total_cltv_expiry_delta;
route_params.payment_params.max_path_count = *max_path_count;
route_params.payment_params.max_channel_saturation_power_of_half =
*max_channel_saturation_power_of_half;
}
let mut recipient_fields = RecipientOnionFields::spontaneous_empty(amount_msat);
if let Some(tlvs) = custom_tlvs {
let tlvs_vec = tlvs.into_iter().map(|tlv| (tlv.type_num, tlv.value)).collect();
recipient_fields = recipient_fields.with_custom_tlvs(
RecipientCustomTlvs::new(tlvs_vec).map_err(|()| {
log_error!(
self.logger,
"Attempted to set payment custom TLVs to a spec-defined value"
);
Error::InvalidCustomTlvs
})?,
);
}
match self.channel_manager.send_spontaneous_payment(
Some(payment_preimage),
recipient_fields,
PaymentId(payment_hash.0),
route_params,
self.config.payment_retry_strategy.into(),
) {
Ok(_hash) => {
log_info!(self.logger, "Initiated sending {}msat to {}.", amount_msat, node_id);
let kind = PaymentKind::Spontaneous {
hash: payment_hash,
preimage: Some(payment_preimage),
};
let payment = PaymentDetails::new(
payment_id,
kind,
Some(amount_msat),
None,
PaymentDirection::Outbound,
PaymentStatus::Pending,
);
self.payment_store.insert(payment)?;
Ok(payment_id)
},
Err(e) => {
log_error!(self.logger, "Failed to send payment: {:?}", e);
match e {
RetryableSendFailure::DuplicatePayment => Err(Error::DuplicatePayment),
_ => {
let kind = PaymentKind::Spontaneous {
hash: payment_hash,
preimage: Some(payment_preimage),
};
let payment = PaymentDetails::new(
payment_id,
kind,
Some(amount_msat),
None,
PaymentDirection::Outbound,
PaymentStatus::Failed,
);
self.payment_store.insert(payment)?;
Err(Error::PaymentSendingFailed)
},
}
},
}
}
}
#[cfg_attr(feature = "uniffi", uniffi::export)]
impl SpontaneousPayment {
/// Send a spontaneous aka. "keysend", payment.
///
/// If `route_parameters` are provided they will override the default as well as the
/// node-wide parameters configured via [`Config::route_parameters`] on a per-field basis.
pub fn send(
&self, amount_msat: u64, node_id: PublicKey,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
self.send_inner(amount_msat, node_id, route_parameters, None, None)
}
/// Send a spontaneous payment including a list of custom TLVs.
pub fn send_with_custom_tlvs(
&self, amount_msat: u64, node_id: PublicKey,
route_parameters: Option<RouteParametersConfig>, custom_tlvs: Vec<CustomTlvRecord>,
) -> Result<PaymentId, Error> {
self.send_inner(amount_msat, node_id, route_parameters, Some(custom_tlvs), None)
}
/// Send a spontaneous payment with custom preimage
pub fn send_with_preimage(
&self, amount_msat: u64, node_id: PublicKey, preimage: PaymentPreimage,
route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
self.send_inner(amount_msat, node_id, route_parameters, None, Some(preimage))
}
/// Send a spontaneous payment with custom preimage including a list of custom TLVs.
pub fn send_with_preimage_and_custom_tlvs(
&self, amount_msat: u64, node_id: PublicKey, custom_tlvs: Vec<CustomTlvRecord>,
preimage: PaymentPreimage, route_parameters: Option<RouteParametersConfig>,
) -> Result<PaymentId, Error> {
self.send_inner(amount_msat, node_id, route_parameters, Some(custom_tlvs), Some(preimage))
}
/// Sends payment probes over all paths of a route that would be used to pay the given
/// amount to the given `node_id`.
///
/// See [`Bolt11Payment::send_probes`] for more information.
///
/// [`Bolt11Payment::send_probes`]: crate::payment::Bolt11Payment
pub fn send_probes(&self, amount_msat: u64, node_id: PublicKey) -> Result<(), Error> {
if !*self.is_running.read().unwrap() {
return Err(Error::NotRunning);
}
let liquidity_limit_multiplier = Some(self.config.probing_liquidity_limit_multiplier);
self.channel_manager
.send_spontaneous_preflight_probes(
node_id,
amount_msat,
LDK_DEFAULT_FINAL_CLTV_EXPIRY_DELTA,
liquidity_limit_multiplier,
)
.map_err(|e| {
log_error!(self.logger, "Failed to send payment probes: {:?}", e);
Error::ProbeSendingFailed
})?;
Ok(())
}
}