1a29d9defd5961c4966860408a7de7d9da379791
[ldk-c-bindings] / lightning-c-bindings / src / lightning / ln / channelmanager.rs
1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
3 //
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
8
9 //! The top-level channel management and payment tracking stuff lives here.
10 //!
11 //! The [`ChannelManager`] is the main chunk of logic implementing the lightning protocol and is
12 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
13 //! upon reconnect to the relevant peer(s).
14 //!
15 //! It does not manage routing logic (see [`Router`] for that) nor does it manage constructing
16 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
17 //! imply it needs to fail HTLCs/payments/channels it manages).
18
19 use alloc::str::FromStr;
20 use alloc::string::String;
21 use core::ffi::c_void;
22 use core::convert::Infallible;
23 use bitcoin::hashes::Hash;
24 use crate::c_types::*;
25 #[cfg(feature="no-std")]
26 use alloc::{vec::Vec, boxed::Box};
27
28 /// Information about where a received HTLC('s onion) has indicated the HTLC should go.
29 #[derive(Clone)]
30 #[must_use]
31 #[repr(C)]
32 pub enum PendingHTLCRouting {
33         /// An HTLC which should be forwarded on to another node.
34         Forward {
35                 /// The onion which should be included in the forwarded HTLC, telling the next hop what to
36                 /// do with the HTLC.
37                 onion_packet: crate::lightning::ln::msgs::OnionPacket,
38                 /// The short channel ID of the channel which we were instructed to forward this HTLC to.
39                 ///
40                 /// This could be a real on-chain SCID, an SCID alias, or some other SCID which has meaning
41                 /// to the receiving node, such as one returned from
42                 /// [`ChannelManager::get_intercept_scid`] or [`ChannelManager::get_phantom_scid`].
43                 short_channel_id: u64,
44                 /// Set if this HTLC is being forwarded within a blinded path.
45                 ///
46                 /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None
47                 blinded: crate::lightning::ln::channelmanager::BlindedForward,
48         },
49         /// The onion indicates that this is a payment for an invoice (supposedly) generated by us.
50         ///
51         /// Note that at this point, we have not checked that the invoice being paid was actually
52         /// generated by us, but rather it's claiming to pay an invoice of ours.
53         Receive {
54                 /// Information about the amount the sender intended to pay and (potential) proof that this
55                 /// is a payment for an invoice we generated. This proof of payment is is also used for
56                 /// linking MPP parts of a larger payment.
57                 payment_data: crate::lightning::ln::msgs::FinalOnionHopData,
58                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
59                 ///
60                 /// For HTLCs received by LDK, this will ultimately be exposed in
61                 /// [`Event::PaymentClaimable::onion_fields`] as
62                 /// [`RecipientOnionFields::payment_metadata`].
63                 payment_metadata: crate::c_types::derived::COption_CVec_u8ZZ,
64                 /// The context of the payment included by the recipient in a blinded path, or `None` if a
65                 /// blinded path was not used.
66                 ///
67                 /// Used in part to determine the [`events::PaymentPurpose`].
68                 payment_context: crate::c_types::derived::COption_PaymentContextZ,
69                 /// CLTV expiry of the received HTLC.
70                 ///
71                 /// Used to track when we should expire pending HTLCs that go unclaimed.
72                 incoming_cltv_expiry: u32,
73                 /// If the onion had forwarding instructions to one of our phantom node SCIDs, this will
74                 /// provide the onion shared secret used to decrypt the next level of forwarding
75                 /// instructions.
76                 ///
77                 /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None
78                 phantom_shared_secret: crate::c_types::ThirtyTwoBytes,
79                 /// Custom TLVs which were set by the sender.
80                 ///
81                 /// For HTLCs received by LDK, this will ultimately be exposed in
82                 /// [`Event::PaymentClaimable::onion_fields`] as
83                 /// [`RecipientOnionFields::custom_tlvs`].
84                 custom_tlvs: crate::c_types::derived::CVec_C2Tuple_u64CVec_u8ZZZ,
85                 /// Set if this HTLC is the final hop in a multi-hop blinded path.
86                 requires_blinded_error: bool,
87         },
88         /// The onion indicates that this is for payment to us but which contains the preimage for
89         /// claiming included, and is unrelated to any invoice we'd previously generated (aka a
90         /// \"keysend\" or \"spontaneous\" payment).
91         ReceiveKeysend {
92                 /// Information about the amount the sender intended to pay and possibly a token to
93                 /// associate MPP parts of a larger payment.
94                 ///
95                 /// This will only be filled in if receiving MPP keysend payments is enabled, and it being
96                 /// present will cause deserialization to fail on versions of LDK prior to 0.0.116.
97                 ///
98                 /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None
99                 payment_data: crate::lightning::ln::msgs::FinalOnionHopData,
100                 /// Preimage for this onion payment. This preimage is provided by the sender and will be
101                 /// used to settle the spontaneous payment.
102                 payment_preimage: crate::c_types::ThirtyTwoBytes,
103                 /// Additional data which we (allegedly) instructed the sender to include in the onion.
104                 ///
105                 /// For HTLCs received by LDK, this will ultimately bubble back up as
106                 /// [`RecipientOnionFields::payment_metadata`].
107                 payment_metadata: crate::c_types::derived::COption_CVec_u8ZZ,
108                 /// CLTV expiry of the received HTLC.
109                 ///
110                 /// Used to track when we should expire pending HTLCs that go unclaimed.
111                 incoming_cltv_expiry: u32,
112                 /// Custom TLVs which were set by the sender.
113                 ///
114                 /// For HTLCs received by LDK, these will ultimately bubble back up as
115                 /// [`RecipientOnionFields::custom_tlvs`].
116                 custom_tlvs: crate::c_types::derived::CVec_C2Tuple_u64CVec_u8ZZZ,
117                 /// Set if this HTLC is the final hop in a multi-hop blinded path.
118                 requires_blinded_error: bool,
119         },
120 }
121 use lightning::ln::channelmanager::PendingHTLCRouting as PendingHTLCRoutingImport;
122 pub(crate) type nativePendingHTLCRouting = PendingHTLCRoutingImport;
123
124 impl PendingHTLCRouting {
125         #[allow(unused)]
126         pub(crate) fn to_native(&self) -> nativePendingHTLCRouting {
127                 match self {
128                         PendingHTLCRouting::Forward {ref onion_packet, ref short_channel_id, ref blinded, } => {
129                                 let mut onion_packet_nonref = Clone::clone(onion_packet);
130                                 let mut short_channel_id_nonref = Clone::clone(short_channel_id);
131                                 let mut blinded_nonref = Clone::clone(blinded);
132                                 let mut local_blinded_nonref = if blinded_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(blinded_nonref.take_inner()) } }) };
133                                 nativePendingHTLCRouting::Forward {
134                                         onion_packet: *unsafe { Box::from_raw(onion_packet_nonref.take_inner()) },
135                                         short_channel_id: short_channel_id_nonref,
136                                         blinded: local_blinded_nonref,
137                                 }
138                         },
139                         PendingHTLCRouting::Receive {ref payment_data, ref payment_metadata, ref payment_context, ref incoming_cltv_expiry, ref phantom_shared_secret, ref custom_tlvs, ref requires_blinded_error, } => {
140                                 let mut payment_data_nonref = Clone::clone(payment_data);
141                                 let mut payment_metadata_nonref = Clone::clone(payment_metadata);
142                                 let mut local_payment_metadata_nonref = { /*payment_metadata_nonref*/ let payment_metadata_nonref_opt = payment_metadata_nonref; if payment_metadata_nonref_opt.is_none() { None } else { Some({ { let mut local_payment_metadata_nonref_0 = Vec::new(); for mut item in { payment_metadata_nonref_opt.take() }.into_rust().drain(..) { local_payment_metadata_nonref_0.push( { item }); }; local_payment_metadata_nonref_0 }})} };
143                                 let mut payment_context_nonref = Clone::clone(payment_context);
144                                 let mut local_payment_context_nonref = { /*payment_context_nonref*/ let payment_context_nonref_opt = payment_context_nonref; if payment_context_nonref_opt.is_none() { None } else { Some({ { { payment_context_nonref_opt.take() }.into_native() }})} };
145                                 let mut incoming_cltv_expiry_nonref = Clone::clone(incoming_cltv_expiry);
146                                 let mut phantom_shared_secret_nonref = Clone::clone(phantom_shared_secret);
147                                 let mut local_phantom_shared_secret_nonref = if phantom_shared_secret_nonref.data == [0; 32] { None } else { Some( { phantom_shared_secret_nonref.data }) };
148                                 let mut custom_tlvs_nonref = Clone::clone(custom_tlvs);
149                                 let mut local_custom_tlvs_nonref = Vec::new(); for mut item in custom_tlvs_nonref.into_rust().drain(..) { local_custom_tlvs_nonref.push( { let (mut orig_custom_tlvs_nonref_0_0, mut orig_custom_tlvs_nonref_0_1) = item.to_rust(); let mut local_orig_custom_tlvs_nonref_0_1 = Vec::new(); for mut item in orig_custom_tlvs_nonref_0_1.into_rust().drain(..) { local_orig_custom_tlvs_nonref_0_1.push( { item }); }; let mut local_custom_tlvs_nonref_0 = (orig_custom_tlvs_nonref_0_0, local_orig_custom_tlvs_nonref_0_1); local_custom_tlvs_nonref_0 }); };
150                                 let mut requires_blinded_error_nonref = Clone::clone(requires_blinded_error);
151                                 nativePendingHTLCRouting::Receive {
152                                         payment_data: *unsafe { Box::from_raw(payment_data_nonref.take_inner()) },
153                                         payment_metadata: local_payment_metadata_nonref,
154                                         payment_context: local_payment_context_nonref,
155                                         incoming_cltv_expiry: incoming_cltv_expiry_nonref,
156                                         phantom_shared_secret: local_phantom_shared_secret_nonref,
157                                         custom_tlvs: local_custom_tlvs_nonref,
158                                         requires_blinded_error: requires_blinded_error_nonref,
159                                 }
160                         },
161                         PendingHTLCRouting::ReceiveKeysend {ref payment_data, ref payment_preimage, ref payment_metadata, ref incoming_cltv_expiry, ref custom_tlvs, ref requires_blinded_error, } => {
162                                 let mut payment_data_nonref = Clone::clone(payment_data);
163                                 let mut local_payment_data_nonref = if payment_data_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(payment_data_nonref.take_inner()) } }) };
164                                 let mut payment_preimage_nonref = Clone::clone(payment_preimage);
165                                 let mut payment_metadata_nonref = Clone::clone(payment_metadata);
166                                 let mut local_payment_metadata_nonref = { /*payment_metadata_nonref*/ let payment_metadata_nonref_opt = payment_metadata_nonref; if payment_metadata_nonref_opt.is_none() { None } else { Some({ { let mut local_payment_metadata_nonref_0 = Vec::new(); for mut item in { payment_metadata_nonref_opt.take() }.into_rust().drain(..) { local_payment_metadata_nonref_0.push( { item }); }; local_payment_metadata_nonref_0 }})} };
167                                 let mut incoming_cltv_expiry_nonref = Clone::clone(incoming_cltv_expiry);
168                                 let mut custom_tlvs_nonref = Clone::clone(custom_tlvs);
169                                 let mut local_custom_tlvs_nonref = Vec::new(); for mut item in custom_tlvs_nonref.into_rust().drain(..) { local_custom_tlvs_nonref.push( { let (mut orig_custom_tlvs_nonref_0_0, mut orig_custom_tlvs_nonref_0_1) = item.to_rust(); let mut local_orig_custom_tlvs_nonref_0_1 = Vec::new(); for mut item in orig_custom_tlvs_nonref_0_1.into_rust().drain(..) { local_orig_custom_tlvs_nonref_0_1.push( { item }); }; let mut local_custom_tlvs_nonref_0 = (orig_custom_tlvs_nonref_0_0, local_orig_custom_tlvs_nonref_0_1); local_custom_tlvs_nonref_0 }); };
170                                 let mut requires_blinded_error_nonref = Clone::clone(requires_blinded_error);
171                                 nativePendingHTLCRouting::ReceiveKeysend {
172                                         payment_data: local_payment_data_nonref,
173                                         payment_preimage: ::lightning::ln::types::PaymentPreimage(payment_preimage_nonref.data),
174                                         payment_metadata: local_payment_metadata_nonref,
175                                         incoming_cltv_expiry: incoming_cltv_expiry_nonref,
176                                         custom_tlvs: local_custom_tlvs_nonref,
177                                         requires_blinded_error: requires_blinded_error_nonref,
178                                 }
179                         },
180                 }
181         }
182         #[allow(unused)]
183         pub(crate) fn into_native(self) -> nativePendingHTLCRouting {
184                 match self {
185                         PendingHTLCRouting::Forward {mut onion_packet, mut short_channel_id, mut blinded, } => {
186                                 let mut local_blinded = if blinded.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(blinded.take_inner()) } }) };
187                                 nativePendingHTLCRouting::Forward {
188                                         onion_packet: *unsafe { Box::from_raw(onion_packet.take_inner()) },
189                                         short_channel_id: short_channel_id,
190                                         blinded: local_blinded,
191                                 }
192                         },
193                         PendingHTLCRouting::Receive {mut payment_data, mut payment_metadata, mut payment_context, mut incoming_cltv_expiry, mut phantom_shared_secret, mut custom_tlvs, mut requires_blinded_error, } => {
194                                 let mut local_payment_metadata = { /*payment_metadata*/ let payment_metadata_opt = payment_metadata; if payment_metadata_opt.is_none() { None } else { Some({ { let mut local_payment_metadata_0 = Vec::new(); for mut item in { payment_metadata_opt.take() }.into_rust().drain(..) { local_payment_metadata_0.push( { item }); }; local_payment_metadata_0 }})} };
195                                 let mut local_payment_context = { /*payment_context*/ let payment_context_opt = payment_context; if payment_context_opt.is_none() { None } else { Some({ { { payment_context_opt.take() }.into_native() }})} };
196                                 let mut local_phantom_shared_secret = if phantom_shared_secret.data == [0; 32] { None } else { Some( { phantom_shared_secret.data }) };
197                                 let mut local_custom_tlvs = Vec::new(); for mut item in custom_tlvs.into_rust().drain(..) { local_custom_tlvs.push( { let (mut orig_custom_tlvs_0_0, mut orig_custom_tlvs_0_1) = item.to_rust(); let mut local_orig_custom_tlvs_0_1 = Vec::new(); for mut item in orig_custom_tlvs_0_1.into_rust().drain(..) { local_orig_custom_tlvs_0_1.push( { item }); }; let mut local_custom_tlvs_0 = (orig_custom_tlvs_0_0, local_orig_custom_tlvs_0_1); local_custom_tlvs_0 }); };
198                                 nativePendingHTLCRouting::Receive {
199                                         payment_data: *unsafe { Box::from_raw(payment_data.take_inner()) },
200                                         payment_metadata: local_payment_metadata,
201                                         payment_context: local_payment_context,
202                                         incoming_cltv_expiry: incoming_cltv_expiry,
203                                         phantom_shared_secret: local_phantom_shared_secret,
204                                         custom_tlvs: local_custom_tlvs,
205                                         requires_blinded_error: requires_blinded_error,
206                                 }
207                         },
208                         PendingHTLCRouting::ReceiveKeysend {mut payment_data, mut payment_preimage, mut payment_metadata, mut incoming_cltv_expiry, mut custom_tlvs, mut requires_blinded_error, } => {
209                                 let mut local_payment_data = if payment_data.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(payment_data.take_inner()) } }) };
210                                 let mut local_payment_metadata = { /*payment_metadata*/ let payment_metadata_opt = payment_metadata; if payment_metadata_opt.is_none() { None } else { Some({ { let mut local_payment_metadata_0 = Vec::new(); for mut item in { payment_metadata_opt.take() }.into_rust().drain(..) { local_payment_metadata_0.push( { item }); }; local_payment_metadata_0 }})} };
211                                 let mut local_custom_tlvs = Vec::new(); for mut item in custom_tlvs.into_rust().drain(..) { local_custom_tlvs.push( { let (mut orig_custom_tlvs_0_0, mut orig_custom_tlvs_0_1) = item.to_rust(); let mut local_orig_custom_tlvs_0_1 = Vec::new(); for mut item in orig_custom_tlvs_0_1.into_rust().drain(..) { local_orig_custom_tlvs_0_1.push( { item }); }; let mut local_custom_tlvs_0 = (orig_custom_tlvs_0_0, local_orig_custom_tlvs_0_1); local_custom_tlvs_0 }); };
212                                 nativePendingHTLCRouting::ReceiveKeysend {
213                                         payment_data: local_payment_data,
214                                         payment_preimage: ::lightning::ln::types::PaymentPreimage(payment_preimage.data),
215                                         payment_metadata: local_payment_metadata,
216                                         incoming_cltv_expiry: incoming_cltv_expiry,
217                                         custom_tlvs: local_custom_tlvs,
218                                         requires_blinded_error: requires_blinded_error,
219                                 }
220                         },
221                 }
222         }
223         #[allow(unused)]
224         pub(crate) fn from_native(native: &PendingHTLCRoutingImport) -> Self {
225                 let native = unsafe { &*(native as *const _ as *const c_void as *const nativePendingHTLCRouting) };
226                 match native {
227                         nativePendingHTLCRouting::Forward {ref onion_packet, ref short_channel_id, ref blinded, } => {
228                                 let mut onion_packet_nonref = Clone::clone(onion_packet);
229                                 let mut short_channel_id_nonref = Clone::clone(short_channel_id);
230                                 let mut blinded_nonref = Clone::clone(blinded);
231                                 let mut local_blinded_nonref = crate::lightning::ln::channelmanager::BlindedForward { inner: if blinded_nonref.is_none() { core::ptr::null_mut() } else {  { ObjOps::heap_alloc((blinded_nonref.unwrap())) } }, is_owned: true };
232                                 PendingHTLCRouting::Forward {
233                                         onion_packet: crate::lightning::ln::msgs::OnionPacket { inner: ObjOps::heap_alloc(onion_packet_nonref), is_owned: true },
234                                         short_channel_id: short_channel_id_nonref,
235                                         blinded: local_blinded_nonref,
236                                 }
237                         },
238                         nativePendingHTLCRouting::Receive {ref payment_data, ref payment_metadata, ref payment_context, ref incoming_cltv_expiry, ref phantom_shared_secret, ref custom_tlvs, ref requires_blinded_error, } => {
239                                 let mut payment_data_nonref = Clone::clone(payment_data);
240                                 let mut payment_metadata_nonref = Clone::clone(payment_metadata);
241                                 let mut local_payment_metadata_nonref = if payment_metadata_nonref.is_none() { crate::c_types::derived::COption_CVec_u8ZZ::None } else { crate::c_types::derived::COption_CVec_u8ZZ::Some( { let mut local_payment_metadata_nonref_0 = Vec::new(); for mut item in payment_metadata_nonref.unwrap().drain(..) { local_payment_metadata_nonref_0.push( { item }); }; local_payment_metadata_nonref_0.into() }) };
242                                 let mut payment_context_nonref = Clone::clone(payment_context);
243                                 let mut local_payment_context_nonref = if payment_context_nonref.is_none() { crate::c_types::derived::COption_PaymentContextZ::None } else { crate::c_types::derived::COption_PaymentContextZ::Some( { crate::lightning::blinded_path::payment::PaymentContext::native_into(payment_context_nonref.unwrap()) }) };
244                                 let mut incoming_cltv_expiry_nonref = Clone::clone(incoming_cltv_expiry);
245                                 let mut phantom_shared_secret_nonref = Clone::clone(phantom_shared_secret);
246                                 let mut local_phantom_shared_secret_nonref = if phantom_shared_secret_nonref.is_none() { crate::c_types::ThirtyTwoBytes { data: [0; 32] } } else {  { crate::c_types::ThirtyTwoBytes { data: (phantom_shared_secret_nonref.unwrap()) } } };
247                                 let mut custom_tlvs_nonref = Clone::clone(custom_tlvs);
248                                 let mut local_custom_tlvs_nonref = Vec::new(); for mut item in custom_tlvs_nonref.drain(..) { local_custom_tlvs_nonref.push( { let (mut orig_custom_tlvs_nonref_0_0, mut orig_custom_tlvs_nonref_0_1) = item; let mut local_orig_custom_tlvs_nonref_0_1 = Vec::new(); for mut item in orig_custom_tlvs_nonref_0_1.drain(..) { local_orig_custom_tlvs_nonref_0_1.push( { item }); }; let mut local_custom_tlvs_nonref_0 = (orig_custom_tlvs_nonref_0_0, local_orig_custom_tlvs_nonref_0_1.into()).into(); local_custom_tlvs_nonref_0 }); };
249                                 let mut requires_blinded_error_nonref = Clone::clone(requires_blinded_error);
250                                 PendingHTLCRouting::Receive {
251                                         payment_data: crate::lightning::ln::msgs::FinalOnionHopData { inner: ObjOps::heap_alloc(payment_data_nonref), is_owned: true },
252                                         payment_metadata: local_payment_metadata_nonref,
253                                         payment_context: local_payment_context_nonref,
254                                         incoming_cltv_expiry: incoming_cltv_expiry_nonref,
255                                         phantom_shared_secret: local_phantom_shared_secret_nonref,
256                                         custom_tlvs: local_custom_tlvs_nonref.into(),
257                                         requires_blinded_error: requires_blinded_error_nonref,
258                                 }
259                         },
260                         nativePendingHTLCRouting::ReceiveKeysend {ref payment_data, ref payment_preimage, ref payment_metadata, ref incoming_cltv_expiry, ref custom_tlvs, ref requires_blinded_error, } => {
261                                 let mut payment_data_nonref = Clone::clone(payment_data);
262                                 let mut local_payment_data_nonref = crate::lightning::ln::msgs::FinalOnionHopData { inner: if payment_data_nonref.is_none() { core::ptr::null_mut() } else {  { ObjOps::heap_alloc((payment_data_nonref.unwrap())) } }, is_owned: true };
263                                 let mut payment_preimage_nonref = Clone::clone(payment_preimage);
264                                 let mut payment_metadata_nonref = Clone::clone(payment_metadata);
265                                 let mut local_payment_metadata_nonref = if payment_metadata_nonref.is_none() { crate::c_types::derived::COption_CVec_u8ZZ::None } else { crate::c_types::derived::COption_CVec_u8ZZ::Some( { let mut local_payment_metadata_nonref_0 = Vec::new(); for mut item in payment_metadata_nonref.unwrap().drain(..) { local_payment_metadata_nonref_0.push( { item }); }; local_payment_metadata_nonref_0.into() }) };
266                                 let mut incoming_cltv_expiry_nonref = Clone::clone(incoming_cltv_expiry);
267                                 let mut custom_tlvs_nonref = Clone::clone(custom_tlvs);
268                                 let mut local_custom_tlvs_nonref = Vec::new(); for mut item in custom_tlvs_nonref.drain(..) { local_custom_tlvs_nonref.push( { let (mut orig_custom_tlvs_nonref_0_0, mut orig_custom_tlvs_nonref_0_1) = item; let mut local_orig_custom_tlvs_nonref_0_1 = Vec::new(); for mut item in orig_custom_tlvs_nonref_0_1.drain(..) { local_orig_custom_tlvs_nonref_0_1.push( { item }); }; let mut local_custom_tlvs_nonref_0 = (orig_custom_tlvs_nonref_0_0, local_orig_custom_tlvs_nonref_0_1.into()).into(); local_custom_tlvs_nonref_0 }); };
269                                 let mut requires_blinded_error_nonref = Clone::clone(requires_blinded_error);
270                                 PendingHTLCRouting::ReceiveKeysend {
271                                         payment_data: local_payment_data_nonref,
272                                         payment_preimage: crate::c_types::ThirtyTwoBytes { data: payment_preimage_nonref.0 },
273                                         payment_metadata: local_payment_metadata_nonref,
274                                         incoming_cltv_expiry: incoming_cltv_expiry_nonref,
275                                         custom_tlvs: local_custom_tlvs_nonref.into(),
276                                         requires_blinded_error: requires_blinded_error_nonref,
277                                 }
278                         },
279                 }
280         }
281         #[allow(unused)]
282         pub(crate) fn native_into(native: nativePendingHTLCRouting) -> Self {
283                 match native {
284                         nativePendingHTLCRouting::Forward {mut onion_packet, mut short_channel_id, mut blinded, } => {
285                                 let mut local_blinded = crate::lightning::ln::channelmanager::BlindedForward { inner: if blinded.is_none() { core::ptr::null_mut() } else {  { ObjOps::heap_alloc((blinded.unwrap())) } }, is_owned: true };
286                                 PendingHTLCRouting::Forward {
287                                         onion_packet: crate::lightning::ln::msgs::OnionPacket { inner: ObjOps::heap_alloc(onion_packet), is_owned: true },
288                                         short_channel_id: short_channel_id,
289                                         blinded: local_blinded,
290                                 }
291                         },
292                         nativePendingHTLCRouting::Receive {mut payment_data, mut payment_metadata, mut payment_context, mut incoming_cltv_expiry, mut phantom_shared_secret, mut custom_tlvs, mut requires_blinded_error, } => {
293                                 let mut local_payment_metadata = if payment_metadata.is_none() { crate::c_types::derived::COption_CVec_u8ZZ::None } else { crate::c_types::derived::COption_CVec_u8ZZ::Some( { let mut local_payment_metadata_0 = Vec::new(); for mut item in payment_metadata.unwrap().drain(..) { local_payment_metadata_0.push( { item }); }; local_payment_metadata_0.into() }) };
294                                 let mut local_payment_context = if payment_context.is_none() { crate::c_types::derived::COption_PaymentContextZ::None } else { crate::c_types::derived::COption_PaymentContextZ::Some( { crate::lightning::blinded_path::payment::PaymentContext::native_into(payment_context.unwrap()) }) };
295                                 let mut local_phantom_shared_secret = if phantom_shared_secret.is_none() { crate::c_types::ThirtyTwoBytes { data: [0; 32] } } else {  { crate::c_types::ThirtyTwoBytes { data: (phantom_shared_secret.unwrap()) } } };
296                                 let mut local_custom_tlvs = Vec::new(); for mut item in custom_tlvs.drain(..) { local_custom_tlvs.push( { let (mut orig_custom_tlvs_0_0, mut orig_custom_tlvs_0_1) = item; let mut local_orig_custom_tlvs_0_1 = Vec::new(); for mut item in orig_custom_tlvs_0_1.drain(..) { local_orig_custom_tlvs_0_1.push( { item }); }; let mut local_custom_tlvs_0 = (orig_custom_tlvs_0_0, local_orig_custom_tlvs_0_1.into()).into(); local_custom_tlvs_0 }); };
297                                 PendingHTLCRouting::Receive {
298                                         payment_data: crate::lightning::ln::msgs::FinalOnionHopData { inner: ObjOps::heap_alloc(payment_data), is_owned: true },
299                                         payment_metadata: local_payment_metadata,
300                                         payment_context: local_payment_context,
301                                         incoming_cltv_expiry: incoming_cltv_expiry,
302                                         phantom_shared_secret: local_phantom_shared_secret,
303                                         custom_tlvs: local_custom_tlvs.into(),
304                                         requires_blinded_error: requires_blinded_error,
305                                 }
306                         },
307                         nativePendingHTLCRouting::ReceiveKeysend {mut payment_data, mut payment_preimage, mut payment_metadata, mut incoming_cltv_expiry, mut custom_tlvs, mut requires_blinded_error, } => {
308                                 let mut local_payment_data = crate::lightning::ln::msgs::FinalOnionHopData { inner: if payment_data.is_none() { core::ptr::null_mut() } else {  { ObjOps::heap_alloc((payment_data.unwrap())) } }, is_owned: true };
309                                 let mut local_payment_metadata = if payment_metadata.is_none() { crate::c_types::derived::COption_CVec_u8ZZ::None } else { crate::c_types::derived::COption_CVec_u8ZZ::Some( { let mut local_payment_metadata_0 = Vec::new(); for mut item in payment_metadata.unwrap().drain(..) { local_payment_metadata_0.push( { item }); }; local_payment_metadata_0.into() }) };
310                                 let mut local_custom_tlvs = Vec::new(); for mut item in custom_tlvs.drain(..) { local_custom_tlvs.push( { let (mut orig_custom_tlvs_0_0, mut orig_custom_tlvs_0_1) = item; let mut local_orig_custom_tlvs_0_1 = Vec::new(); for mut item in orig_custom_tlvs_0_1.drain(..) { local_orig_custom_tlvs_0_1.push( { item }); }; let mut local_custom_tlvs_0 = (orig_custom_tlvs_0_0, local_orig_custom_tlvs_0_1.into()).into(); local_custom_tlvs_0 }); };
311                                 PendingHTLCRouting::ReceiveKeysend {
312                                         payment_data: local_payment_data,
313                                         payment_preimage: crate::c_types::ThirtyTwoBytes { data: payment_preimage.0 },
314                                         payment_metadata: local_payment_metadata,
315                                         incoming_cltv_expiry: incoming_cltv_expiry,
316                                         custom_tlvs: local_custom_tlvs.into(),
317                                         requires_blinded_error: requires_blinded_error,
318                                 }
319                         },
320                 }
321         }
322 }
323 /// Frees any resources used by the PendingHTLCRouting
324 #[no_mangle]
325 pub extern "C" fn PendingHTLCRouting_free(this_ptr: PendingHTLCRouting) { }
326 /// Creates a copy of the PendingHTLCRouting
327 #[no_mangle]
328 pub extern "C" fn PendingHTLCRouting_clone(orig: &PendingHTLCRouting) -> PendingHTLCRouting {
329         orig.clone()
330 }
331 #[allow(unused)]
332 /// Used only if an object of this type is returned as a trait impl by a method
333 pub(crate) extern "C" fn PendingHTLCRouting_clone_void(this_ptr: *const c_void) -> *mut c_void {
334         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const PendingHTLCRouting)).clone() })) as *mut c_void
335 }
336 #[allow(unused)]
337 /// Used only if an object of this type is returned as a trait impl by a method
338 pub(crate) extern "C" fn PendingHTLCRouting_free_void(this_ptr: *mut c_void) {
339         let _ = unsafe { Box::from_raw(this_ptr as *mut PendingHTLCRouting) };
340 }
341 #[no_mangle]
342 /// Utility method to constructs a new Forward-variant PendingHTLCRouting
343 pub extern "C" fn PendingHTLCRouting_forward(onion_packet: crate::lightning::ln::msgs::OnionPacket, short_channel_id: u64, blinded: crate::lightning::ln::channelmanager::BlindedForward) -> PendingHTLCRouting {
344         PendingHTLCRouting::Forward {
345                 onion_packet,
346                 short_channel_id,
347                 blinded,
348         }
349 }
350 #[no_mangle]
351 /// Utility method to constructs a new Receive-variant PendingHTLCRouting
352 pub extern "C" fn PendingHTLCRouting_receive(payment_data: crate::lightning::ln::msgs::FinalOnionHopData, payment_metadata: crate::c_types::derived::COption_CVec_u8ZZ, payment_context: crate::c_types::derived::COption_PaymentContextZ, incoming_cltv_expiry: u32, phantom_shared_secret: crate::c_types::ThirtyTwoBytes, custom_tlvs: crate::c_types::derived::CVec_C2Tuple_u64CVec_u8ZZZ, requires_blinded_error: bool) -> PendingHTLCRouting {
353         PendingHTLCRouting::Receive {
354                 payment_data,
355                 payment_metadata,
356                 payment_context,
357                 incoming_cltv_expiry,
358                 phantom_shared_secret,
359                 custom_tlvs,
360                 requires_blinded_error,
361         }
362 }
363 #[no_mangle]
364 /// Utility method to constructs a new ReceiveKeysend-variant PendingHTLCRouting
365 pub extern "C" fn PendingHTLCRouting_receive_keysend(payment_data: crate::lightning::ln::msgs::FinalOnionHopData, payment_preimage: crate::c_types::ThirtyTwoBytes, payment_metadata: crate::c_types::derived::COption_CVec_u8ZZ, incoming_cltv_expiry: u32, custom_tlvs: crate::c_types::derived::CVec_C2Tuple_u64CVec_u8ZZZ, requires_blinded_error: bool) -> PendingHTLCRouting {
366         PendingHTLCRouting::ReceiveKeysend {
367                 payment_data,
368                 payment_preimage,
369                 payment_metadata,
370                 incoming_cltv_expiry,
371                 custom_tlvs,
372                 requires_blinded_error,
373         }
374 }
375
376 use lightning::ln::channelmanager::BlindedForward as nativeBlindedForwardImport;
377 pub(crate) type nativeBlindedForward = nativeBlindedForwardImport;
378
379 /// Information used to forward or fail this HTLC that is being forwarded within a blinded path.
380 #[must_use]
381 #[repr(C)]
382 pub struct BlindedForward {
383         /// A pointer to the opaque Rust object.
384
385         /// Nearly everywhere, inner must be non-null, however in places where
386         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
387         pub inner: *mut nativeBlindedForward,
388         /// Indicates that this is the only struct which contains the same pointer.
389
390         /// Rust functions which take ownership of an object provided via an argument require
391         /// this to be true and invalidate the object pointed to by inner.
392         pub is_owned: bool,
393 }
394
395 impl Drop for BlindedForward {
396         fn drop(&mut self) {
397                 if self.is_owned && !<*mut nativeBlindedForward>::is_null(self.inner) {
398                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
399                 }
400         }
401 }
402 /// Frees any resources used by the BlindedForward, if is_owned is set and inner is non-NULL.
403 #[no_mangle]
404 pub extern "C" fn BlindedForward_free(this_obj: BlindedForward) { }
405 #[allow(unused)]
406 /// Used only if an object of this type is returned as a trait impl by a method
407 pub(crate) extern "C" fn BlindedForward_free_void(this_ptr: *mut c_void) {
408         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeBlindedForward) };
409 }
410 #[allow(unused)]
411 impl BlindedForward {
412         pub(crate) fn get_native_ref(&self) -> &'static nativeBlindedForward {
413                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
414         }
415         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBlindedForward {
416                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
417         }
418         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
419         pub(crate) fn take_inner(mut self) -> *mut nativeBlindedForward {
420                 assert!(self.is_owned);
421                 let ret = ObjOps::untweak_ptr(self.inner);
422                 self.inner = core::ptr::null_mut();
423                 ret
424         }
425 }
426 /// The `blinding_point` that was set in the inbound [`msgs::UpdateAddHTLC`], or in the inbound
427 /// onion payload if we're the introduction node. Useful for calculating the next hop's
428 /// [`msgs::UpdateAddHTLC::blinding_point`].
429 #[no_mangle]
430 pub extern "C" fn BlindedForward_get_inbound_blinding_point(this_ptr: &BlindedForward) -> crate::c_types::PublicKey {
431         let mut inner_val = &mut this_ptr.get_native_mut_ref().inbound_blinding_point;
432         crate::c_types::PublicKey::from_rust(&inner_val)
433 }
434 /// The `blinding_point` that was set in the inbound [`msgs::UpdateAddHTLC`], or in the inbound
435 /// onion payload if we're the introduction node. Useful for calculating the next hop's
436 /// [`msgs::UpdateAddHTLC::blinding_point`].
437 #[no_mangle]
438 pub extern "C" fn BlindedForward_set_inbound_blinding_point(this_ptr: &mut BlindedForward, mut val: crate::c_types::PublicKey) {
439         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inbound_blinding_point = val.into_rust();
440 }
441 /// If needed, this determines how this HTLC should be failed backwards, based on whether we are
442 /// the introduction node.
443 #[no_mangle]
444 pub extern "C" fn BlindedForward_get_failure(this_ptr: &BlindedForward) -> crate::lightning::ln::channelmanager::BlindedFailure {
445         let mut inner_val = &mut this_ptr.get_native_mut_ref().failure;
446         crate::lightning::ln::channelmanager::BlindedFailure::from_native(inner_val)
447 }
448 /// If needed, this determines how this HTLC should be failed backwards, based on whether we are
449 /// the introduction node.
450 #[no_mangle]
451 pub extern "C" fn BlindedForward_set_failure(this_ptr: &mut BlindedForward, mut val: crate::lightning::ln::channelmanager::BlindedFailure) {
452         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure = val.into_native();
453 }
454 /// Constructs a new BlindedForward given each field
455 #[must_use]
456 #[no_mangle]
457 pub extern "C" fn BlindedForward_new(mut inbound_blinding_point_arg: crate::c_types::PublicKey, mut failure_arg: crate::lightning::ln::channelmanager::BlindedFailure) -> BlindedForward {
458         BlindedForward { inner: ObjOps::heap_alloc(nativeBlindedForward {
459                 inbound_blinding_point: inbound_blinding_point_arg.into_rust(),
460                 failure: failure_arg.into_native(),
461         }), is_owned: true }
462 }
463 impl Clone for BlindedForward {
464         fn clone(&self) -> Self {
465                 Self {
466                         inner: if <*mut nativeBlindedForward>::is_null(self.inner) { core::ptr::null_mut() } else {
467                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
468                         is_owned: true,
469                 }
470         }
471 }
472 #[allow(unused)]
473 /// Used only if an object of this type is returned as a trait impl by a method
474 pub(crate) extern "C" fn BlindedForward_clone_void(this_ptr: *const c_void) -> *mut c_void {
475         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeBlindedForward)).clone() })) as *mut c_void
476 }
477 #[no_mangle]
478 /// Creates a copy of the BlindedForward
479 pub extern "C" fn BlindedForward_clone(orig: &BlindedForward) -> BlindedForward {
480         orig.clone()
481 }
482 /// Get a string which allows debug introspection of a BlindedForward object
483 pub extern "C" fn BlindedForward_debug_str_void(o: *const c_void) -> Str {
484         alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::BlindedForward }).into()}
485 /// Generates a non-cryptographic 64-bit hash of the BlindedForward.
486 #[no_mangle]
487 pub extern "C" fn BlindedForward_hash(o: &BlindedForward) -> u64 {
488         if o.inner.is_null() { return 0; }
489         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
490         #[allow(deprecated)]
491         let mut hasher = core::hash::SipHasher::new();
492         core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
493         core::hash::Hasher::finish(&hasher)
494 }
495 /// Checks if two BlindedForwards contain equal inner contents.
496 /// This ignores pointers and is_owned flags and looks at the values in fields.
497 /// Two objects with NULL inner values will be considered "equal" here.
498 #[no_mangle]
499 pub extern "C" fn BlindedForward_eq(a: &BlindedForward, b: &BlindedForward) -> bool {
500         if a.inner == b.inner { return true; }
501         if a.inner.is_null() || b.inner.is_null() { return false; }
502         if a.get_native_ref() == b.get_native_ref() { true } else { false }
503 }
504
505 use lightning::ln::channelmanager::PendingHTLCInfo as nativePendingHTLCInfoImport;
506 pub(crate) type nativePendingHTLCInfo = nativePendingHTLCInfoImport;
507
508 /// Information about an incoming HTLC, including the [`PendingHTLCRouting`] describing where it
509 /// should go next.
510 #[must_use]
511 #[repr(C)]
512 pub struct PendingHTLCInfo {
513         /// A pointer to the opaque Rust object.
514
515         /// Nearly everywhere, inner must be non-null, however in places where
516         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
517         pub inner: *mut nativePendingHTLCInfo,
518         /// Indicates that this is the only struct which contains the same pointer.
519
520         /// Rust functions which take ownership of an object provided via an argument require
521         /// this to be true and invalidate the object pointed to by inner.
522         pub is_owned: bool,
523 }
524
525 impl Drop for PendingHTLCInfo {
526         fn drop(&mut self) {
527                 if self.is_owned && !<*mut nativePendingHTLCInfo>::is_null(self.inner) {
528                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
529                 }
530         }
531 }
532 /// Frees any resources used by the PendingHTLCInfo, if is_owned is set and inner is non-NULL.
533 #[no_mangle]
534 pub extern "C" fn PendingHTLCInfo_free(this_obj: PendingHTLCInfo) { }
535 #[allow(unused)]
536 /// Used only if an object of this type is returned as a trait impl by a method
537 pub(crate) extern "C" fn PendingHTLCInfo_free_void(this_ptr: *mut c_void) {
538         let _ = unsafe { Box::from_raw(this_ptr as *mut nativePendingHTLCInfo) };
539 }
540 #[allow(unused)]
541 impl PendingHTLCInfo {
542         pub(crate) fn get_native_ref(&self) -> &'static nativePendingHTLCInfo {
543                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
544         }
545         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePendingHTLCInfo {
546                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
547         }
548         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
549         pub(crate) fn take_inner(mut self) -> *mut nativePendingHTLCInfo {
550                 assert!(self.is_owned);
551                 let ret = ObjOps::untweak_ptr(self.inner);
552                 self.inner = core::ptr::null_mut();
553                 ret
554         }
555 }
556 /// Further routing details based on whether the HTLC is being forwarded or received.
557 #[no_mangle]
558 pub extern "C" fn PendingHTLCInfo_get_routing(this_ptr: &PendingHTLCInfo) -> crate::lightning::ln::channelmanager::PendingHTLCRouting {
559         let mut inner_val = &mut this_ptr.get_native_mut_ref().routing;
560         crate::lightning::ln::channelmanager::PendingHTLCRouting::from_native(inner_val)
561 }
562 /// Further routing details based on whether the HTLC is being forwarded or received.
563 #[no_mangle]
564 pub extern "C" fn PendingHTLCInfo_set_routing(this_ptr: &mut PendingHTLCInfo, mut val: crate::lightning::ln::channelmanager::PendingHTLCRouting) {
565         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.routing = val.into_native();
566 }
567 /// The onion shared secret we build with the sender used to decrypt the onion.
568 ///
569 /// This is later used to encrypt failure packets in the event that the HTLC is failed.
570 #[no_mangle]
571 pub extern "C" fn PendingHTLCInfo_get_incoming_shared_secret(this_ptr: &PendingHTLCInfo) -> *const [u8; 32] {
572         let mut inner_val = &mut this_ptr.get_native_mut_ref().incoming_shared_secret;
573         inner_val
574 }
575 /// The onion shared secret we build with the sender used to decrypt the onion.
576 ///
577 /// This is later used to encrypt failure packets in the event that the HTLC is failed.
578 #[no_mangle]
579 pub extern "C" fn PendingHTLCInfo_set_incoming_shared_secret(this_ptr: &mut PendingHTLCInfo, mut val: crate::c_types::ThirtyTwoBytes) {
580         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.incoming_shared_secret = val.data;
581 }
582 /// Hash of the payment preimage, to lock the payment until the receiver releases the preimage.
583 #[no_mangle]
584 pub extern "C" fn PendingHTLCInfo_get_payment_hash(this_ptr: &PendingHTLCInfo) -> *const [u8; 32] {
585         let mut inner_val = &mut this_ptr.get_native_mut_ref().payment_hash;
586         &inner_val.0
587 }
588 /// Hash of the payment preimage, to lock the payment until the receiver releases the preimage.
589 #[no_mangle]
590 pub extern "C" fn PendingHTLCInfo_set_payment_hash(this_ptr: &mut PendingHTLCInfo, mut val: crate::c_types::ThirtyTwoBytes) {
591         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.payment_hash = ::lightning::ln::types::PaymentHash(val.data);
592 }
593 /// Amount received in the incoming HTLC.
594 ///
595 /// This field was added in LDK 0.0.113 and will be `None` for objects written by prior
596 /// versions.
597 #[no_mangle]
598 pub extern "C" fn PendingHTLCInfo_get_incoming_amt_msat(this_ptr: &PendingHTLCInfo) -> crate::c_types::derived::COption_u64Z {
599         let mut inner_val = &mut this_ptr.get_native_mut_ref().incoming_amt_msat;
600         let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) };
601         local_inner_val
602 }
603 /// Amount received in the incoming HTLC.
604 ///
605 /// This field was added in LDK 0.0.113 and will be `None` for objects written by prior
606 /// versions.
607 #[no_mangle]
608 pub extern "C" fn PendingHTLCInfo_set_incoming_amt_msat(this_ptr: &mut PendingHTLCInfo, mut val: crate::c_types::derived::COption_u64Z) {
609         let mut local_val = if val.is_some() { Some( { val.take() }) } else { None };
610         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.incoming_amt_msat = local_val;
611 }
612 /// The amount the sender indicated should be forwarded on to the next hop or amount the sender
613 /// intended for us to receive for received payments.
614 ///
615 /// If the received amount is less than this for received payments, an intermediary hop has
616 /// attempted to steal some of our funds and we should fail the HTLC (the sender should retry
617 /// it along another path).
618 ///
619 /// Because nodes can take less than their required fees, and because senders may wish to
620 /// improve their own privacy, this amount may be less than [`Self::incoming_amt_msat`] for
621 /// received payments. In such cases, recipients must handle this HTLC as if it had received
622 /// [`Self::outgoing_amt_msat`].
623 #[no_mangle]
624 pub extern "C" fn PendingHTLCInfo_get_outgoing_amt_msat(this_ptr: &PendingHTLCInfo) -> u64 {
625         let mut inner_val = &mut this_ptr.get_native_mut_ref().outgoing_amt_msat;
626         *inner_val
627 }
628 /// The amount the sender indicated should be forwarded on to the next hop or amount the sender
629 /// intended for us to receive for received payments.
630 ///
631 /// If the received amount is less than this for received payments, an intermediary hop has
632 /// attempted to steal some of our funds and we should fail the HTLC (the sender should retry
633 /// it along another path).
634 ///
635 /// Because nodes can take less than their required fees, and because senders may wish to
636 /// improve their own privacy, this amount may be less than [`Self::incoming_amt_msat`] for
637 /// received payments. In such cases, recipients must handle this HTLC as if it had received
638 /// [`Self::outgoing_amt_msat`].
639 #[no_mangle]
640 pub extern "C" fn PendingHTLCInfo_set_outgoing_amt_msat(this_ptr: &mut PendingHTLCInfo, mut val: u64) {
641         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outgoing_amt_msat = val;
642 }
643 /// The CLTV the sender has indicated we should set on the forwarded HTLC (or has indicated
644 /// should have been set on the received HTLC for received payments).
645 #[no_mangle]
646 pub extern "C" fn PendingHTLCInfo_get_outgoing_cltv_value(this_ptr: &PendingHTLCInfo) -> u32 {
647         let mut inner_val = &mut this_ptr.get_native_mut_ref().outgoing_cltv_value;
648         *inner_val
649 }
650 /// The CLTV the sender has indicated we should set on the forwarded HTLC (or has indicated
651 /// should have been set on the received HTLC for received payments).
652 #[no_mangle]
653 pub extern "C" fn PendingHTLCInfo_set_outgoing_cltv_value(this_ptr: &mut PendingHTLCInfo, mut val: u32) {
654         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.outgoing_cltv_value = val;
655 }
656 /// The fee taken for this HTLC in addition to the standard protocol HTLC fees.
657 ///
658 /// If this is a payment for forwarding, this is the fee we are taking before forwarding the
659 /// HTLC.
660 ///
661 /// If this is a received payment, this is the fee that our counterparty took.
662 ///
663 /// This is used to allow LSPs to take fees as a part of payments, without the sender having to
664 /// shoulder them.
665 #[no_mangle]
666 pub extern "C" fn PendingHTLCInfo_get_skimmed_fee_msat(this_ptr: &PendingHTLCInfo) -> crate::c_types::derived::COption_u64Z {
667         let mut inner_val = &mut this_ptr.get_native_mut_ref().skimmed_fee_msat;
668         let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { inner_val.unwrap() }) };
669         local_inner_val
670 }
671 /// The fee taken for this HTLC in addition to the standard protocol HTLC fees.
672 ///
673 /// If this is a payment for forwarding, this is the fee we are taking before forwarding the
674 /// HTLC.
675 ///
676 /// If this is a received payment, this is the fee that our counterparty took.
677 ///
678 /// This is used to allow LSPs to take fees as a part of payments, without the sender having to
679 /// shoulder them.
680 #[no_mangle]
681 pub extern "C" fn PendingHTLCInfo_set_skimmed_fee_msat(this_ptr: &mut PendingHTLCInfo, mut val: crate::c_types::derived::COption_u64Z) {
682         let mut local_val = if val.is_some() { Some( { val.take() }) } else { None };
683         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.skimmed_fee_msat = local_val;
684 }
685 /// Constructs a new PendingHTLCInfo given each field
686 #[must_use]
687 #[no_mangle]
688 pub extern "C" fn PendingHTLCInfo_new(mut routing_arg: crate::lightning::ln::channelmanager::PendingHTLCRouting, mut incoming_shared_secret_arg: crate::c_types::ThirtyTwoBytes, mut payment_hash_arg: crate::c_types::ThirtyTwoBytes, mut incoming_amt_msat_arg: crate::c_types::derived::COption_u64Z, mut outgoing_amt_msat_arg: u64, mut outgoing_cltv_value_arg: u32, mut skimmed_fee_msat_arg: crate::c_types::derived::COption_u64Z) -> PendingHTLCInfo {
689         let mut local_incoming_amt_msat_arg = if incoming_amt_msat_arg.is_some() { Some( { incoming_amt_msat_arg.take() }) } else { None };
690         let mut local_skimmed_fee_msat_arg = if skimmed_fee_msat_arg.is_some() { Some( { skimmed_fee_msat_arg.take() }) } else { None };
691         PendingHTLCInfo { inner: ObjOps::heap_alloc(nativePendingHTLCInfo {
692                 routing: routing_arg.into_native(),
693                 incoming_shared_secret: incoming_shared_secret_arg.data,
694                 payment_hash: ::lightning::ln::types::PaymentHash(payment_hash_arg.data),
695                 incoming_amt_msat: local_incoming_amt_msat_arg,
696                 outgoing_amt_msat: outgoing_amt_msat_arg,
697                 outgoing_cltv_value: outgoing_cltv_value_arg,
698                 skimmed_fee_msat: local_skimmed_fee_msat_arg,
699         }), is_owned: true }
700 }
701 impl Clone for PendingHTLCInfo {
702         fn clone(&self) -> Self {
703                 Self {
704                         inner: if <*mut nativePendingHTLCInfo>::is_null(self.inner) { core::ptr::null_mut() } else {
705                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
706                         is_owned: true,
707                 }
708         }
709 }
710 #[allow(unused)]
711 /// Used only if an object of this type is returned as a trait impl by a method
712 pub(crate) extern "C" fn PendingHTLCInfo_clone_void(this_ptr: *const c_void) -> *mut c_void {
713         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativePendingHTLCInfo)).clone() })) as *mut c_void
714 }
715 #[no_mangle]
716 /// Creates a copy of the PendingHTLCInfo
717 pub extern "C" fn PendingHTLCInfo_clone(orig: &PendingHTLCInfo) -> PendingHTLCInfo {
718         orig.clone()
719 }
720 /// Whether this blinded HTLC is being failed backwards by the introduction node or a blinded node,
721 /// which determines the failure message that should be used.
722 #[derive(Clone)]
723 #[must_use]
724 #[repr(C)]
725 pub enum BlindedFailure {
726         /// This HTLC is being failed backwards by the introduction node, and thus should be failed with
727         /// [`msgs::UpdateFailHTLC`] and error code `0x8000|0x4000|24`.
728         FromIntroductionNode,
729         /// This HTLC is being failed backwards by a blinded node within the path, and thus should be
730         /// failed with [`msgs::UpdateFailMalformedHTLC`] and error code `0x8000|0x4000|24`.
731         FromBlindedNode,
732 }
733 use lightning::ln::channelmanager::BlindedFailure as BlindedFailureImport;
734 pub(crate) type nativeBlindedFailure = BlindedFailureImport;
735
736 impl BlindedFailure {
737         #[allow(unused)]
738         pub(crate) fn to_native(&self) -> nativeBlindedFailure {
739                 match self {
740                         BlindedFailure::FromIntroductionNode => nativeBlindedFailure::FromIntroductionNode,
741                         BlindedFailure::FromBlindedNode => nativeBlindedFailure::FromBlindedNode,
742                 }
743         }
744         #[allow(unused)]
745         pub(crate) fn into_native(self) -> nativeBlindedFailure {
746                 match self {
747                         BlindedFailure::FromIntroductionNode => nativeBlindedFailure::FromIntroductionNode,
748                         BlindedFailure::FromBlindedNode => nativeBlindedFailure::FromBlindedNode,
749                 }
750         }
751         #[allow(unused)]
752         pub(crate) fn from_native(native: &BlindedFailureImport) -> Self {
753                 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeBlindedFailure) };
754                 match native {
755                         nativeBlindedFailure::FromIntroductionNode => BlindedFailure::FromIntroductionNode,
756                         nativeBlindedFailure::FromBlindedNode => BlindedFailure::FromBlindedNode,
757                 }
758         }
759         #[allow(unused)]
760         pub(crate) fn native_into(native: nativeBlindedFailure) -> Self {
761                 match native {
762                         nativeBlindedFailure::FromIntroductionNode => BlindedFailure::FromIntroductionNode,
763                         nativeBlindedFailure::FromBlindedNode => BlindedFailure::FromBlindedNode,
764                 }
765         }
766 }
767 /// Creates a copy of the BlindedFailure
768 #[no_mangle]
769 pub extern "C" fn BlindedFailure_clone(orig: &BlindedFailure) -> BlindedFailure {
770         orig.clone()
771 }
772 #[allow(unused)]
773 /// Used only if an object of this type is returned as a trait impl by a method
774 pub(crate) extern "C" fn BlindedFailure_clone_void(this_ptr: *const c_void) -> *mut c_void {
775         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const BlindedFailure)).clone() })) as *mut c_void
776 }
777 #[allow(unused)]
778 /// Used only if an object of this type is returned as a trait impl by a method
779 pub(crate) extern "C" fn BlindedFailure_free_void(this_ptr: *mut c_void) {
780         let _ = unsafe { Box::from_raw(this_ptr as *mut BlindedFailure) };
781 }
782 #[no_mangle]
783 /// Utility method to constructs a new FromIntroductionNode-variant BlindedFailure
784 pub extern "C" fn BlindedFailure_from_introduction_node() -> BlindedFailure {
785         BlindedFailure::FromIntroductionNode}
786 #[no_mangle]
787 /// Utility method to constructs a new FromBlindedNode-variant BlindedFailure
788 pub extern "C" fn BlindedFailure_from_blinded_node() -> BlindedFailure {
789         BlindedFailure::FromBlindedNode}
790 /// Get a string which allows debug introspection of a BlindedFailure object
791 pub extern "C" fn BlindedFailure_debug_str_void(o: *const c_void) -> Str {
792         alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::BlindedFailure }).into()}
793 /// Generates a non-cryptographic 64-bit hash of the BlindedFailure.
794 #[no_mangle]
795 pub extern "C" fn BlindedFailure_hash(o: &BlindedFailure) -> u64 {
796         // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core
797         #[allow(deprecated)]
798         let mut hasher = core::hash::SipHasher::new();
799         core::hash::Hash::hash(&o.to_native(), &mut hasher);
800         core::hash::Hasher::finish(&hasher)
801 }
802 /// Checks if two BlindedFailures contain equal inner contents.
803 /// This ignores pointers and is_owned flags and looks at the values in fields.
804 #[no_mangle]
805 pub extern "C" fn BlindedFailure_eq(a: &BlindedFailure, b: &BlindedFailure) -> bool {
806         if &a.to_native() == &b.to_native() { true } else { false }
807 }
808 /// This enum is used to specify which error data to send to peers when failing back an HTLC
809 /// using [`ChannelManager::fail_htlc_backwards_with_reason`].
810 ///
811 /// For more info on failure codes, see <https://github.com/lightning/bolts/blob/master/04-onion-routing.md#failure-messages>.
812 #[derive(Clone)]
813 #[must_use]
814 #[repr(C)]
815 pub enum FailureCode {
816         /// We had a temporary error processing the payment. Useful if no other error codes fit
817         /// and you want to indicate that the payer may want to retry.
818         TemporaryNodeFailure,
819         /// We have a required feature which was not in this onion. For example, you may require
820         /// some additional metadata that was not provided with this payment.
821         RequiredNodeFeatureMissing,
822         /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of
823         /// the HTLC is too close to the current block height for safe handling.
824         /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is
825         /// equivalent to calling [`ChannelManager::fail_htlc_backwards`].
826         IncorrectOrUnknownPaymentDetails,
827         /// We failed to process the payload after the onion was decrypted. You may wish to
828         /// use this when receiving custom HTLC TLVs with even type numbers that you don't recognize.
829         ///
830         /// If available, the tuple data may include the type number and byte offset in the
831         /// decrypted byte stream where the failure occurred.
832         InvalidOnionPayload(
833                 crate::c_types::derived::COption_C2Tuple_u64u16ZZ),
834 }
835 use lightning::ln::channelmanager::FailureCode as FailureCodeImport;
836 pub(crate) type nativeFailureCode = FailureCodeImport;
837
838 impl FailureCode {
839         #[allow(unused)]
840         pub(crate) fn to_native(&self) -> nativeFailureCode {
841                 match self {
842                         FailureCode::TemporaryNodeFailure => nativeFailureCode::TemporaryNodeFailure,
843                         FailureCode::RequiredNodeFeatureMissing => nativeFailureCode::RequiredNodeFeatureMissing,
844                         FailureCode::IncorrectOrUnknownPaymentDetails => nativeFailureCode::IncorrectOrUnknownPaymentDetails,
845                         FailureCode::InvalidOnionPayload (ref a, ) => {
846                                 let mut a_nonref = Clone::clone(a);
847                                 let mut local_a_nonref = if a_nonref.is_some() { Some( { let (mut orig_a_nonref_0_0, mut orig_a_nonref_0_1) = a_nonref.take().to_rust(); let mut local_a_nonref_0 = (orig_a_nonref_0_0, orig_a_nonref_0_1); local_a_nonref_0 }) } else { None };
848                                 nativeFailureCode::InvalidOnionPayload (
849                                         local_a_nonref,
850                                 )
851                         },
852                 }
853         }
854         #[allow(unused)]
855         pub(crate) fn into_native(self) -> nativeFailureCode {
856                 match self {
857                         FailureCode::TemporaryNodeFailure => nativeFailureCode::TemporaryNodeFailure,
858                         FailureCode::RequiredNodeFeatureMissing => nativeFailureCode::RequiredNodeFeatureMissing,
859                         FailureCode::IncorrectOrUnknownPaymentDetails => nativeFailureCode::IncorrectOrUnknownPaymentDetails,
860                         FailureCode::InvalidOnionPayload (mut a, ) => {
861                                 let mut local_a = if a.is_some() { Some( { let (mut orig_a_0_0, mut orig_a_0_1) = a.take().to_rust(); let mut local_a_0 = (orig_a_0_0, orig_a_0_1); local_a_0 }) } else { None };
862                                 nativeFailureCode::InvalidOnionPayload (
863                                         local_a,
864                                 )
865                         },
866                 }
867         }
868         #[allow(unused)]
869         pub(crate) fn from_native(native: &FailureCodeImport) -> Self {
870                 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeFailureCode) };
871                 match native {
872                         nativeFailureCode::TemporaryNodeFailure => FailureCode::TemporaryNodeFailure,
873                         nativeFailureCode::RequiredNodeFeatureMissing => FailureCode::RequiredNodeFeatureMissing,
874                         nativeFailureCode::IncorrectOrUnknownPaymentDetails => FailureCode::IncorrectOrUnknownPaymentDetails,
875                         nativeFailureCode::InvalidOnionPayload (ref a, ) => {
876                                 let mut a_nonref = Clone::clone(a);
877                                 let mut local_a_nonref = if a_nonref.is_none() { crate::c_types::derived::COption_C2Tuple_u64u16ZZ::None } else { crate::c_types::derived::COption_C2Tuple_u64u16ZZ::Some( { let (mut orig_a_nonref_0_0, mut orig_a_nonref_0_1) = (a_nonref.unwrap()); let mut local_a_nonref_0 = (orig_a_nonref_0_0, orig_a_nonref_0_1).into(); local_a_nonref_0 }) };
878                                 FailureCode::InvalidOnionPayload (
879                                         local_a_nonref,
880                                 )
881                         },
882                 }
883         }
884         #[allow(unused)]
885         pub(crate) fn native_into(native: nativeFailureCode) -> Self {
886                 match native {
887                         nativeFailureCode::TemporaryNodeFailure => FailureCode::TemporaryNodeFailure,
888                         nativeFailureCode::RequiredNodeFeatureMissing => FailureCode::RequiredNodeFeatureMissing,
889                         nativeFailureCode::IncorrectOrUnknownPaymentDetails => FailureCode::IncorrectOrUnknownPaymentDetails,
890                         nativeFailureCode::InvalidOnionPayload (mut a, ) => {
891                                 let mut local_a = if a.is_none() { crate::c_types::derived::COption_C2Tuple_u64u16ZZ::None } else { crate::c_types::derived::COption_C2Tuple_u64u16ZZ::Some( { let (mut orig_a_0_0, mut orig_a_0_1) = (a.unwrap()); let mut local_a_0 = (orig_a_0_0, orig_a_0_1).into(); local_a_0 }) };
892                                 FailureCode::InvalidOnionPayload (
893                                         local_a,
894                                 )
895                         },
896                 }
897         }
898 }
899 /// Frees any resources used by the FailureCode
900 #[no_mangle]
901 pub extern "C" fn FailureCode_free(this_ptr: FailureCode) { }
902 /// Creates a copy of the FailureCode
903 #[no_mangle]
904 pub extern "C" fn FailureCode_clone(orig: &FailureCode) -> FailureCode {
905         orig.clone()
906 }
907 #[allow(unused)]
908 /// Used only if an object of this type is returned as a trait impl by a method
909 pub(crate) extern "C" fn FailureCode_clone_void(this_ptr: *const c_void) -> *mut c_void {
910         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const FailureCode)).clone() })) as *mut c_void
911 }
912 #[allow(unused)]
913 /// Used only if an object of this type is returned as a trait impl by a method
914 pub(crate) extern "C" fn FailureCode_free_void(this_ptr: *mut c_void) {
915         let _ = unsafe { Box::from_raw(this_ptr as *mut FailureCode) };
916 }
917 #[no_mangle]
918 /// Utility method to constructs a new TemporaryNodeFailure-variant FailureCode
919 pub extern "C" fn FailureCode_temporary_node_failure() -> FailureCode {
920         FailureCode::TemporaryNodeFailure}
921 #[no_mangle]
922 /// Utility method to constructs a new RequiredNodeFeatureMissing-variant FailureCode
923 pub extern "C" fn FailureCode_required_node_feature_missing() -> FailureCode {
924         FailureCode::RequiredNodeFeatureMissing}
925 #[no_mangle]
926 /// Utility method to constructs a new IncorrectOrUnknownPaymentDetails-variant FailureCode
927 pub extern "C" fn FailureCode_incorrect_or_unknown_payment_details() -> FailureCode {
928         FailureCode::IncorrectOrUnknownPaymentDetails}
929 #[no_mangle]
930 /// Utility method to constructs a new InvalidOnionPayload-variant FailureCode
931 pub extern "C" fn FailureCode_invalid_onion_payload(a: crate::c_types::derived::COption_C2Tuple_u64u16ZZ) -> FailureCode {
932         FailureCode::InvalidOnionPayload(a, )
933 }
934
935 use lightning::ln::channelmanager::ChannelManager as nativeChannelManagerImport;
936 pub(crate) type nativeChannelManager = nativeChannelManagerImport<crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::sign::EntropySource, crate::lightning::sign::NodeSigner, crate::lightning::sign::SignerProvider, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::routing::router::Router, crate::lightning::util::logger::Logger, >;
937
938 /// A lightning node's channel state machine and payment management logic, which facilitates
939 /// sending, forwarding, and receiving payments through lightning channels.
940 ///
941 /// [`ChannelManager`] is parameterized by a number of components to achieve this.
942 /// - [`chain::Watch`] (typically [`ChainMonitor`]) for on-chain monitoring and enforcement of each
943 ///   channel
944 /// - [`BroadcasterInterface`] for broadcasting transactions related to opening, funding, and
945 ///   closing channels
946 /// - [`EntropySource`] for providing random data needed for cryptographic operations
947 /// - [`NodeSigner`] for cryptographic operations scoped to the node
948 /// - [`SignerProvider`] for providing signers whose operations are scoped to individual channels
949 /// - [`FeeEstimator`] to determine transaction fee rates needed to have a transaction mined in a
950 ///   timely manner
951 /// - [`Router`] for finding payment paths when initiating and retrying payments
952 /// - [`Logger`] for logging operational information of varying degrees
953 ///
954 /// Additionally, it implements the following traits:
955 /// - [`ChannelMessageHandler`] to handle off-chain channel activity from peers
956 /// - [`MessageSendEventsProvider`] to similarly send such messages to peers
957 /// - [`OffersMessageHandler`] for BOLT 12 message handling and sending
958 /// - [`EventsProvider`] to generate user-actionable [`Event`]s
959 /// - [`chain::Listen`] and [`chain::Confirm`] for notification of on-chain activity
960 ///
961 /// Thus, [`ChannelManager`] is typically used to parameterize a [`MessageHandler`] and an
962 /// [`OnionMessenger`]. The latter is required to support BOLT 12 functionality.
963 ///
964 /// # `ChannelManager` vs `ChannelMonitor`
965 ///
966 /// It's important to distinguish between the *off-chain* management and *on-chain* enforcement of
967 /// lightning channels. [`ChannelManager`] exchanges messages with peers to manage the off-chain
968 /// state of each channel. During this process, it generates a [`ChannelMonitor`] for each channel
969 /// and a [`ChannelMonitorUpdate`] for each relevant change, notifying its parameterized
970 /// [`chain::Watch`] of them.
971 ///
972 /// An implementation of [`chain::Watch`], such as [`ChainMonitor`], is responsible for aggregating
973 /// these [`ChannelMonitor`]s and applying any [`ChannelMonitorUpdate`]s to them. It then monitors
974 /// for any pertinent on-chain activity, enforcing claims as needed.
975 ///
976 /// This division of off-chain management and on-chain enforcement allows for interesting node
977 /// setups. For instance, on-chain enforcement could be moved to a separate host or have added
978 /// redundancy, possibly as a watchtower. See [`chain::Watch`] for the relevant interface.
979 ///
980 /// # Initialization
981 ///
982 /// Use [`ChannelManager::new`] with the most recent [`BlockHash`] when creating a fresh instance.
983 /// Otherwise, if restarting, construct [`ChannelManagerReadArgs`] with the necessary parameters and
984 /// references to any deserialized [`ChannelMonitor`]s that were previously persisted. Use this to
985 /// deserialize the [`ChannelManager`] and feed it any new chain data since it was last online, as
986 /// detailed in the [`ChannelManagerReadArgs`] documentation.
987 ///
988 /// ```
989 /// use bitcoin::BlockHash;
990 /// use bitcoin::network::constants::Network;
991 /// use lightning::chain::BestBlock;
992 /// # use lightning::chain::channelmonitor::ChannelMonitor;
993 /// use lightning::ln::channelmanager::{ChainParameters, ChannelManager, ChannelManagerReadArgs};
994 /// # use lightning::routing::gossip::NetworkGraph;
995 /// use lightning::util::config::UserConfig;
996 /// use lightning::util::ser::ReadableArgs;
997 ///
998 /// # fn read_channel_monitors() -> Vec<ChannelMonitor<lightning::sign::InMemorySigner>> { vec![] }
999 /// # fn example<
1000 /// #     'a,
1001 /// #     L: lightning::util::logger::Logger,
1002 /// #     ES: lightning::sign::EntropySource,
1003 /// #     S: for <'b> lightning::routing::scoring::LockableScore<'b, ScoreLookUp = SL>,
1004 /// #     SL: lightning::routing::scoring::ScoreLookUp<ScoreParams = SP>,
1005 /// #     SP: Sized,
1006 /// #     R: lightning::io::Read,
1007 /// # >(
1008 /// #     fee_estimator: &dyn lightning::chain::chaininterface::FeeEstimator,
1009 /// #     chain_monitor: &dyn lightning::chain::Watch<lightning::sign::InMemorySigner>,
1010 /// #     tx_broadcaster: &dyn lightning::chain::chaininterface::BroadcasterInterface,
1011 /// #     router: &lightning::routing::router::DefaultRouter<&NetworkGraph<&'a L>, &'a L, &ES, &S, SP, SL>,
1012 /// #     logger: &L,
1013 /// #     entropy_source: &ES,
1014 /// #     node_signer: &dyn lightning::sign::NodeSigner,
1015 /// #     signer_provider: &lightning::sign::DynSignerProvider,
1016 /// #     best_block: lightning::chain::BestBlock,
1017 /// #     current_timestamp: u32,
1018 /// #     mut reader: R,
1019 /// # ) -> Result<(), lightning::ln::msgs::DecodeError> {
1020 /// // Fresh start with no channels
1021 /// let params = ChainParameters {
1022 ///     network: Network::Bitcoin,
1023 ///     best_block,
1024 /// };
1025 /// let default_config = UserConfig::default();
1026 /// let channel_manager = ChannelManager::new(
1027 ///     fee_estimator, chain_monitor, tx_broadcaster, router, logger, entropy_source, node_signer,
1028 ///     signer_provider, default_config, params, current_timestamp
1029 /// );
1030 ///
1031 /// // Restart from deserialized data
1032 /// let mut channel_monitors = read_channel_monitors();
1033 /// let args = ChannelManagerReadArgs::new(
1034 ///     entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster,
1035 ///     router, logger, default_config, channel_monitors.iter_mut().collect()
1036 /// );
1037 /// let (block_hash, channel_manager) =
1038 ///     <(BlockHash, ChannelManager<_, _, _, _, _, _, _, _>)>::read(&mut reader, args)?;
1039 ///
1040 /// // Update the ChannelManager and ChannelMonitors with the latest chain data
1041 /// // ...
1042 ///
1043 /// // Move the monitors to the ChannelManager's chain::Watch parameter
1044 /// for monitor in channel_monitors {
1045 ///     chain_monitor.watch_channel(monitor.get_funding_txo().0, monitor);
1046 /// }
1047 /// # Ok(())
1048 /// # }
1049 /// ```
1050 ///
1051 /// # Operation
1052 ///
1053 /// The following is required for [`ChannelManager`] to function properly:
1054 /// - Handle messages from peers using its [`ChannelMessageHandler`] implementation (typically
1055 ///   called by [`PeerManager::read_event`] when processing network I/O)
1056 /// - Send messages to peers obtained via its [`MessageSendEventsProvider`] implementation
1057 ///   (typically initiated when [`PeerManager::process_events`] is called)
1058 /// - Feed on-chain activity using either its [`chain::Listen`] or [`chain::Confirm`] implementation
1059 ///   as documented by those traits
1060 /// - Perform any periodic channel and payment checks by calling [`timer_tick_occurred`] roughly
1061 ///   every minute
1062 /// - Persist to disk whenever [`get_and_clear_needs_persistence`] returns `true` using a
1063 ///   [`Persister`] such as a [`KVStore`] implementation
1064 /// - Handle [`Event`]s obtained via its [`EventsProvider`] implementation
1065 ///
1066 /// The [`Future`] returned by [`get_event_or_persistence_needed_future`] is useful in determining
1067 /// when the last two requirements need to be checked.
1068 ///
1069 /// The [`lightning-block-sync`] and [`lightning-transaction-sync`] crates provide utilities that
1070 /// simplify feeding in on-chain activity using the [`chain::Listen`] and [`chain::Confirm`] traits,
1071 /// respectively. The remaining requirements can be met using the [`lightning-background-processor`]
1072 /// crate. For languages other than Rust, the availability of similar utilities may vary.
1073 ///
1074 /// # Channels
1075 ///
1076 /// [`ChannelManager`]'s primary function involves managing a channel state. Without channels,
1077 /// payments can't be sent. Use [`list_channels`] or [`list_usable_channels`] for a snapshot of the
1078 /// currently open channels.
1079 ///
1080 /// ```
1081 /// # use lightning::ln::channelmanager::AChannelManager;
1082 /// #
1083 /// # fn example<T: AChannelManager>(channel_manager: T) {
1084 /// # let channel_manager = channel_manager.get_cm();
1085 /// let channels = channel_manager.list_usable_channels();
1086 /// for details in channels {
1087 ///     println!(\"{:?}\", details);
1088 /// }
1089 /// # }
1090 /// ```
1091 ///
1092 /// Each channel is identified using a [`ChannelId`], which will change throughout the channel's
1093 /// life cycle. Additionally, channels are assigned a `user_channel_id`, which is given in
1094 /// [`Event`]s associated with the channel and serves as a fixed identifier but is otherwise unused
1095 /// by [`ChannelManager`].
1096 ///
1097 /// ## Opening Channels
1098 ///
1099 /// To an open a channel with a peer, call [`create_channel`]. This will initiate the process of
1100 /// opening an outbound channel, which requires self-funding when handling
1101 /// [`Event::FundingGenerationReady`].
1102 ///
1103 /// ```
1104 /// # use bitcoin::{ScriptBuf, Transaction};
1105 /// # use bitcoin::secp256k1::PublicKey;
1106 /// # use lightning::ln::channelmanager::AChannelManager;
1107 /// # use lightning::events::{Event, EventsProvider};
1108 /// #
1109 /// # trait Wallet {
1110 /// #     fn create_funding_transaction(
1111 /// #         &self, _amount_sats: u64, _output_script: ScriptBuf
1112 /// #     ) -> Transaction;
1113 /// # }
1114 /// #
1115 /// # fn example<T: AChannelManager, W: Wallet>(channel_manager: T, wallet: W, peer_id: PublicKey) {
1116 /// # let channel_manager = channel_manager.get_cm();
1117 /// let value_sats = 1_000_000;
1118 /// let push_msats = 10_000_000;
1119 /// match channel_manager.create_channel(peer_id, value_sats, push_msats, 42, None, None) {
1120 ///     Ok(channel_id) => println!(\"Opening channel {}\", channel_id),
1121 ///     Err(e) => println!(\"Error opening channel: {:?}\", e),
1122 /// }
1123 ///
1124 /// // On the event processing thread once the peer has responded
1125 /// channel_manager.process_pending_events(&|event| match event {
1126 ///     Event::FundingGenerationReady {
1127 ///         temporary_channel_id, counterparty_node_id, channel_value_satoshis, output_script,
1128 ///         user_channel_id, ..
1129 ///     } => {
1130 ///         assert_eq!(user_channel_id, 42);
1131 ///         let funding_transaction = wallet.create_funding_transaction(
1132 ///             channel_value_satoshis, output_script
1133 ///         );
1134 ///         match channel_manager.funding_transaction_generated(
1135 ///             &temporary_channel_id, &counterparty_node_id, funding_transaction
1136 ///         ) {
1137 ///             Ok(()) => println!(\"Funding channel {}\", temporary_channel_id),
1138 ///             Err(e) => println!(\"Error funding channel {}: {:?}\", temporary_channel_id, e),
1139 ///         }
1140 ///     },
1141 ///     Event::ChannelPending { channel_id, user_channel_id, former_temporary_channel_id, .. } => {
1142 ///         assert_eq!(user_channel_id, 42);
1143 ///         println!(
1144 ///             \"Channel {} now {} pending (funding transaction has been broadcasted)\", channel_id,
1145 ///             former_temporary_channel_id.unwrap()
1146 ///         );
1147 ///     },
1148 ///     Event::ChannelReady { channel_id, user_channel_id, .. } => {
1149 ///         assert_eq!(user_channel_id, 42);
1150 ///         println!(\"Channel {} ready\", channel_id);
1151 ///     },
1152 ///     // ...
1153 /// #     _ => {},
1154 /// });
1155 /// # }
1156 /// ```
1157 ///
1158 /// ## Accepting Channels
1159 ///
1160 /// Inbound channels are initiated by peers and are automatically accepted unless [`ChannelManager`]
1161 /// has [`UserConfig::manually_accept_inbound_channels`] set. In that case, the channel may be
1162 /// either accepted or rejected when handling [`Event::OpenChannelRequest`].
1163 ///
1164 /// ```
1165 /// # use bitcoin::secp256k1::PublicKey;
1166 /// # use lightning::ln::channelmanager::AChannelManager;
1167 /// # use lightning::events::{Event, EventsProvider};
1168 /// #
1169 /// # fn is_trusted(counterparty_node_id: PublicKey) -> bool {
1170 /// #     // ...
1171 /// #     unimplemented!()
1172 /// # }
1173 /// #
1174 /// # fn example<T: AChannelManager>(channel_manager: T) {
1175 /// # let channel_manager = channel_manager.get_cm();
1176 /// channel_manager.process_pending_events(&|event| match event {
1177 ///     Event::OpenChannelRequest { temporary_channel_id, counterparty_node_id, ..  } => {
1178 ///         if !is_trusted(counterparty_node_id) {
1179 ///             match channel_manager.force_close_without_broadcasting_txn(
1180 ///                 &temporary_channel_id, &counterparty_node_id
1181 ///             ) {
1182 ///                 Ok(()) => println!(\"Rejecting channel {}\", temporary_channel_id),
1183 ///                 Err(e) => println!(\"Error rejecting channel {}: {:?}\", temporary_channel_id, e),
1184 ///             }
1185 ///             return;
1186 ///         }
1187 ///
1188 ///         let user_channel_id = 43;
1189 ///         match channel_manager.accept_inbound_channel(
1190 ///             &temporary_channel_id, &counterparty_node_id, user_channel_id
1191 ///         ) {
1192 ///             Ok(()) => println!(\"Accepting channel {}\", temporary_channel_id),
1193 ///             Err(e) => println!(\"Error accepting channel {}: {:?}\", temporary_channel_id, e),
1194 ///         }
1195 ///     },
1196 ///     // ...
1197 /// #     _ => {},
1198 /// });
1199 /// # }
1200 /// ```
1201 ///
1202 /// ## Closing Channels
1203 ///
1204 /// There are two ways to close a channel: either cooperatively using [`close_channel`] or
1205 /// unilaterally using [`force_close_broadcasting_latest_txn`]. The former is ideal as it makes for
1206 /// lower fees and immediate access to funds. However, the latter may be necessary if the
1207 /// counterparty isn't behaving properly or has gone offline. [`Event::ChannelClosed`] is generated
1208 /// once the channel has been closed successfully.
1209 ///
1210 /// ```
1211 /// # use bitcoin::secp256k1::PublicKey;
1212 /// # use lightning::ln::types::ChannelId;
1213 /// # use lightning::ln::channelmanager::AChannelManager;
1214 /// # use lightning::events::{Event, EventsProvider};
1215 /// #
1216 /// # fn example<T: AChannelManager>(
1217 /// #     channel_manager: T, channel_id: ChannelId, counterparty_node_id: PublicKey
1218 /// # ) {
1219 /// # let channel_manager = channel_manager.get_cm();
1220 /// match channel_manager.close_channel(&channel_id, &counterparty_node_id) {
1221 ///     Ok(()) => println!(\"Closing channel {}\", channel_id),
1222 ///     Err(e) => println!(\"Error closing channel {}: {:?}\", channel_id, e),
1223 /// }
1224 ///
1225 /// // On the event processing thread
1226 /// channel_manager.process_pending_events(&|event| match event {
1227 ///     Event::ChannelClosed { channel_id, user_channel_id, ..  } => {
1228 ///         assert_eq!(user_channel_id, 42);
1229 ///         println!(\"Channel {} closed\", channel_id);
1230 ///     },
1231 ///     // ...
1232 /// #     _ => {},
1233 /// });
1234 /// # }
1235 /// ```
1236 ///
1237 /// # Payments
1238 ///
1239 /// [`ChannelManager`] is responsible for sending, forwarding, and receiving payments through its
1240 /// channels. A payment is typically initiated from a [BOLT 11] invoice or a [BOLT 12] offer, though
1241 /// spontaneous (i.e., keysend) payments are also possible. Incoming payments don't require
1242 /// maintaining any additional state as [`ChannelManager`] can reconstruct the [`PaymentPreimage`]
1243 /// from the [`PaymentSecret`]. Sending payments, however, require tracking in order to retry failed
1244 /// HTLCs.
1245 ///
1246 /// After a payment is initiated, it will appear in [`list_recent_payments`] until a short time
1247 /// after either an [`Event::PaymentSent`] or [`Event::PaymentFailed`] is handled. Failed HTLCs
1248 /// for a payment will be retried according to the payment's [`Retry`] strategy or until
1249 /// [`abandon_payment`] is called.
1250 ///
1251 /// ## BOLT 11 Invoices
1252 ///
1253 /// The [`lightning-invoice`] crate is useful for creating BOLT 11 invoices. Specifically, use the
1254 /// functions in its `utils` module for constructing invoices that are compatible with
1255 /// [`ChannelManager`]. These functions serve as a convenience for building invoices with the
1256 /// [`PaymentHash`] and [`PaymentSecret`] returned from [`create_inbound_payment`]. To provide your
1257 /// own [`PaymentHash`], use [`create_inbound_payment_for_hash`] or the corresponding functions in
1258 /// the [`lightning-invoice`] `utils` module.
1259 ///
1260 /// [`ChannelManager`] generates an [`Event::PaymentClaimable`] once the full payment has been
1261 /// received. Call [`claim_funds`] to release the [`PaymentPreimage`], which in turn will result in
1262 /// an [`Event::PaymentClaimed`].
1263 ///
1264 /// ```
1265 /// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
1266 /// # use lightning::ln::channelmanager::AChannelManager;
1267 /// #
1268 /// # fn example<T: AChannelManager>(channel_manager: T) {
1269 /// # let channel_manager = channel_manager.get_cm();
1270 /// // Or use utils::create_invoice_from_channelmanager
1271 /// let known_payment_hash = match channel_manager.create_inbound_payment(
1272 ///     Some(10_000_000), 3600, None
1273 /// ) {
1274 ///     Ok((payment_hash, _payment_secret)) => {
1275 ///         println!(\"Creating inbound payment {}\", payment_hash);
1276 ///         payment_hash
1277 ///     },
1278 ///     Err(()) => panic!(\"Error creating inbound payment\"),
1279 /// };
1280 ///
1281 /// // On the event processing thread
1282 /// channel_manager.process_pending_events(&|event| match event {
1283 ///     Event::PaymentClaimable { payment_hash, purpose, .. } => match purpose {
1284 ///         PaymentPurpose::Bolt11InvoicePayment { payment_preimage: Some(payment_preimage), .. } => {
1285 ///             assert_eq!(payment_hash, known_payment_hash);
1286 ///             println!(\"Claiming payment {}\", payment_hash);
1287 ///             channel_manager.claim_funds(payment_preimage);
1288 ///         },
1289 ///         PaymentPurpose::Bolt11InvoicePayment { payment_preimage: None, .. } => {
1290 ///             println!(\"Unknown payment hash: {}\", payment_hash);
1291 ///         },
1292 ///         PaymentPurpose::SpontaneousPayment(payment_preimage) => {
1293 ///             assert_ne!(payment_hash, known_payment_hash);
1294 ///             println!(\"Claiming spontaneous payment {}\", payment_hash);
1295 ///             channel_manager.claim_funds(payment_preimage);
1296 ///         },
1297 ///         // ...
1298 /// #         _ => {},
1299 ///     },
1300 ///     Event::PaymentClaimed { payment_hash, amount_msat, .. } => {
1301 ///         assert_eq!(payment_hash, known_payment_hash);
1302 ///         println!(\"Claimed {} msats\", amount_msat);
1303 ///     },
1304 ///     // ...
1305 /// #     _ => {},
1306 /// });
1307 /// # }
1308 /// ```
1309 ///
1310 /// For paying an invoice, [`lightning-invoice`] provides a `payment` module with convenience
1311 /// functions for use with [`send_payment`].
1312 ///
1313 /// ```
1314 /// # use lightning::events::{Event, EventsProvider};
1315 /// # use lightning::ln::types::PaymentHash;
1316 /// # use lightning::ln::channelmanager::{AChannelManager, PaymentId, RecentPaymentDetails, RecipientOnionFields, Retry};
1317 /// # use lightning::routing::router::RouteParameters;
1318 /// #
1319 /// # fn example<T: AChannelManager>(
1320 /// #     channel_manager: T, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1321 /// #     route_params: RouteParameters, retry: Retry
1322 /// # ) {
1323 /// # let channel_manager = channel_manager.get_cm();
1324 /// // let (payment_hash, recipient_onion, route_params) =
1325 /// //     payment::payment_parameters_from_invoice(&invoice);
1326 /// let payment_id = PaymentId([42; 32]);
1327 /// match channel_manager.send_payment(
1328 ///     payment_hash, recipient_onion, payment_id, route_params, retry
1329 /// ) {
1330 ///     Ok(()) => println!(\"Sending payment with hash {}\", payment_hash),
1331 ///     Err(e) => println!(\"Failed sending payment with hash {}: {:?}\", payment_hash, e),
1332 /// }
1333 ///
1334 /// let expected_payment_id = payment_id;
1335 /// let expected_payment_hash = payment_hash;
1336 /// assert!(
1337 ///     channel_manager.list_recent_payments().iter().find(|details| matches!(
1338 ///         details,
1339 ///         RecentPaymentDetails::Pending {
1340 ///             payment_id: expected_payment_id,
1341 ///             payment_hash: expected_payment_hash,
1342 ///             ..
1343 ///         }
1344 ///     )).is_some()
1345 /// );
1346 ///
1347 /// // On the event processing thread
1348 /// channel_manager.process_pending_events(&|event| match event {
1349 ///     Event::PaymentSent { payment_hash, .. } => println!(\"Paid {}\", payment_hash),
1350 ///     Event::PaymentFailed { payment_hash, .. } => println!(\"Failed paying {}\", payment_hash),
1351 ///     // ...
1352 /// #     _ => {},
1353 /// });
1354 /// # }
1355 /// ```
1356 ///
1357 /// ## BOLT 12 Offers
1358 ///
1359 /// The [`offers`] module is useful for creating BOLT 12 offers. An [`Offer`] is a precursor to a
1360 /// [`Bolt12Invoice`], which must first be requested by the payer. The interchange of these messages
1361 /// as defined in the specification is handled by [`ChannelManager`] and its implementation of
1362 /// [`OffersMessageHandler`]. However, this only works with an [`Offer`] created using a builder
1363 /// returned by [`create_offer_builder`]. With this approach, BOLT 12 offers and invoices are
1364 /// stateless just as BOLT 11 invoices are.
1365 ///
1366 /// ```
1367 /// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
1368 /// # use lightning::ln::channelmanager::AChannelManager;
1369 /// # use lightning::offers::parse::Bolt12SemanticError;
1370 /// #
1371 /// # fn example<T: AChannelManager>(channel_manager: T) -> Result<(), Bolt12SemanticError> {
1372 /// # let channel_manager = channel_manager.get_cm();
1373 /// let offer = channel_manager
1374 ///     .create_offer_builder()?
1375 /// # ;
1376 /// # // Needed for compiling for c_bindings
1377 /// # let builder: lightning::offers::offer::OfferBuilder<_, _> = offer.into();
1378 /// # let offer = builder
1379 ///     .description(\"coffee\".to_string())
1380 ///     .amount_msats(10_000_000)
1381 ///     .build()?;
1382 /// let bech32_offer = offer.to_string();
1383 ///
1384 /// // On the event processing thread
1385 /// channel_manager.process_pending_events(&|event| match event {
1386 ///     Event::PaymentClaimable { payment_hash, purpose, .. } => match purpose {
1387 ///         PaymentPurpose::Bolt12OfferPayment { payment_preimage: Some(payment_preimage), .. } => {
1388 ///             println!(\"Claiming payment {}\", payment_hash);
1389 ///             channel_manager.claim_funds(payment_preimage);
1390 ///         },
1391 ///         PaymentPurpose::Bolt12OfferPayment { payment_preimage: None, .. } => {
1392 ///             println!(\"Unknown payment hash: {}\", payment_hash);
1393 ///         },
1394 ///         // ...
1395 /// #         _ => {},
1396 ///     },
1397 ///     Event::PaymentClaimed { payment_hash, amount_msat, .. } => {
1398 ///         println!(\"Claimed {} msats\", amount_msat);
1399 ///     },
1400 ///     // ...
1401 /// #     _ => {},
1402 /// });
1403 /// # Ok(())
1404 /// # }
1405 /// ```
1406 ///
1407 /// Use [`pay_for_offer`] to initiated payment, which sends an [`InvoiceRequest`] for an [`Offer`]
1408 /// and pays the [`Bolt12Invoice`] response. In addition to success and failure events,
1409 /// [`ChannelManager`] may also generate an [`Event::InvoiceRequestFailed`].
1410 ///
1411 /// ```
1412 /// # use lightning::events::{Event, EventsProvider};
1413 /// # use lightning::ln::channelmanager::{AChannelManager, PaymentId, RecentPaymentDetails, Retry};
1414 /// # use lightning::offers::offer::Offer;
1415 /// #
1416 /// # fn example<T: AChannelManager>(
1417 /// #     channel_manager: T, offer: &Offer, quantity: Option<u64>, amount_msats: Option<u64>,
1418 /// #     payer_note: Option<String>, retry: Retry, max_total_routing_fee_msat: Option<u64>
1419 /// # ) {
1420 /// # let channel_manager = channel_manager.get_cm();
1421 /// let payment_id = PaymentId([42; 32]);
1422 /// match channel_manager.pay_for_offer(
1423 ///     offer, quantity, amount_msats, payer_note, payment_id, retry, max_total_routing_fee_msat
1424 /// ) {
1425 ///     Ok(()) => println!(\"Requesting invoice for offer\"),
1426 ///     Err(e) => println!(\"Unable to request invoice for offer: {:?}\", e),
1427 /// }
1428 ///
1429 /// // First the payment will be waiting on an invoice
1430 /// let expected_payment_id = payment_id;
1431 /// assert!(
1432 ///     channel_manager.list_recent_payments().iter().find(|details| matches!(
1433 ///         details,
1434 ///         RecentPaymentDetails::AwaitingInvoice { payment_id: expected_payment_id }
1435 ///     )).is_some()
1436 /// );
1437 ///
1438 /// // Once the invoice is received, a payment will be sent
1439 /// assert!(
1440 ///     channel_manager.list_recent_payments().iter().find(|details| matches!(
1441 ///         details,
1442 ///         RecentPaymentDetails::Pending { payment_id: expected_payment_id, ..  }
1443 ///     )).is_some()
1444 /// );
1445 ///
1446 /// // On the event processing thread
1447 /// channel_manager.process_pending_events(&|event| match event {
1448 ///     Event::PaymentSent { payment_id: Some(payment_id), .. } => println!(\"Paid {}\", payment_id),
1449 ///     Event::PaymentFailed { payment_id, .. } => println!(\"Failed paying {}\", payment_id),
1450 ///     Event::InvoiceRequestFailed { payment_id, .. } => println!(\"Failed paying {}\", payment_id),
1451 ///     // ...
1452 /// #     _ => {},
1453 /// });
1454 /// # }
1455 /// ```
1456 ///
1457 /// ## BOLT 12 Refunds
1458 ///
1459 /// A [`Refund`] is a request for an invoice to be paid. Like *paying* for an [`Offer`], *creating*
1460 /// a [`Refund`] involves maintaining state since it represents a future outbound payment.
1461 /// Therefore, use [`create_refund_builder`] when creating one, otherwise [`ChannelManager`] will
1462 /// refuse to pay any corresponding [`Bolt12Invoice`] that it receives.
1463 ///
1464 /// ```
1465 /// # use core::time::Duration;
1466 /// # use lightning::events::{Event, EventsProvider};
1467 /// # use lightning::ln::channelmanager::{AChannelManager, PaymentId, RecentPaymentDetails, Retry};
1468 /// # use lightning::offers::parse::Bolt12SemanticError;
1469 /// #
1470 /// # fn example<T: AChannelManager>(
1471 /// #     channel_manager: T, amount_msats: u64, absolute_expiry: Duration, retry: Retry,
1472 /// #     max_total_routing_fee_msat: Option<u64>
1473 /// # ) -> Result<(), Bolt12SemanticError> {
1474 /// # let channel_manager = channel_manager.get_cm();
1475 /// let payment_id = PaymentId([42; 32]);
1476 /// let refund = channel_manager
1477 ///     .create_refund_builder(
1478 ///         amount_msats, absolute_expiry, payment_id, retry, max_total_routing_fee_msat
1479 ///     )?
1480 /// # ;
1481 /// # // Needed for compiling for c_bindings
1482 /// # let builder: lightning::offers::refund::RefundBuilder<_> = refund.into();
1483 /// # let refund = builder
1484 ///     .description(\"coffee\".to_string())
1485 ///     .payer_note(\"refund for order 1234\".to_string())
1486 ///     .build()?;
1487 /// let bech32_refund = refund.to_string();
1488 ///
1489 /// // First the payment will be waiting on an invoice
1490 /// let expected_payment_id = payment_id;
1491 /// assert!(
1492 ///     channel_manager.list_recent_payments().iter().find(|details| matches!(
1493 ///         details,
1494 ///         RecentPaymentDetails::AwaitingInvoice { payment_id: expected_payment_id }
1495 ///     )).is_some()
1496 /// );
1497 ///
1498 /// // Once the invoice is received, a payment will be sent
1499 /// assert!(
1500 ///     channel_manager.list_recent_payments().iter().find(|details| matches!(
1501 ///         details,
1502 ///         RecentPaymentDetails::Pending { payment_id: expected_payment_id, ..  }
1503 ///     )).is_some()
1504 /// );
1505 ///
1506 /// // On the event processing thread
1507 /// channel_manager.process_pending_events(&|event| match event {
1508 ///     Event::PaymentSent { payment_id: Some(payment_id), .. } => println!(\"Paid {}\", payment_id),
1509 ///     Event::PaymentFailed { payment_id, .. } => println!(\"Failed paying {}\", payment_id),
1510 ///     // ...
1511 /// #     _ => {},
1512 /// });
1513 /// # Ok(())
1514 /// # }
1515 /// ```
1516 ///
1517 /// Use [`request_refund_payment`] to send a [`Bolt12Invoice`] for receiving the refund. Similar to
1518 /// *creating* an [`Offer`], this is stateless as it represents an inbound payment.
1519 ///
1520 /// ```
1521 /// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
1522 /// # use lightning::ln::channelmanager::AChannelManager;
1523 /// # use lightning::offers::refund::Refund;
1524 /// #
1525 /// # fn example<T: AChannelManager>(channel_manager: T, refund: &Refund) {
1526 /// # let channel_manager = channel_manager.get_cm();
1527 /// let known_payment_hash = match channel_manager.request_refund_payment(refund) {
1528 ///     Ok(invoice) => {
1529 ///         let payment_hash = invoice.payment_hash();
1530 ///         println!(\"Requesting refund payment {}\", payment_hash);
1531 ///         payment_hash
1532 ///     },
1533 ///     Err(e) => panic!(\"Unable to request payment for refund: {:?}\", e),
1534 /// };
1535 ///
1536 /// // On the event processing thread
1537 /// channel_manager.process_pending_events(&|event| match event {
1538 ///     Event::PaymentClaimable { payment_hash, purpose, .. } => match purpose {
1539 ///     \tPaymentPurpose::Bolt12RefundPayment { payment_preimage: Some(payment_preimage), .. } => {
1540 ///             assert_eq!(payment_hash, known_payment_hash);
1541 ///             println!(\"Claiming payment {}\", payment_hash);
1542 ///             channel_manager.claim_funds(payment_preimage);
1543 ///         },
1544 ///     \tPaymentPurpose::Bolt12RefundPayment { payment_preimage: None, .. } => {
1545 ///             println!(\"Unknown payment hash: {}\", payment_hash);
1546 ///     \t},
1547 ///         // ...
1548 /// #         _ => {},
1549 ///     },
1550 ///     Event::PaymentClaimed { payment_hash, amount_msat, .. } => {
1551 ///         assert_eq!(payment_hash, known_payment_hash);
1552 ///         println!(\"Claimed {} msats\", amount_msat);
1553 ///     },
1554 ///     // ...
1555 /// #     _ => {},
1556 /// });
1557 /// # }
1558 /// ```
1559 ///
1560 /// # Persistence
1561 ///
1562 /// Implements [`Writeable`] to write out all channel state to disk. Implies [`peer_disconnected`] for
1563 /// all peers during write/read (though does not modify this instance, only the instance being
1564 /// serialized). This will result in any channels which have not yet exchanged [`funding_created`] (i.e.,
1565 /// called [`funding_transaction_generated`] for outbound channels) being closed.
1566 ///
1567 /// Note that you can be a bit lazier about writing out `ChannelManager` than you can be with
1568 /// [`ChannelMonitor`]. With [`ChannelMonitor`] you MUST durably write each
1569 /// [`ChannelMonitorUpdate`] before returning from
1570 /// [`chain::Watch::watch_channel`]/[`update_channel`] or before completing async writes. With
1571 /// `ChannelManager`s, writing updates happens out-of-band (and will prevent any other
1572 /// `ChannelManager` operations from occurring during the serialization process). If the
1573 /// deserialized version is out-of-date compared to the [`ChannelMonitor`] passed by reference to
1574 /// [`read`], those channels will be force-closed based on the `ChannelMonitor` state and no funds
1575 /// will be lost (modulo on-chain transaction fees).
1576 ///
1577 /// Note that the deserializer is only implemented for `(`[`BlockHash`]`, `[`ChannelManager`]`)`, which
1578 /// tells you the last block hash which was connected. You should get the best block tip before using the manager.
1579 /// See [`chain::Listen`] and [`chain::Confirm`] for more details.
1580 ///
1581 /// # `ChannelUpdate` Messages
1582 ///
1583 /// Note that `ChannelManager` is responsible for tracking liveness of its channels and generating
1584 /// [`ChannelUpdate`] messages informing peers that the channel is temporarily disabled. To avoid
1585 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
1586 /// offline for a full minute. In order to track this, you must call
1587 /// [`timer_tick_occurred`] roughly once per minute, though it doesn't have to be perfect.
1588 ///
1589 /// # DoS Mitigation
1590 ///
1591 /// To avoid trivial DoS issues, `ChannelManager` limits the number of inbound connections and
1592 /// inbound channels without confirmed funding transactions. This may result in nodes which we do
1593 /// not have a channel with being unable to connect to us or open new channels with us if we have
1594 /// many peers with unfunded channels.
1595 ///
1596 /// Because it is an indication of trust, inbound channels which we've accepted as 0conf are
1597 /// exempted from the count of unfunded channels. Similarly, outbound channels and connections are
1598 /// never limited. Please ensure you limit the count of such channels yourself.
1599 ///
1600 /// # Type Aliases
1601 ///
1602 /// Rather than using a plain `ChannelManager`, it is preferable to use either a [`SimpleArcChannelManager`]
1603 /// a [`SimpleRefChannelManager`], for conciseness. See their documentation for more details, but
1604 /// essentially you should default to using a [`SimpleRefChannelManager`], and use a
1605 /// [`SimpleArcChannelManager`] when you require a `ChannelManager` with a static lifetime, such as when
1606 /// you're using lightning-net-tokio.
1607 ///
1608 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
1609 /// [`MessageHandler`]: crate::ln::peer_handler::MessageHandler
1610 /// [`OnionMessenger`]: crate::onion_message::messenger::OnionMessenger
1611 /// [`PeerManager::read_event`]: crate::ln::peer_handler::PeerManager::read_event
1612 /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
1613 /// [`timer_tick_occurred`]: Self::timer_tick_occurred
1614 /// [`get_and_clear_needs_persistence`]: Self::get_and_clear_needs_persistence
1615 /// [`Persister`]: crate::util::persist::Persister
1616 /// [`KVStore`]: crate::util::persist::KVStore
1617 /// [`get_event_or_persistence_needed_future`]: Self::get_event_or_persistence_needed_future
1618 /// [`lightning-block-sync`]: https://docs.rs/lightning_block_sync/latest/lightning_block_sync
1619 /// [`lightning-transaction-sync`]: https://docs.rs/lightning_transaction_sync/latest/lightning_transaction_sync
1620 /// [`lightning-background-processor`]: https://docs.rs/lightning_background_processor/lightning_background_processor
1621 /// [`list_channels`]: Self::list_channels
1622 /// [`list_usable_channels`]: Self::list_usable_channels
1623 /// [`create_channel`]: Self::create_channel
1624 /// [`close_channel`]: Self::force_close_broadcasting_latest_txn
1625 /// [`force_close_broadcasting_latest_txn`]: Self::force_close_broadcasting_latest_txn
1626 /// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md
1627 /// [BOLT 12]: https://github.com/rustyrussell/lightning-rfc/blob/guilt/offers/12-offer-encoding.md
1628 /// [`list_recent_payments`]: Self::list_recent_payments
1629 /// [`abandon_payment`]: Self::abandon_payment
1630 /// [`lightning-invoice`]: https://docs.rs/lightning_invoice/latest/lightning_invoice
1631 /// [`create_inbound_payment`]: Self::create_inbound_payment
1632 /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
1633 /// [`claim_funds`]: Self::claim_funds
1634 /// [`send_payment`]: Self::send_payment
1635 /// [`offers`]: crate::offers
1636 /// [`create_offer_builder`]: Self::create_offer_builder
1637 /// [`pay_for_offer`]: Self::pay_for_offer
1638 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
1639 /// [`create_refund_builder`]: Self::create_refund_builder
1640 /// [`request_refund_payment`]: Self::request_refund_payment
1641 /// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
1642 /// [`funding_created`]: msgs::FundingCreated
1643 /// [`funding_transaction_generated`]: Self::funding_transaction_generated
1644 /// [`BlockHash`]: bitcoin::hash_types::BlockHash
1645 /// [`update_channel`]: chain::Watch::update_channel
1646 /// [`ChannelUpdate`]: msgs::ChannelUpdate
1647 /// [`read`]: ReadableArgs::read
1648 #[must_use]
1649 #[repr(C)]
1650 pub struct ChannelManager {
1651         /// A pointer to the opaque Rust object.
1652
1653         /// Nearly everywhere, inner must be non-null, however in places where
1654         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1655         pub inner: *mut nativeChannelManager,
1656         /// Indicates that this is the only struct which contains the same pointer.
1657
1658         /// Rust functions which take ownership of an object provided via an argument require
1659         /// this to be true and invalidate the object pointed to by inner.
1660         pub is_owned: bool,
1661 }
1662
1663 impl Drop for ChannelManager {
1664         fn drop(&mut self) {
1665                 if self.is_owned && !<*mut nativeChannelManager>::is_null(self.inner) {
1666                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
1667                 }
1668         }
1669 }
1670 /// Frees any resources used by the ChannelManager, if is_owned is set and inner is non-NULL.
1671 #[no_mangle]
1672 pub extern "C" fn ChannelManager_free(this_obj: ChannelManager) { }
1673 #[allow(unused)]
1674 /// Used only if an object of this type is returned as a trait impl by a method
1675 pub(crate) extern "C" fn ChannelManager_free_void(this_ptr: *mut c_void) {
1676         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelManager) };
1677 }
1678 #[allow(unused)]
1679 impl ChannelManager {
1680         pub(crate) fn get_native_ref(&self) -> &'static nativeChannelManager {
1681                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
1682         }
1683         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelManager {
1684                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
1685         }
1686         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1687         pub(crate) fn take_inner(mut self) -> *mut nativeChannelManager {
1688                 assert!(self.is_owned);
1689                 let ret = ObjOps::untweak_ptr(self.inner);
1690                 self.inner = core::ptr::null_mut();
1691                 ret
1692         }
1693 }
1694
1695 use lightning::ln::channelmanager::ChainParameters as nativeChainParametersImport;
1696 pub(crate) type nativeChainParameters = nativeChainParametersImport;
1697
1698 /// Chain-related parameters used to construct a new `ChannelManager`.
1699 ///
1700 /// Typically, the block-specific parameters are derived from the best block hash for the network,
1701 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
1702 /// are not needed when deserializing a previously constructed `ChannelManager`.
1703 #[must_use]
1704 #[repr(C)]
1705 pub struct ChainParameters {
1706         /// A pointer to the opaque Rust object.
1707
1708         /// Nearly everywhere, inner must be non-null, however in places where
1709         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1710         pub inner: *mut nativeChainParameters,
1711         /// Indicates that this is the only struct which contains the same pointer.
1712
1713         /// Rust functions which take ownership of an object provided via an argument require
1714         /// this to be true and invalidate the object pointed to by inner.
1715         pub is_owned: bool,
1716 }
1717
1718 impl Drop for ChainParameters {
1719         fn drop(&mut self) {
1720                 if self.is_owned && !<*mut nativeChainParameters>::is_null(self.inner) {
1721                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
1722                 }
1723         }
1724 }
1725 /// Frees any resources used by the ChainParameters, if is_owned is set and inner is non-NULL.
1726 #[no_mangle]
1727 pub extern "C" fn ChainParameters_free(this_obj: ChainParameters) { }
1728 #[allow(unused)]
1729 /// Used only if an object of this type is returned as a trait impl by a method
1730 pub(crate) extern "C" fn ChainParameters_free_void(this_ptr: *mut c_void) {
1731         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChainParameters) };
1732 }
1733 #[allow(unused)]
1734 impl ChainParameters {
1735         pub(crate) fn get_native_ref(&self) -> &'static nativeChainParameters {
1736                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
1737         }
1738         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChainParameters {
1739                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
1740         }
1741         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1742         pub(crate) fn take_inner(mut self) -> *mut nativeChainParameters {
1743                 assert!(self.is_owned);
1744                 let ret = ObjOps::untweak_ptr(self.inner);
1745                 self.inner = core::ptr::null_mut();
1746                 ret
1747         }
1748 }
1749 /// The network for determining the `chain_hash` in Lightning messages.
1750 #[no_mangle]
1751 pub extern "C" fn ChainParameters_get_network(this_ptr: &ChainParameters) -> crate::bitcoin::network::Network {
1752         let mut inner_val = &mut this_ptr.get_native_mut_ref().network;
1753         crate::bitcoin::network::Network::from_bitcoin(inner_val)
1754 }
1755 /// The network for determining the `chain_hash` in Lightning messages.
1756 #[no_mangle]
1757 pub extern "C" fn ChainParameters_set_network(this_ptr: &mut ChainParameters, mut val: crate::bitcoin::network::Network) {
1758         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.network = val.into_bitcoin();
1759 }
1760 /// The hash and height of the latest block successfully connected.
1761 ///
1762 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1763 #[no_mangle]
1764 pub extern "C" fn ChainParameters_get_best_block(this_ptr: &ChainParameters) -> crate::lightning::chain::BestBlock {
1765         let mut inner_val = &mut this_ptr.get_native_mut_ref().best_block;
1766         crate::lightning::chain::BestBlock { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::chain::BestBlock<>) as *mut _) }, is_owned: false }
1767 }
1768 /// The hash and height of the latest block successfully connected.
1769 ///
1770 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
1771 #[no_mangle]
1772 pub extern "C" fn ChainParameters_set_best_block(this_ptr: &mut ChainParameters, mut val: crate::lightning::chain::BestBlock) {
1773         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.best_block = *unsafe { Box::from_raw(val.take_inner()) };
1774 }
1775 /// Constructs a new ChainParameters given each field
1776 #[must_use]
1777 #[no_mangle]
1778 pub extern "C" fn ChainParameters_new(mut network_arg: crate::bitcoin::network::Network, mut best_block_arg: crate::lightning::chain::BestBlock) -> ChainParameters {
1779         ChainParameters { inner: ObjOps::heap_alloc(nativeChainParameters {
1780                 network: network_arg.into_bitcoin(),
1781                 best_block: *unsafe { Box::from_raw(best_block_arg.take_inner()) },
1782         }), is_owned: true }
1783 }
1784 impl Clone for ChainParameters {
1785         fn clone(&self) -> Self {
1786                 Self {
1787                         inner: if <*mut nativeChainParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1788                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1789                         is_owned: true,
1790                 }
1791         }
1792 }
1793 #[allow(unused)]
1794 /// Used only if an object of this type is returned as a trait impl by a method
1795 pub(crate) extern "C" fn ChainParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1796         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativeChainParameters)).clone() })) as *mut c_void
1797 }
1798 #[no_mangle]
1799 /// Creates a copy of the ChainParameters
1800 pub extern "C" fn ChainParameters_clone(orig: &ChainParameters) -> ChainParameters {
1801         orig.clone()
1802 }
1803 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
1804 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
1805 ///
1806 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
1807 ///
1808 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
1809
1810 #[no_mangle]
1811 pub static BREAKDOWN_TIMEOUT: u16 = lightning::ln::channelmanager::BREAKDOWN_TIMEOUT;
1812 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
1813 /// HTLC's CLTV. The current default represents roughly seven hours of blocks at six blocks/hour.
1814 ///
1815 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
1816 ///
1817 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
1818
1819 #[no_mangle]
1820 pub static MIN_CLTV_EXPIRY_DELTA: u16 = lightning::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA;
1821 /// Minimum CLTV difference between the current block height and received inbound payments.
1822 /// Invoices generated for payment to us must set their `min_final_cltv_expiry_delta` field to at least
1823 /// this value.
1824
1825 #[no_mangle]
1826 pub static MIN_FINAL_CLTV_EXPIRY_DELTA: u16 = lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA;
1827 /// Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments.
1828 /// These include payments that have yet to find a successful path, or have unresolved HTLCs.
1829 #[derive(Clone)]
1830 #[must_use]
1831 #[repr(C)]
1832 pub enum RecentPaymentDetails {
1833         /// When an invoice was requested and thus a payment has not yet been sent.
1834         AwaitingInvoice {
1835                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1836                 /// a payment and ensure idempotency in LDK.
1837                 payment_id: crate::c_types::ThirtyTwoBytes,
1838         },
1839         /// When a payment is still being sent and awaiting successful delivery.
1840         Pending {
1841                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1842                 /// a payment and ensure idempotency in LDK.
1843                 payment_id: crate::c_types::ThirtyTwoBytes,
1844                 /// Hash of the payment that is currently being sent but has yet to be fulfilled or
1845                 /// abandoned.
1846                 payment_hash: crate::c_types::ThirtyTwoBytes,
1847                 /// Total amount (in msat, excluding fees) across all paths for this payment,
1848                 /// not just the amount currently inflight.
1849                 total_msat: u64,
1850         },
1851         /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
1852         /// been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the
1853         /// payment is removed from tracking.
1854         Fulfilled {
1855                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1856                 /// a payment and ensure idempotency in LDK.
1857                 payment_id: crate::c_types::ThirtyTwoBytes,
1858                 /// Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`]
1859                 /// made before LDK version 0.0.104.
1860                 payment_hash: crate::c_types::derived::COption_ThirtyTwoBytesZ,
1861         },
1862         /// After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly
1863         /// abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all
1864         /// pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated.
1865         Abandoned {
1866                 /// A user-provided identifier in [`ChannelManager::send_payment`] used to uniquely identify
1867                 /// a payment and ensure idempotency in LDK.
1868                 payment_id: crate::c_types::ThirtyTwoBytes,
1869                 /// Hash of the payment that we have given up trying to send.
1870                 payment_hash: crate::c_types::ThirtyTwoBytes,
1871         },
1872 }
1873 use lightning::ln::channelmanager::RecentPaymentDetails as RecentPaymentDetailsImport;
1874 pub(crate) type nativeRecentPaymentDetails = RecentPaymentDetailsImport;
1875
1876 impl RecentPaymentDetails {
1877         #[allow(unused)]
1878         pub(crate) fn to_native(&self) -> nativeRecentPaymentDetails {
1879                 match self {
1880                         RecentPaymentDetails::AwaitingInvoice {ref payment_id, } => {
1881                                 let mut payment_id_nonref = Clone::clone(payment_id);
1882                                 nativeRecentPaymentDetails::AwaitingInvoice {
1883                                         payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data),
1884                                 }
1885                         },
1886                         RecentPaymentDetails::Pending {ref payment_id, ref payment_hash, ref total_msat, } => {
1887                                 let mut payment_id_nonref = Clone::clone(payment_id);
1888                                 let mut payment_hash_nonref = Clone::clone(payment_hash);
1889                                 let mut total_msat_nonref = Clone::clone(total_msat);
1890                                 nativeRecentPaymentDetails::Pending {
1891                                         payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data),
1892                                         payment_hash: ::lightning::ln::types::PaymentHash(payment_hash_nonref.data),
1893                                         total_msat: total_msat_nonref,
1894                                 }
1895                         },
1896                         RecentPaymentDetails::Fulfilled {ref payment_id, ref payment_hash, } => {
1897                                 let mut payment_id_nonref = Clone::clone(payment_id);
1898                                 let mut payment_hash_nonref = Clone::clone(payment_hash);
1899                                 let mut local_payment_hash_nonref = { /*payment_hash_nonref*/ let payment_hash_nonref_opt = payment_hash_nonref; if payment_hash_nonref_opt.is_none() { None } else { Some({ { ::lightning::ln::types::PaymentHash({ payment_hash_nonref_opt.take() }.data) }})} };
1900                                 nativeRecentPaymentDetails::Fulfilled {
1901                                         payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data),
1902                                         payment_hash: local_payment_hash_nonref,
1903                                 }
1904                         },
1905                         RecentPaymentDetails::Abandoned {ref payment_id, ref payment_hash, } => {
1906                                 let mut payment_id_nonref = Clone::clone(payment_id);
1907                                 let mut payment_hash_nonref = Clone::clone(payment_hash);
1908                                 nativeRecentPaymentDetails::Abandoned {
1909                                         payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data),
1910                                         payment_hash: ::lightning::ln::types::PaymentHash(payment_hash_nonref.data),
1911                                 }
1912                         },
1913                 }
1914         }
1915         #[allow(unused)]
1916         pub(crate) fn into_native(self) -> nativeRecentPaymentDetails {
1917                 match self {
1918                         RecentPaymentDetails::AwaitingInvoice {mut payment_id, } => {
1919                                 nativeRecentPaymentDetails::AwaitingInvoice {
1920                                         payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data),
1921                                 }
1922                         },
1923                         RecentPaymentDetails::Pending {mut payment_id, mut payment_hash, mut total_msat, } => {
1924                                 nativeRecentPaymentDetails::Pending {
1925                                         payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data),
1926                                         payment_hash: ::lightning::ln::types::PaymentHash(payment_hash.data),
1927                                         total_msat: total_msat,
1928                                 }
1929                         },
1930                         RecentPaymentDetails::Fulfilled {mut payment_id, mut payment_hash, } => {
1931                                 let mut local_payment_hash = { /*payment_hash*/ let payment_hash_opt = payment_hash; if payment_hash_opt.is_none() { None } else { Some({ { ::lightning::ln::types::PaymentHash({ payment_hash_opt.take() }.data) }})} };
1932                                 nativeRecentPaymentDetails::Fulfilled {
1933                                         payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data),
1934                                         payment_hash: local_payment_hash,
1935                                 }
1936                         },
1937                         RecentPaymentDetails::Abandoned {mut payment_id, mut payment_hash, } => {
1938                                 nativeRecentPaymentDetails::Abandoned {
1939                                         payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data),
1940                                         payment_hash: ::lightning::ln::types::PaymentHash(payment_hash.data),
1941                                 }
1942                         },
1943                 }
1944         }
1945         #[allow(unused)]
1946         pub(crate) fn from_native(native: &RecentPaymentDetailsImport) -> Self {
1947                 let native = unsafe { &*(native as *const _ as *const c_void as *const nativeRecentPaymentDetails) };
1948                 match native {
1949                         nativeRecentPaymentDetails::AwaitingInvoice {ref payment_id, } => {
1950                                 let mut payment_id_nonref = Clone::clone(payment_id);
1951                                 RecentPaymentDetails::AwaitingInvoice {
1952                                         payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 },
1953                                 }
1954                         },
1955                         nativeRecentPaymentDetails::Pending {ref payment_id, ref payment_hash, ref total_msat, } => {
1956                                 let mut payment_id_nonref = Clone::clone(payment_id);
1957                                 let mut payment_hash_nonref = Clone::clone(payment_hash);
1958                                 let mut total_msat_nonref = Clone::clone(total_msat);
1959                                 RecentPaymentDetails::Pending {
1960                                         payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 },
1961                                         payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 },
1962                                         total_msat: total_msat_nonref,
1963                                 }
1964                         },
1965                         nativeRecentPaymentDetails::Fulfilled {ref payment_id, ref payment_hash, } => {
1966                                 let mut payment_id_nonref = Clone::clone(payment_id);
1967                                 let mut payment_hash_nonref = Clone::clone(payment_hash);
1968                                 let mut local_payment_hash_nonref = if payment_hash_nonref.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some( { crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.unwrap().0 } }) };
1969                                 RecentPaymentDetails::Fulfilled {
1970                                         payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 },
1971                                         payment_hash: local_payment_hash_nonref,
1972                                 }
1973                         },
1974                         nativeRecentPaymentDetails::Abandoned {ref payment_id, ref payment_hash, } => {
1975                                 let mut payment_id_nonref = Clone::clone(payment_id);
1976                                 let mut payment_hash_nonref = Clone::clone(payment_hash);
1977                                 RecentPaymentDetails::Abandoned {
1978                                         payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 },
1979                                         payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 },
1980                                 }
1981                         },
1982                 }
1983         }
1984         #[allow(unused)]
1985         pub(crate) fn native_into(native: nativeRecentPaymentDetails) -> Self {
1986                 match native {
1987                         nativeRecentPaymentDetails::AwaitingInvoice {mut payment_id, } => {
1988                                 RecentPaymentDetails::AwaitingInvoice {
1989                                         payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 },
1990                                 }
1991                         },
1992                         nativeRecentPaymentDetails::Pending {mut payment_id, mut payment_hash, mut total_msat, } => {
1993                                 RecentPaymentDetails::Pending {
1994                                         payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 },
1995                                         payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 },
1996                                         total_msat: total_msat,
1997                                 }
1998                         },
1999                         nativeRecentPaymentDetails::Fulfilled {mut payment_id, mut payment_hash, } => {
2000                                 let mut local_payment_hash = if payment_hash.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some( { crate::c_types::ThirtyTwoBytes { data: payment_hash.unwrap().0 } }) };
2001                                 RecentPaymentDetails::Fulfilled {
2002                                         payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 },
2003                                         payment_hash: local_payment_hash,
2004                                 }
2005                         },
2006                         nativeRecentPaymentDetails::Abandoned {mut payment_id, mut payment_hash, } => {
2007                                 RecentPaymentDetails::Abandoned {
2008                                         payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 },
2009                                         payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 },
2010                                 }
2011                         },
2012                 }
2013         }
2014 }
2015 /// Frees any resources used by the RecentPaymentDetails
2016 #[no_mangle]
2017 pub extern "C" fn RecentPaymentDetails_free(this_ptr: RecentPaymentDetails) { }
2018 /// Creates a copy of the RecentPaymentDetails
2019 #[no_mangle]
2020 pub extern "C" fn RecentPaymentDetails_clone(orig: &RecentPaymentDetails) -> RecentPaymentDetails {
2021         orig.clone()
2022 }
2023 #[allow(unused)]
2024 /// Used only if an object of this type is returned as a trait impl by a method
2025 pub(crate) extern "C" fn RecentPaymentDetails_clone_void(this_ptr: *const c_void) -> *mut c_void {
2026         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const RecentPaymentDetails)).clone() })) as *mut c_void
2027 }
2028 #[allow(unused)]
2029 /// Used only if an object of this type is returned as a trait impl by a method
2030 pub(crate) extern "C" fn RecentPaymentDetails_free_void(this_ptr: *mut c_void) {
2031         let _ = unsafe { Box::from_raw(this_ptr as *mut RecentPaymentDetails) };
2032 }
2033 #[no_mangle]
2034 /// Utility method to constructs a new AwaitingInvoice-variant RecentPaymentDetails
2035 pub extern "C" fn RecentPaymentDetails_awaiting_invoice(payment_id: crate::c_types::ThirtyTwoBytes) -> RecentPaymentDetails {
2036         RecentPaymentDetails::AwaitingInvoice {
2037                 payment_id,
2038         }
2039 }
2040 #[no_mangle]
2041 /// Utility method to constructs a new Pending-variant RecentPaymentDetails
2042 pub extern "C" fn RecentPaymentDetails_pending(payment_id: crate::c_types::ThirtyTwoBytes, payment_hash: crate::c_types::ThirtyTwoBytes, total_msat: u64) -> RecentPaymentDetails {
2043         RecentPaymentDetails::Pending {
2044                 payment_id,
2045                 payment_hash,
2046                 total_msat,
2047         }
2048 }
2049 #[no_mangle]
2050 /// Utility method to constructs a new Fulfilled-variant RecentPaymentDetails
2051 pub extern "C" fn RecentPaymentDetails_fulfilled(payment_id: crate::c_types::ThirtyTwoBytes, payment_hash: crate::c_types::derived::COption_ThirtyTwoBytesZ) -> RecentPaymentDetails {
2052         RecentPaymentDetails::Fulfilled {
2053                 payment_id,
2054                 payment_hash,
2055         }
2056 }
2057 #[no_mangle]
2058 /// Utility method to constructs a new Abandoned-variant RecentPaymentDetails
2059 pub extern "C" fn RecentPaymentDetails_abandoned(payment_id: crate::c_types::ThirtyTwoBytes, payment_hash: crate::c_types::ThirtyTwoBytes) -> RecentPaymentDetails {
2060         RecentPaymentDetails::Abandoned {
2061                 payment_id,
2062                 payment_hash,
2063         }
2064 }
2065 /// Get a string which allows debug introspection of a RecentPaymentDetails object
2066 pub extern "C" fn RecentPaymentDetails_debug_str_void(o: *const c_void) -> Str {
2067         alloc::format!("{:?}", unsafe { o as *const crate::lightning::ln::channelmanager::RecentPaymentDetails }).into()}
2068
2069 use lightning::ln::channelmanager::PhantomRouteHints as nativePhantomRouteHintsImport;
2070 pub(crate) type nativePhantomRouteHints = nativePhantomRouteHintsImport;
2071
2072 /// Route hints used in constructing invoices for [phantom node payents].
2073 ///
2074 /// [phantom node payments]: crate::sign::PhantomKeysManager
2075 #[must_use]
2076 #[repr(C)]
2077 pub struct PhantomRouteHints {
2078         /// A pointer to the opaque Rust object.
2079
2080         /// Nearly everywhere, inner must be non-null, however in places where
2081         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
2082         pub inner: *mut nativePhantomRouteHints,
2083         /// Indicates that this is the only struct which contains the same pointer.
2084
2085         /// Rust functions which take ownership of an object provided via an argument require
2086         /// this to be true and invalidate the object pointed to by inner.
2087         pub is_owned: bool,
2088 }
2089
2090 impl Drop for PhantomRouteHints {
2091         fn drop(&mut self) {
2092                 if self.is_owned && !<*mut nativePhantomRouteHints>::is_null(self.inner) {
2093                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
2094                 }
2095         }
2096 }
2097 /// Frees any resources used by the PhantomRouteHints, if is_owned is set and inner is non-NULL.
2098 #[no_mangle]
2099 pub extern "C" fn PhantomRouteHints_free(this_obj: PhantomRouteHints) { }
2100 #[allow(unused)]
2101 /// Used only if an object of this type is returned as a trait impl by a method
2102 pub(crate) extern "C" fn PhantomRouteHints_free_void(this_ptr: *mut c_void) {
2103         let _ = unsafe { Box::from_raw(this_ptr as *mut nativePhantomRouteHints) };
2104 }
2105 #[allow(unused)]
2106 impl PhantomRouteHints {
2107         pub(crate) fn get_native_ref(&self) -> &'static nativePhantomRouteHints {
2108                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
2109         }
2110         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativePhantomRouteHints {
2111                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
2112         }
2113         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
2114         pub(crate) fn take_inner(mut self) -> *mut nativePhantomRouteHints {
2115                 assert!(self.is_owned);
2116                 let ret = ObjOps::untweak_ptr(self.inner);
2117                 self.inner = core::ptr::null_mut();
2118                 ret
2119         }
2120 }
2121 /// The list of channels to be included in the invoice route hints.
2122 #[no_mangle]
2123 pub extern "C" fn PhantomRouteHints_get_channels(this_ptr: &PhantomRouteHints) -> crate::c_types::derived::CVec_ChannelDetailsZ {
2124         let mut inner_val = &mut this_ptr.get_native_mut_ref().channels;
2125         let mut local_inner_val = Vec::new(); for item in inner_val.iter() { local_inner_val.push( { crate::lightning::ln::channel_state::ChannelDetails { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const lightning::ln::channel_state::ChannelDetails<>) as *mut _) }, is_owned: false } }); };
2126         local_inner_val.into()
2127 }
2128 /// The list of channels to be included in the invoice route hints.
2129 #[no_mangle]
2130 pub extern "C" fn PhantomRouteHints_set_channels(this_ptr: &mut PhantomRouteHints, mut val: crate::c_types::derived::CVec_ChannelDetailsZ) {
2131         let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
2132         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channels = local_val;
2133 }
2134 /// A fake scid used for representing the phantom node's fake channel in generating the invoice
2135 /// route hints.
2136 #[no_mangle]
2137 pub extern "C" fn PhantomRouteHints_get_phantom_scid(this_ptr: &PhantomRouteHints) -> u64 {
2138         let mut inner_val = &mut this_ptr.get_native_mut_ref().phantom_scid;
2139         *inner_val
2140 }
2141 /// A fake scid used for representing the phantom node's fake channel in generating the invoice
2142 /// route hints.
2143 #[no_mangle]
2144 pub extern "C" fn PhantomRouteHints_set_phantom_scid(this_ptr: &mut PhantomRouteHints, mut val: u64) {
2145         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.phantom_scid = val;
2146 }
2147 /// The pubkey of the real backing node that would ultimately receive the payment.
2148 #[no_mangle]
2149 pub extern "C" fn PhantomRouteHints_get_real_node_pubkey(this_ptr: &PhantomRouteHints) -> crate::c_types::PublicKey {
2150         let mut inner_val = &mut this_ptr.get_native_mut_ref().real_node_pubkey;
2151         crate::c_types::PublicKey::from_rust(&inner_val)
2152 }
2153 /// The pubkey of the real backing node that would ultimately receive the payment.
2154 #[no_mangle]
2155 pub extern "C" fn PhantomRouteHints_set_real_node_pubkey(this_ptr: &mut PhantomRouteHints, mut val: crate::c_types::PublicKey) {
2156         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.real_node_pubkey = val.into_rust();
2157 }
2158 /// Constructs a new PhantomRouteHints given each field
2159 #[must_use]
2160 #[no_mangle]
2161 pub extern "C" fn PhantomRouteHints_new(mut channels_arg: crate::c_types::derived::CVec_ChannelDetailsZ, mut phantom_scid_arg: u64, mut real_node_pubkey_arg: crate::c_types::PublicKey) -> PhantomRouteHints {
2162         let mut local_channels_arg = Vec::new(); for mut item in channels_arg.into_rust().drain(..) { local_channels_arg.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
2163         PhantomRouteHints { inner: ObjOps::heap_alloc(nativePhantomRouteHints {
2164                 channels: local_channels_arg,
2165                 phantom_scid: phantom_scid_arg,
2166                 real_node_pubkey: real_node_pubkey_arg.into_rust(),
2167         }), is_owned: true }
2168 }
2169 impl Clone for PhantomRouteHints {
2170         fn clone(&self) -> Self {
2171                 Self {
2172                         inner: if <*mut nativePhantomRouteHints>::is_null(self.inner) { core::ptr::null_mut() } else {
2173                                 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
2174                         is_owned: true,
2175                 }
2176         }
2177 }
2178 #[allow(unused)]
2179 /// Used only if an object of this type is returned as a trait impl by a method
2180 pub(crate) extern "C" fn PhantomRouteHints_clone_void(this_ptr: *const c_void) -> *mut c_void {
2181         Box::into_raw(Box::new(unsafe { (*(this_ptr as *const nativePhantomRouteHints)).clone() })) as *mut c_void
2182 }
2183 #[no_mangle]
2184 /// Creates a copy of the PhantomRouteHints
2185 pub extern "C" fn PhantomRouteHints_clone(orig: &PhantomRouteHints) -> PhantomRouteHints {
2186         orig.clone()
2187 }
2188 /// Constructs a new `ChannelManager` to hold several channels and route between them.
2189 ///
2190 /// The current time or latest block header time can be provided as the `current_timestamp`.
2191 ///
2192 /// This is the main \"logic hub\" for all channel-related actions, and implements
2193 /// [`ChannelMessageHandler`].
2194 ///
2195 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
2196 ///
2197 /// Users need to notify the new `ChannelManager` when a new block is connected or
2198 /// disconnected using its [`block_connected`] and [`block_disconnected`] methods, starting
2199 /// from after [`params.best_block.block_hash`]. See [`chain::Listen`] and [`chain::Confirm`] for
2200 /// more details.
2201 ///
2202 /// [`block_connected`]: chain::Listen::block_connected
2203 /// [`block_disconnected`]: chain::Listen::block_disconnected
2204 /// [`params.best_block.block_hash`]: chain::BestBlock::block_hash
2205 #[must_use]
2206 #[no_mangle]
2207 pub extern "C" fn ChannelManager_new(mut fee_est: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut router: crate::lightning::routing::router::Router, mut logger: crate::lightning::util::logger::Logger, mut entropy_source: crate::lightning::sign::EntropySource, mut node_signer: crate::lightning::sign::NodeSigner, mut signer_provider: crate::lightning::sign::SignerProvider, mut config: crate::lightning::util::config::UserConfig, mut params: crate::lightning::ln::channelmanager::ChainParameters, mut current_timestamp: u32) -> crate::lightning::ln::channelmanager::ChannelManager {
2208         let mut ret = lightning::ln::channelmanager::ChannelManager::new(fee_est, chain_monitor, tx_broadcaster, router, logger, entropy_source, node_signer, signer_provider, *unsafe { Box::from_raw(config.take_inner()) }, *unsafe { Box::from_raw(params.take_inner()) }, current_timestamp);
2209         crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(ret), is_owned: true }
2210 }
2211
2212 /// Gets the current configuration applied to all new channels.
2213 #[must_use]
2214 #[no_mangle]
2215 pub extern "C" fn ChannelManager_get_current_default_configuration(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::util::config::UserConfig {
2216         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_current_default_configuration();
2217         crate::lightning::util::config::UserConfig { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const lightning::util::config::UserConfig<>) as *mut _) }, is_owned: false }
2218 }
2219
2220 /// Creates a new outbound channel to the given remote node and with the given value.
2221 ///
2222 /// `user_channel_id` will be provided back as in
2223 /// [`Event::FundingGenerationReady::user_channel_id`] to allow tracking of which events
2224 /// correspond with which `create_channel` call. Note that the `user_channel_id` defaults to a
2225 /// randomized value for inbound channels. `user_channel_id` has no meaning inside of LDK, it
2226 /// is simply copied to events and otherwise ignored.
2227 ///
2228 /// Raises [`APIError::APIMisuseError`] when `channel_value_satoshis` > 2**24 or `push_msat` is
2229 /// greater than `channel_value_satoshis * 1k` or `channel_value_satoshis < 1000`.
2230 ///
2231 /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be opened due to failing to
2232 /// generate a shutdown scriptpubkey or destination script set by
2233 /// [`SignerProvider::get_shutdown_scriptpubkey`] or [`SignerProvider::get_destination_script`].
2234 ///
2235 /// Note that we do not check if you are currently connected to the given peer. If no
2236 /// connection is available, the outbound `open_channel` message may fail to send, resulting in
2237 /// the channel eventually being silently forgotten (dropped on reload).
2238 ///
2239 /// If `temporary_channel_id` is specified, it will be used as the temporary channel ID of the
2240 /// channel. Otherwise, a random one will be generated for you.
2241 ///
2242 /// Returns the new Channel's temporary `channel_id`. This ID will appear as
2243 /// [`Event::FundingGenerationReady::temporary_channel_id`] and in
2244 /// [`ChannelDetails::channel_id`] until after
2245 /// [`ChannelManager::funding_transaction_generated`] is called, swapping the Channel's ID for
2246 /// one derived from the funding transaction's TXID. If the counterparty rejects the channel
2247 /// immediately, this temporary ID will appear in [`Event::ChannelClosed::channel_id`].
2248 ///
2249 /// [`Event::FundingGenerationReady::user_channel_id`]: events::Event::FundingGenerationReady::user_channel_id
2250 /// [`Event::FundingGenerationReady::temporary_channel_id`]: events::Event::FundingGenerationReady::temporary_channel_id
2251 /// [`Event::ChannelClosed::channel_id`]: events::Event::ChannelClosed::channel_id
2252 ///
2253 /// Note that temporary_channel_id (or a relevant inner pointer) may be NULL or all-0s to represent None
2254 /// Note that override_config (or a relevant inner pointer) may be NULL or all-0s to represent None
2255 #[must_use]
2256 #[no_mangle]
2257 pub extern "C" fn ChannelManager_create_channel(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut their_network_key: crate::c_types::PublicKey, mut channel_value_satoshis: u64, mut push_msat: u64, mut user_channel_id: crate::c_types::U128, mut temporary_channel_id: crate::lightning::ln::types::ChannelId, mut override_config: crate::lightning::util::config::UserConfig) -> crate::c_types::derived::CResult_ChannelIdAPIErrorZ {
2258         let mut local_temporary_channel_id = if temporary_channel_id.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(temporary_channel_id.take_inner()) } }) };
2259         let mut local_override_config = if override_config.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(override_config.take_inner()) } }) };
2260         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_channel(their_network_key.into_rust(), channel_value_satoshis, push_msat, user_channel_id.into(), local_temporary_channel_id, local_override_config);
2261         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::types::ChannelId { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2262         local_ret
2263 }
2264
2265 /// Gets the list of open channels, in random order. See [`ChannelDetails`] field documentation for
2266 /// more information.
2267 #[must_use]
2268 #[no_mangle]
2269 pub extern "C" fn ChannelManager_list_channels(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
2270         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_channels();
2271         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channel_state::ChannelDetails { inner: ObjOps::heap_alloc(item), is_owned: true } }); };
2272         local_ret.into()
2273 }
2274
2275 /// Gets the list of usable channels, in random order. Useful as an argument to
2276 /// [`Router::find_route`] to ensure non-announced channels are used.
2277 ///
2278 /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the
2279 /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria
2280 /// are.
2281 #[must_use]
2282 #[no_mangle]
2283 pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
2284         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_usable_channels();
2285         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channel_state::ChannelDetails { inner: ObjOps::heap_alloc(item), is_owned: true } }); };
2286         local_ret.into()
2287 }
2288
2289 /// Gets the list of channels we have with a given counterparty, in random order.
2290 #[must_use]
2291 #[no_mangle]
2292 pub extern "C" fn ChannelManager_list_channels_with_counterparty(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut counterparty_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CVec_ChannelDetailsZ {
2293         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_channels_with_counterparty(&counterparty_node_id.into_rust());
2294         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channel_state::ChannelDetails { inner: ObjOps::heap_alloc(item), is_owned: true } }); };
2295         local_ret.into()
2296 }
2297
2298 /// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a
2299 /// successful path, or have unresolved HTLCs.
2300 ///
2301 /// This can be useful for payments that may have been prepared, but ultimately not sent, as a
2302 /// result of a crash. If such a payment exists, is not listed here, and an
2303 /// [`Event::PaymentSent`] has not been received, you may consider resending the payment.
2304 ///
2305 /// [`Event::PaymentSent`]: events::Event::PaymentSent
2306 #[must_use]
2307 #[no_mangle]
2308 pub extern "C" fn ChannelManager_list_recent_payments(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_RecentPaymentDetailsZ {
2309         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_recent_payments();
2310         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::RecentPaymentDetails::native_into(item) }); };
2311         local_ret.into()
2312 }
2313
2314 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2315 /// will be accepted on the given channel, and after additional timeout/the closing of all
2316 /// pending HTLCs, the channel will be closed on chain.
2317 ///
2318 ///  * If we are the channel initiator, we will pay between our [`ChannelCloseMinimum`] and
2319 ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2320 ///    fee estimate.
2321 ///  * If our counterparty is the channel initiator, we will require a channel closing
2322 ///    transaction feerate of at least our [`ChannelCloseMinimum`] feerate or the feerate which
2323 ///    would appear on a force-closure transaction, whichever is lower. We will allow our
2324 ///    counterparty to pay as much fee as they'd like, however.
2325 ///
2326 /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2327 ///
2328 /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2329 /// generate a shutdown scriptpubkey or destination script set by
2330 /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2331 /// channel.
2332 ///
2333 /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2334 /// [`ChannelCloseMinimum`]: crate::chain::chaininterface::ConfirmationTarget::ChannelCloseMinimum
2335 /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2336 /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2337 #[must_use]
2338 #[no_mangle]
2339 pub extern "C" fn ChannelManager_close_channel(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, channel_id: &crate::lightning::ln::types::ChannelId, mut counterparty_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2340         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.close_channel(channel_id.get_native_ref(), &counterparty_node_id.into_rust());
2341         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2342         local_ret
2343 }
2344
2345 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
2346 /// will be accepted on the given channel, and after additional timeout/the closing of all
2347 /// pending HTLCs, the channel will be closed on chain.
2348 ///
2349 /// `target_feerate_sat_per_1000_weight` has different meanings depending on if we initiated
2350 /// the channel being closed or not:
2351 ///  * If we are the channel initiator, we will pay at least this feerate on the closing
2352 ///    transaction. The upper-bound is set by
2353 ///    [`ChannelConfig::force_close_avoidance_max_fee_satoshis`] plus our [`NonAnchorChannelFee`]
2354 ///    fee estimate (or `target_feerate_sat_per_1000_weight`, if it is greater).
2355 ///  * If our counterparty is the channel initiator, we will refuse to accept a channel closure
2356 ///    transaction feerate below `target_feerate_sat_per_1000_weight` (or the feerate which
2357 ///    will appear on a force-closure transaction, whichever is lower).
2358 ///
2359 /// The `shutdown_script` provided  will be used as the `scriptPubKey` for the closing transaction.
2360 /// Will fail if a shutdown script has already been set for this channel by
2361 /// ['ChannelHandshakeConfig::commit_upfront_shutdown_pubkey`]. The given shutdown script must
2362 /// also be compatible with our and the counterparty's features.
2363 ///
2364 /// May generate a [`SendShutdown`] message event on success, which should be relayed.
2365 ///
2366 /// Raises [`APIError::ChannelUnavailable`] if the channel cannot be closed due to failing to
2367 /// generate a shutdown scriptpubkey or destination script set by
2368 /// [`SignerProvider::get_shutdown_scriptpubkey`]. A force-closure may be needed to close the
2369 /// channel.
2370 ///
2371 /// [`ChannelConfig::force_close_avoidance_max_fee_satoshis`]: crate::util::config::ChannelConfig::force_close_avoidance_max_fee_satoshis
2372 /// [`NonAnchorChannelFee`]: crate::chain::chaininterface::ConfirmationTarget::NonAnchorChannelFee
2373 /// [`SendShutdown`]: crate::events::MessageSendEvent::SendShutdown
2374 ///
2375 /// Note that shutdown_script (or a relevant inner pointer) may be NULL or all-0s to represent None
2376 #[must_use]
2377 #[no_mangle]
2378 pub extern "C" fn ChannelManager_close_channel_with_feerate_and_script(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, channel_id: &crate::lightning::ln::types::ChannelId, mut counterparty_node_id: crate::c_types::PublicKey, mut target_feerate_sats_per_1000_weight: crate::c_types::derived::COption_u32Z, mut shutdown_script: crate::lightning::ln::script::ShutdownScript) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2379         let mut local_target_feerate_sats_per_1000_weight = if target_feerate_sats_per_1000_weight.is_some() { Some( { target_feerate_sats_per_1000_weight.take() }) } else { None };
2380         let mut local_shutdown_script = if shutdown_script.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(shutdown_script.take_inner()) } }) };
2381         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.close_channel_with_feerate_and_script(channel_id.get_native_ref(), &counterparty_node_id.into_rust(), local_target_feerate_sats_per_1000_weight, local_shutdown_script);
2382         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2383         local_ret
2384 }
2385
2386 /// Force closes a channel, immediately broadcasting the latest local transaction(s) and
2387 /// rejecting new HTLCs on the given channel. Fails if `channel_id` is unknown to
2388 /// the manager, or if the `counterparty_node_id` isn't the counterparty of the corresponding
2389 /// channel.
2390 #[must_use]
2391 #[no_mangle]
2392 pub extern "C" fn ChannelManager_force_close_broadcasting_latest_txn(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, channel_id: &crate::lightning::ln::types::ChannelId, mut counterparty_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2393         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_broadcasting_latest_txn(channel_id.get_native_ref(), &counterparty_node_id.into_rust());
2394         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2395         local_ret
2396 }
2397
2398 /// Force closes a channel, rejecting new HTLCs on the given channel but skips broadcasting
2399 /// the latest local transaction(s). Fails if `channel_id` is unknown to the manager, or if the
2400 /// `counterparty_node_id` isn't the counterparty of the corresponding channel.
2401 ///
2402 /// You can always broadcast the latest local transaction(s) via
2403 /// [`ChannelMonitor::broadcast_latest_holder_commitment_txn`].
2404 #[must_use]
2405 #[no_mangle]
2406 pub extern "C" fn ChannelManager_force_close_without_broadcasting_txn(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, channel_id: &crate::lightning::ln::types::ChannelId, mut counterparty_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2407         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_without_broadcasting_txn(channel_id.get_native_ref(), &counterparty_node_id.into_rust());
2408         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2409         local_ret
2410 }
2411
2412 /// Force close all channels, immediately broadcasting the latest local commitment transaction
2413 /// for each to the chain and rejecting new HTLCs on each.
2414 #[no_mangle]
2415 pub extern "C" fn ChannelManager_force_close_all_channels_broadcasting_latest_txn(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) {
2416         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_all_channels_broadcasting_latest_txn()
2417 }
2418
2419 /// Force close all channels rejecting new HTLCs on each but without broadcasting the latest
2420 /// local transaction(s).
2421 #[no_mangle]
2422 pub extern "C" fn ChannelManager_force_close_all_channels_without_broadcasting_txn(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) {
2423         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.force_close_all_channels_without_broadcasting_txn()
2424 }
2425
2426 /// Sends a payment along a given route.
2427 ///
2428 /// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`]
2429 /// fields for more info.
2430 ///
2431 /// May generate [`UpdateHTLCs`] message(s) event on success, which should be relayed (e.g. via
2432 /// [`PeerManager::process_events`]).
2433 ///
2434 /// # Avoiding Duplicate Payments
2435 ///
2436 /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this
2437 /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment
2438 /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an
2439 /// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a
2440 /// second payment with the same [`PaymentId`].
2441 ///
2442 /// Thus, in order to ensure duplicate payments are not sent, you should implement your own
2443 /// tracking of payments, including state to indicate once a payment has completed. Because you
2444 /// should also ensure that [`PaymentHash`]es are not re-used, for simplicity, you should
2445 /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the
2446 /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes.
2447 ///
2448 /// Additionally, in the scenario where we begin the process of sending a payment, but crash
2449 /// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're
2450 /// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See
2451 /// [`ChannelManager::list_recent_payments`] for more information.
2452 ///
2453 /// # Possible Error States on [`PaymentSendFailure`]
2454 ///
2455 /// Each path may have a different return value, and [`PaymentSendFailure`] may return a `Vec` with
2456 /// each entry matching the corresponding-index entry in the route paths, see
2457 /// [`PaymentSendFailure`] for more info.
2458 ///
2459 /// In general, a path may raise:
2460 ///  * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee,
2461 ///    node public key) is specified.
2462 ///  * [`APIError::ChannelUnavailable`] if the next-hop channel is not available as it has been
2463 ///    closed, doesn't exist, or the peer is currently disconnected.
2464 ///  * [`APIError::MonitorUpdateInProgress`] if a new monitor update failure prevented sending the
2465 ///    relevant updates.
2466 ///
2467 /// Note that depending on the type of the [`PaymentSendFailure`] the HTLC may have been
2468 /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
2469 /// different route unless you intend to pay twice!
2470 ///
2471 /// [`RouteHop`]: crate::routing::router::RouteHop
2472 /// [`Event::PaymentSent`]: events::Event::PaymentSent
2473 /// [`Event::PaymentFailed`]: events::Event::PaymentFailed
2474 /// [`UpdateHTLCs`]: events::MessageSendEvent::UpdateHTLCs
2475 /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events
2476 /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress
2477 #[must_use]
2478 #[no_mangle]
2479 pub extern "C" fn ChannelManager_send_payment_with_route(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut recipient_onion: crate::lightning::ln::outbound_payment::RecipientOnionFields, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ {
2480         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_payment_with_route(route.get_native_ref(), ::lightning::ln::types::PaymentHash(payment_hash.data), *unsafe { Box::from_raw(recipient_onion.take_inner()) }, ::lightning::ln::channelmanager::PaymentId(payment_id.data));
2481         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::PaymentSendFailure::native_into(e) }).into() };
2482         local_ret
2483 }
2484
2485 /// Similar to [`ChannelManager::send_payment_with_route`], but will automatically find a route based on
2486 /// `route_params` and retry failed payment paths based on `retry_strategy`.
2487 #[must_use]
2488 #[no_mangle]
2489 pub extern "C" fn ChannelManager_send_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut recipient_onion: crate::lightning::ln::outbound_payment::RecipientOnionFields, mut payment_id: crate::c_types::ThirtyTwoBytes, mut route_params: crate::lightning::routing::router::RouteParameters, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry) -> crate::c_types::derived::CResult_NoneRetryableSendFailureZ {
2490         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_payment(::lightning::ln::types::PaymentHash(payment_hash.data), *unsafe { Box::from_raw(recipient_onion.take_inner()) }, ::lightning::ln::channelmanager::PaymentId(payment_id.data), *unsafe { Box::from_raw(route_params.take_inner()) }, retry_strategy.into_native());
2491         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::RetryableSendFailure::native_into(e) }).into() };
2492         local_ret
2493 }
2494
2495 /// Signals that no further attempts for the given payment should occur. Useful if you have a
2496 /// pending outbound payment with retries remaining, but wish to stop retrying the payment before
2497 /// retries are exhausted.
2498 ///
2499 /// # Event Generation
2500 ///
2501 /// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon
2502 /// as there are no remaining pending HTLCs for this payment.
2503 ///
2504 /// Note that calling this method does *not* prevent a payment from succeeding. You must still
2505 /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to
2506 /// determine the ultimate status of a payment.
2507 ///
2508 /// # Requested Invoices
2509 ///
2510 /// In the case of paying a [`Bolt12Invoice`] via [`ChannelManager::pay_for_offer`], abandoning
2511 /// the payment prior to receiving the invoice will result in an [`Event::InvoiceRequestFailed`]
2512 /// and prevent any attempts at paying it once received. The other events may only be generated
2513 /// once the invoice has been received.
2514 ///
2515 /// # Restart Behavior
2516 ///
2517 /// If an [`Event::PaymentFailed`] is generated and we restart without first persisting the
2518 /// [`ChannelManager`], another [`Event::PaymentFailed`] may be generated; likewise for
2519 /// [`Event::InvoiceRequestFailed`].
2520 ///
2521 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
2522 #[no_mangle]
2523 pub extern "C" fn ChannelManager_abandon_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_id: crate::c_types::ThirtyTwoBytes) {
2524         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.abandon_payment(::lightning::ln::channelmanager::PaymentId(payment_id.data))
2525 }
2526
2527 /// Send a spontaneous payment, which is a payment that does not require the recipient to have
2528 /// generated an invoice. Optionally, you may specify the preimage. If you do choose to specify
2529 /// the preimage, it must be a cryptographically secure random value that no intermediate node
2530 /// would be able to guess -- otherwise, an intermediate node may claim the payment and it will
2531 /// never reach the recipient.
2532 ///
2533 /// See [`send_payment`] documentation for more details on the return value of this function
2534 /// and idempotency guarantees provided by the [`PaymentId`] key.
2535 ///
2536 /// Similar to regular payments, you MUST NOT reuse a `payment_preimage` value. See
2537 /// [`send_payment`] for more information about the risks of duplicate preimage usage.
2538 ///
2539 /// [`send_payment`]: Self::send_payment
2540 #[must_use]
2541 #[no_mangle]
2542 pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_preimage: crate::c_types::derived::COption_ThirtyTwoBytesZ, mut recipient_onion: crate::lightning::ln::outbound_payment::RecipientOnionFields, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_ThirtyTwoBytesPaymentSendFailureZ {
2543         let mut local_payment_preimage = { /*payment_preimage*/ let payment_preimage_opt = payment_preimage; if payment_preimage_opt.is_none() { None } else { Some({ { ::lightning::ln::types::PaymentPreimage({ payment_preimage_opt.take() }.data) }})} };
2544         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_payment(route.get_native_ref(), local_payment_preimage, *unsafe { Box::from_raw(recipient_onion.take_inner()) }, ::lightning::ln::channelmanager::PaymentId(payment_id.data));
2545         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::PaymentSendFailure::native_into(e) }).into() };
2546         local_ret
2547 }
2548
2549 /// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route
2550 /// based on `route_params` and retry failed payment paths based on `retry_strategy`.
2551 ///
2552 /// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous
2553 /// payments.
2554 ///
2555 /// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend
2556 #[must_use]
2557 #[no_mangle]
2558 pub extern "C" fn ChannelManager_send_spontaneous_payment_with_retry(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_preimage: crate::c_types::derived::COption_ThirtyTwoBytesZ, mut recipient_onion: crate::lightning::ln::outbound_payment::RecipientOnionFields, mut payment_id: crate::c_types::ThirtyTwoBytes, mut route_params: crate::lightning::routing::router::RouteParameters, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry) -> crate::c_types::derived::CResult_ThirtyTwoBytesRetryableSendFailureZ {
2559         let mut local_payment_preimage = { /*payment_preimage*/ let payment_preimage_opt = payment_preimage; if payment_preimage_opt.is_none() { None } else { Some({ { ::lightning::ln::types::PaymentPreimage({ payment_preimage_opt.take() }.data) }})} };
2560         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_payment_with_retry(local_payment_preimage, *unsafe { Box::from_raw(recipient_onion.take_inner()) }, ::lightning::ln::channelmanager::PaymentId(payment_id.data), *unsafe { Box::from_raw(route_params.take_inner()) }, retry_strategy.into_native());
2561         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::RetryableSendFailure::native_into(e) }).into() };
2562         local_ret
2563 }
2564
2565 /// Send a payment that is probing the given route for liquidity. We calculate the
2566 /// [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows
2567 /// us to easily discern them from real payments.
2568 #[must_use]
2569 #[no_mangle]
2570 pub extern "C" fn ChannelManager_send_probe(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut path: crate::lightning::routing::router::Path) -> crate::c_types::derived::CResult_C2Tuple_ThirtyTwoBytesThirtyTwoBytesZPaymentSendFailureZ {
2571         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_probe(*unsafe { Box::from_raw(path.take_inner()) });
2572         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::PaymentSendFailure::native_into(e) }).into() };
2573         local_ret
2574 }
2575
2576 /// Sends payment probes over all paths of a route that would be used to pay the given
2577 /// amount to the given `node_id`.
2578 ///
2579 /// See [`ChannelManager::send_preflight_probes`] for more information.
2580 #[must_use]
2581 #[no_mangle]
2582 pub extern "C" fn ChannelManager_send_spontaneous_preflight_probes(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut node_id: crate::c_types::PublicKey, mut amount_msat: u64, mut final_cltv_expiry_delta: u32, mut liquidity_limit_multiplier: crate::c_types::derived::COption_u64Z) -> crate::c_types::derived::CResult_CVec_C2Tuple_ThirtyTwoBytesThirtyTwoBytesZZProbeSendFailureZ {
2583         let mut local_liquidity_limit_multiplier = if liquidity_limit_multiplier.is_some() { Some( { liquidity_limit_multiplier.take() }) } else { None };
2584         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_preflight_probes(node_id.into_rust(), amount_msat, final_cltv_expiry_delta, local_liquidity_limit_multiplier);
2585         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let (mut orig_ret_0_0_0, mut orig_ret_0_0_1) = item; let mut local_ret_0_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0_1.0 }).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::ProbeSendFailure::native_into(e) }).into() };
2586         local_ret
2587 }
2588
2589 /// Sends payment probes over all paths of a route that would be used to pay a route found
2590 /// according to the given [`RouteParameters`].
2591 ///
2592 /// This may be used to send \"pre-flight\" probes, i.e., to train our scorer before conducting
2593 /// the actual payment. Note this is only useful if there likely is sufficient time for the
2594 /// probe to settle before sending out the actual payment, e.g., when waiting for user
2595 /// confirmation in a wallet UI.
2596 ///
2597 /// Otherwise, there is a chance the probe could take up some liquidity needed to complete the
2598 /// actual payment. Users should therefore be cautious and might avoid sending probes if
2599 /// liquidity is scarce and/or they don't expect the probe to return before they send the
2600 /// payment. To mitigate this issue, channels with available liquidity less than the required
2601 /// amount times the given `liquidity_limit_multiplier` won't be used to send pre-flight
2602 /// probes. If `None` is given as `liquidity_limit_multiplier`, it defaults to `3`.
2603 #[must_use]
2604 #[no_mangle]
2605 pub extern "C" fn ChannelManager_send_preflight_probes(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut route_params: crate::lightning::routing::router::RouteParameters, mut liquidity_limit_multiplier: crate::c_types::derived::COption_u64Z) -> crate::c_types::derived::CResult_CVec_C2Tuple_ThirtyTwoBytesThirtyTwoBytesZZProbeSendFailureZ {
2606         let mut local_liquidity_limit_multiplier = if liquidity_limit_multiplier.is_some() { Some( { liquidity_limit_multiplier.take() }) } else { None };
2607         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_preflight_probes(*unsafe { Box::from_raw(route_params.take_inner()) }, local_liquidity_limit_multiplier);
2608         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let (mut orig_ret_0_0_0, mut orig_ret_0_0_1) = item; let mut local_ret_0_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0_1.0 }).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::ProbeSendFailure::native_into(e) }).into() };
2609         local_ret
2610 }
2611
2612 /// Call this upon creation of a funding transaction for the given channel.
2613 ///
2614 /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
2615 /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
2616 ///
2617 /// Returns [`APIError::APIMisuseError`] if the funding transaction is not final for propagation
2618 /// across the p2p network.
2619 ///
2620 /// Returns [`APIError::ChannelUnavailable`] if a funding transaction has already been provided
2621 /// for the channel or if the channel has been closed as indicated by [`Event::ChannelClosed`].
2622 ///
2623 /// May panic if the output found in the funding transaction is duplicative with some other
2624 /// channel (note that this should be trivially prevented by using unique funding transaction
2625 /// keys per-channel).
2626 ///
2627 /// Do NOT broadcast the funding transaction yourself. When we have safely received our
2628 /// counterparty's signature the funding transaction will automatically be broadcast via the
2629 /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
2630 ///
2631 /// Note that this includes RBF or similar transaction replacement strategies - lightning does
2632 /// not currently support replacing a funding transaction on an existing channel. Instead,
2633 /// create a new channel with a conflicting funding transaction.
2634 ///
2635 /// Note to keep the miner incentives aligned in moving the blockchain forward, we recommend
2636 /// the wallet software generating the funding transaction to apply anti-fee sniping as
2637 /// implemented by Bitcoin Core wallet. See <https://bitcoinops.org/en/topics/fee-sniping/>
2638 /// for more details.
2639 ///
2640 /// [`Event::FundingGenerationReady`]: crate::events::Event::FundingGenerationReady
2641 /// [`Event::ChannelClosed`]: crate::events::Event::ChannelClosed
2642 #[must_use]
2643 #[no_mangle]
2644 pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, temporary_channel_id: &crate::lightning::ln::types::ChannelId, mut counterparty_node_id: crate::c_types::PublicKey, mut funding_transaction: crate::c_types::Transaction) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2645         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.funding_transaction_generated(temporary_channel_id.get_native_ref(), &counterparty_node_id.into_rust(), funding_transaction.into_bitcoin());
2646         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2647         local_ret
2648 }
2649
2650 /// Call this upon creation of a batch funding transaction for the given channels.
2651 ///
2652 /// Return values are identical to [`Self::funding_transaction_generated`], respective to
2653 /// each individual channel and transaction output.
2654 ///
2655 /// Do NOT broadcast the funding transaction yourself. This batch funding transaction
2656 /// will only be broadcast when we have safely received and persisted the counterparty's
2657 /// signature for each channel.
2658 ///
2659 /// If there is an error, all channels in the batch are to be considered closed.
2660 #[must_use]
2661 #[no_mangle]
2662 pub extern "C" fn ChannelManager_batch_funding_transaction_generated(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut temporary_channels: crate::c_types::derived::CVec_C2Tuple_ChannelIdPublicKeyZZ, mut funding_transaction: crate::c_types::Transaction) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2663         let mut local_temporary_channels = Vec::new(); for mut item in temporary_channels.into_rust().drain(..) { local_temporary_channels.push( { let (mut orig_temporary_channels_0_0, mut orig_temporary_channels_0_1) = item.to_rust(); let mut local_temporary_channels_0 = (*unsafe { Box::from_raw(orig_temporary_channels_0_0.take_inner()) }, orig_temporary_channels_0_1.into_rust()); local_temporary_channels_0 }); };
2664         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.batch_funding_transaction_generated(&local_temporary_channels.iter().map(|(a, b)| (a, b)).collect::<Vec<_>>()[..], funding_transaction.into_bitcoin());
2665         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2666         local_ret
2667 }
2668
2669 /// Atomically applies partial updates to the [`ChannelConfig`] of the given channels.
2670 ///
2671 /// Once the updates are applied, each eligible channel (advertised with a known short channel
2672 /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
2673 /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
2674 /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
2675 ///
2676 /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
2677 /// `counterparty_node_id` is provided.
2678 ///
2679 /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
2680 /// below [`MIN_CLTV_EXPIRY_DELTA`].
2681 ///
2682 /// If an error is returned, none of the updates should be considered applied.
2683 ///
2684 /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
2685 /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
2686 /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
2687 /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
2688 /// [`ChannelUpdate`]: msgs::ChannelUpdate
2689 /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
2690 /// [`APIMisuseError`]: APIError::APIMisuseError
2691 #[must_use]
2692 #[no_mangle]
2693 pub extern "C" fn ChannelManager_update_partial_channel_config(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut counterparty_node_id: crate::c_types::PublicKey, mut channel_ids: crate::c_types::derived::CVec_ChannelIdZ, config_update: &crate::lightning::util::config::ChannelConfigUpdate) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2694         let mut local_channel_ids = Vec::new(); for mut item in channel_ids.into_rust().drain(..) { local_channel_ids.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
2695         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_partial_channel_config(&counterparty_node_id.into_rust(), local_channel_ids, config_update.get_native_ref());
2696         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2697         local_ret
2698 }
2699
2700 /// Atomically updates the [`ChannelConfig`] for the given channels.
2701 ///
2702 /// Once the updates are applied, each eligible channel (advertised with a known short channel
2703 /// ID and a change in [`forwarding_fee_proportional_millionths`], [`forwarding_fee_base_msat`],
2704 /// or [`cltv_expiry_delta`]) has a [`BroadcastChannelUpdate`] event message generated
2705 /// containing the new [`ChannelUpdate`] message which should be broadcast to the network.
2706 ///
2707 /// Returns [`ChannelUnavailable`] when a channel is not found or an incorrect
2708 /// `counterparty_node_id` is provided.
2709 ///
2710 /// Returns [`APIMisuseError`] when a [`cltv_expiry_delta`] update is to be applied with a value
2711 /// below [`MIN_CLTV_EXPIRY_DELTA`].
2712 ///
2713 /// If an error is returned, none of the updates should be considered applied.
2714 ///
2715 /// [`forwarding_fee_proportional_millionths`]: ChannelConfig::forwarding_fee_proportional_millionths
2716 /// [`forwarding_fee_base_msat`]: ChannelConfig::forwarding_fee_base_msat
2717 /// [`cltv_expiry_delta`]: ChannelConfig::cltv_expiry_delta
2718 /// [`BroadcastChannelUpdate`]: events::MessageSendEvent::BroadcastChannelUpdate
2719 /// [`ChannelUpdate`]: msgs::ChannelUpdate
2720 /// [`ChannelUnavailable`]: APIError::ChannelUnavailable
2721 /// [`APIMisuseError`]: APIError::APIMisuseError
2722 #[must_use]
2723 #[no_mangle]
2724 pub extern "C" fn ChannelManager_update_channel_config(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut counterparty_node_id: crate::c_types::PublicKey, mut channel_ids: crate::c_types::derived::CVec_ChannelIdZ, config: &crate::lightning::util::config::ChannelConfig) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2725         let mut local_channel_ids = Vec::new(); for mut item in channel_ids.into_rust().drain(..) { local_channel_ids.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
2726         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_channel_config(&counterparty_node_id.into_rust(), local_channel_ids, config.get_native_ref());
2727         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2728         local_ret
2729 }
2730
2731 /// Attempts to forward an intercepted HTLC over the provided channel id and with the provided
2732 /// amount to forward. Should only be called in response to an [`HTLCIntercepted`] event.
2733 ///
2734 /// Intercepted HTLCs can be useful for Lightning Service Providers (LSPs) to open a just-in-time
2735 /// channel to a receiving node if the node lacks sufficient inbound liquidity.
2736 ///
2737 /// To make use of intercepted HTLCs, set [`UserConfig::accept_intercept_htlcs`] and use
2738 /// [`ChannelManager::get_intercept_scid`] to generate short channel id(s) to put in the
2739 /// receiver's invoice route hints. These route hints will signal to LDK to generate an
2740 /// [`HTLCIntercepted`] event when it receives the forwarded HTLC, and this method or
2741 /// [`ChannelManager::fail_intercepted_htlc`] MUST be called in response to the event.
2742 ///
2743 /// Note that LDK does not enforce fee requirements in `amt_to_forward_msat`, and will not stop
2744 /// you from forwarding more than you received. See
2745 /// [`HTLCIntercepted::expected_outbound_amount_msat`] for more on forwarding a different amount
2746 /// than expected.
2747 ///
2748 /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
2749 /// backwards.
2750 ///
2751 /// [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs
2752 /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
2753 /// [`HTLCIntercepted::expected_outbound_amount_msat`]: events::Event::HTLCIntercepted::expected_outbound_amount_msat
2754 #[must_use]
2755 #[no_mangle]
2756 pub extern "C" fn ChannelManager_forward_intercepted_htlc(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut intercept_id: crate::c_types::ThirtyTwoBytes, next_hop_channel_id: &crate::lightning::ln::types::ChannelId, mut next_node_id: crate::c_types::PublicKey, mut amt_to_forward_msat: u64) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2757         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.forward_intercepted_htlc(::lightning::ln::channelmanager::InterceptId(intercept_id.data), next_hop_channel_id.get_native_ref(), next_node_id.into_rust(), amt_to_forward_msat);
2758         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2759         local_ret
2760 }
2761
2762 /// Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to
2763 /// an [`HTLCIntercepted`] event. See [`ChannelManager::forward_intercepted_htlc`].
2764 ///
2765 /// Errors if the event was not handled in time, in which case the HTLC was automatically failed
2766 /// backwards.
2767 ///
2768 /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted
2769 #[must_use]
2770 #[no_mangle]
2771 pub extern "C" fn ChannelManager_fail_intercepted_htlc(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut intercept_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2772         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_intercepted_htlc(::lightning::ln::channelmanager::InterceptId(intercept_id.data));
2773         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2774         local_ret
2775 }
2776
2777 /// Processes HTLCs which are pending waiting on random forward delay.
2778 ///
2779 /// Should only really ever be called in response to a PendingHTLCsForwardable event.
2780 /// Will likely generate further events.
2781 #[no_mangle]
2782 pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) {
2783         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.process_pending_htlc_forwards()
2784 }
2785
2786 /// Performs actions which should happen on startup and roughly once per minute thereafter.
2787 ///
2788 /// This currently includes:
2789 ///  * Increasing or decreasing the on-chain feerate estimates for our outbound channels,
2790 ///  * Broadcasting [`ChannelUpdate`] messages if we've been disconnected from our peer for more
2791 ///    than a minute, informing the network that they should no longer attempt to route over
2792 ///    the channel.
2793 ///  * Expiring a channel's previous [`ChannelConfig`] if necessary to only allow forwarding HTLCs
2794 ///    with the current [`ChannelConfig`].
2795 ///  * Removing peers which have disconnected but and no longer have any channels.
2796 ///  * Force-closing and removing channels which have not completed establishment in a timely manner.
2797 ///  * Forgetting about stale outbound payments, either those that have already been fulfilled
2798 ///    or those awaiting an invoice that hasn't been delivered in the necessary amount of time.
2799 ///    The latter is determined using the system clock in `std` and the highest seen block time
2800 ///    minus two hours in `no-std`.
2801 ///
2802 /// Note that this may cause reentrancy through [`chain::Watch::update_channel`] calls or feerate
2803 /// estimate fetches.
2804 ///
2805 /// [`ChannelUpdate`]: msgs::ChannelUpdate
2806 /// [`ChannelConfig`]: crate::util::config::ChannelConfig
2807 #[no_mangle]
2808 pub extern "C" fn ChannelManager_timer_tick_occurred(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) {
2809         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.timer_tick_occurred()
2810 }
2811
2812 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
2813 /// after a PaymentClaimable event, failing the HTLC back to its origin and freeing resources
2814 /// along the path (including in our own channel on which we received it).
2815 ///
2816 /// Note that in some cases around unclean shutdown, it is possible the payment may have
2817 /// already been claimed by you via [`ChannelManager::claim_funds`] prior to you seeing (a
2818 /// second copy of) the [`events::Event::PaymentClaimable`] event. Alternatively, the payment
2819 /// may have already been failed automatically by LDK if it was nearing its expiration time.
2820 ///
2821 /// While LDK will never claim a payment automatically on your behalf (i.e. without you calling
2822 /// [`ChannelManager::claim_funds`]), you should still monitor for
2823 /// [`events::Event::PaymentClaimed`] events even for payments you intend to fail, especially on
2824 /// startup during which time claims that were in-progress at shutdown may be replayed.
2825 #[no_mangle]
2826 pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, payment_hash: *const [u8; 32]) {
2827         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_htlc_backwards(&::lightning::ln::types::PaymentHash(unsafe { *payment_hash }))
2828 }
2829
2830 /// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the
2831 /// reason for the failure.
2832 ///
2833 /// See [`FailureCode`] for valid failure codes.
2834 #[no_mangle]
2835 pub extern "C" fn ChannelManager_fail_htlc_backwards_with_reason(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, payment_hash: *const [u8; 32], mut failure_code: crate::lightning::ln::channelmanager::FailureCode) {
2836         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_htlc_backwards_with_reason(&::lightning::ln::types::PaymentHash(unsafe { *payment_hash }), failure_code.into_native())
2837 }
2838
2839 /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any
2840 /// [`MessageSendEvent`]s needed to claim the payment.
2841 ///
2842 /// This method is guaranteed to ensure the payment has been claimed but only if the current
2843 /// height is strictly below [`Event::PaymentClaimable::claim_deadline`]. To avoid race
2844 /// conditions, you should wait for an [`Event::PaymentClaimed`] before considering the payment
2845 /// successful. It will generally be available in the next [`process_pending_events`] call.
2846 ///
2847 /// Note that if you did not set an `amount_msat` when calling [`create_inbound_payment`] or
2848 /// [`create_inbound_payment_for_hash`] you must check that the amount in the `PaymentClaimable`
2849 /// event matches your expectation. If you fail to do so and call this method, you may provide
2850 /// the sender \"proof-of-payment\" when they did not fulfill the full expected payment.
2851 ///
2852 /// This function will fail the payment if it has custom TLVs with even type numbers, as we
2853 /// will assume they are unknown. If you intend to accept even custom TLVs, you should use
2854 /// [`claim_funds_with_known_custom_tlvs`].
2855 ///
2856 /// [`Event::PaymentClaimable`]: crate::events::Event::PaymentClaimable
2857 /// [`Event::PaymentClaimable::claim_deadline`]: crate::events::Event::PaymentClaimable::claim_deadline
2858 /// [`Event::PaymentClaimed`]: crate::events::Event::PaymentClaimed
2859 /// [`process_pending_events`]: EventsProvider::process_pending_events
2860 /// [`create_inbound_payment`]: Self::create_inbound_payment
2861 /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
2862 /// [`claim_funds_with_known_custom_tlvs`]: Self::claim_funds_with_known_custom_tlvs
2863 #[no_mangle]
2864 pub extern "C" fn ChannelManager_claim_funds(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_preimage: crate::c_types::ThirtyTwoBytes) {
2865         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.claim_funds(::lightning::ln::types::PaymentPreimage(payment_preimage.data))
2866 }
2867
2868 /// This is a variant of [`claim_funds`] that allows accepting a payment with custom TLVs with
2869 /// even type numbers.
2870 ///
2871 /// # Note
2872 ///
2873 /// You MUST check you've understood all even TLVs before using this to
2874 /// claim, otherwise you may unintentionally agree to some protocol you do not understand.
2875 ///
2876 /// [`claim_funds`]: Self::claim_funds
2877 #[no_mangle]
2878 pub extern "C" fn ChannelManager_claim_funds_with_known_custom_tlvs(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_preimage: crate::c_types::ThirtyTwoBytes) {
2879         unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.claim_funds_with_known_custom_tlvs(::lightning::ln::types::PaymentPreimage(payment_preimage.data))
2880 }
2881
2882 /// Gets the node_id held by this ChannelManager
2883 #[must_use]
2884 #[no_mangle]
2885 pub extern "C" fn ChannelManager_get_our_node_id(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::PublicKey {
2886         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_our_node_id();
2887         crate::c_types::PublicKey::from_rust(&ret)
2888 }
2889
2890 /// Accepts a request to open a channel after a [`Event::OpenChannelRequest`].
2891 ///
2892 /// The `temporary_channel_id` parameter indicates which inbound channel should be accepted,
2893 /// and the `counterparty_node_id` parameter is the id of the peer which has requested to open
2894 /// the channel.
2895 ///
2896 /// The `user_channel_id` parameter will be provided back in
2897 /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
2898 /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
2899 ///
2900 /// Note that this method will return an error and reject the channel, if it requires support
2901 /// for zero confirmations. Instead, `accept_inbound_channel_from_trusted_peer_0conf` must be
2902 /// used to accept such channels.
2903 ///
2904 /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
2905 /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
2906 #[must_use]
2907 #[no_mangle]
2908 pub extern "C" fn ChannelManager_accept_inbound_channel(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, temporary_channel_id: &crate::lightning::ln::types::ChannelId, mut counterparty_node_id: crate::c_types::PublicKey, mut user_channel_id: crate::c_types::U128) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2909         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.accept_inbound_channel(temporary_channel_id.get_native_ref(), &counterparty_node_id.into_rust(), user_channel_id.into());
2910         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2911         local_ret
2912 }
2913
2914 /// Accepts a request to open a channel after a [`events::Event::OpenChannelRequest`], treating
2915 /// it as confirmed immediately.
2916 ///
2917 /// The `user_channel_id` parameter will be provided back in
2918 /// [`Event::ChannelClosed::user_channel_id`] to allow tracking of which events correspond
2919 /// with which `accept_inbound_channel`/`accept_inbound_channel_from_trusted_peer_0conf` call.
2920 ///
2921 /// Unlike [`ChannelManager::accept_inbound_channel`], this method accepts the incoming channel
2922 /// and (if the counterparty agrees), enables forwarding of payments immediately.
2923 ///
2924 /// This fully trusts that the counterparty has honestly and correctly constructed the funding
2925 /// transaction and blindly assumes that it will eventually confirm.
2926 ///
2927 /// If it does not confirm before we decide to close the channel, or if the funding transaction
2928 /// does not pay to the correct script the correct amount, *you will lose funds*.
2929 ///
2930 /// [`Event::OpenChannelRequest`]: events::Event::OpenChannelRequest
2931 /// [`Event::ChannelClosed::user_channel_id`]: events::Event::ChannelClosed::user_channel_id
2932 #[must_use]
2933 #[no_mangle]
2934 pub extern "C" fn ChannelManager_accept_inbound_channel_from_trusted_peer_0conf(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, temporary_channel_id: &crate::lightning::ln::types::ChannelId, mut counterparty_node_id: crate::c_types::PublicKey, mut user_channel_id: crate::c_types::U128) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
2935         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.accept_inbound_channel_from_trusted_peer_0conf(temporary_channel_id.get_native_ref(), &counterparty_node_id.into_rust(), user_channel_id.into());
2936         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
2937         local_ret
2938 }
2939
2940 /// Creates an [`OfferBuilder`] such that the [`Offer`] it builds is recognized by the
2941 /// [`ChannelManager`] when handling [`InvoiceRequest`] messages for the offer. The offer will
2942 /// not have an expiration unless otherwise set on the builder.
2943 ///
2944 /// # Privacy
2945 ///
2946 /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the offer.
2947 /// However, if one is not found, uses a one-hop [`BlindedPath`] with
2948 /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
2949 /// the node must be announced, otherwise, there is no way to find a path to the introduction in
2950 /// order to send the [`InvoiceRequest`].
2951 ///
2952 /// Also, uses a derived signing pubkey in the offer for recipient privacy.
2953 ///
2954 /// # Limitations
2955 ///
2956 /// Requires a direct connection to the introduction node in the responding [`InvoiceRequest`]'s
2957 /// reply path.
2958 ///
2959 /// # Errors
2960 ///
2961 /// Errors if the parameterized [`Router`] is unable to create a blinded path for the offer.
2962 ///
2963 /// [`Offer`]: crate::offers::offer::Offer
2964 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
2965 #[must_use]
2966 #[no_mangle]
2967 pub extern "C" fn ChannelManager_create_offer_builder(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_OfferWithDerivedMetadataBuilderBolt12SemanticErrorZ {
2968         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_offer_builder();
2969         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::offer::OfferWithDerivedMetadataBuilder { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() };
2970         local_ret
2971 }
2972
2973 /// Creates a [`RefundBuilder`] such that the [`Refund`] it builds is recognized by the
2974 /// [`ChannelManager`] when handling [`Bolt12Invoice`] messages for the refund.
2975 ///
2976 /// # Payment
2977 ///
2978 /// The provided `payment_id` is used to ensure that only one invoice is paid for the refund.
2979 /// See [Avoiding Duplicate Payments] for other requirements once the payment has been sent.
2980 ///
2981 /// The builder will have the provided expiration set. Any changes to the expiration on the
2982 /// returned builder will not be honored by [`ChannelManager`]. For `no-std`, the highest seen
2983 /// block time minus two hours is used for the current time when determining if the refund has
2984 /// expired.
2985 ///
2986 /// To revoke the refund, use [`ChannelManager::abandon_payment`] prior to receiving the
2987 /// invoice. If abandoned, or an invoice isn't received before expiration, the payment will fail
2988 /// with an [`Event::InvoiceRequestFailed`].
2989 ///
2990 /// If `max_total_routing_fee_msat` is not specified, The default from
2991 /// [`RouteParameters::from_payment_params_and_value`] is applied.
2992 ///
2993 /// # Privacy
2994 ///
2995 /// Uses [`MessageRouter::create_blinded_paths`] to construct a [`BlindedPath`] for the refund.
2996 /// However, if one is not found, uses a one-hop [`BlindedPath`] with
2997 /// [`ChannelManager::get_our_node_id`] as the introduction node instead. In the latter case,
2998 /// the node must be announced, otherwise, there is no way to find a path to the introduction in
2999 /// order to send the [`Bolt12Invoice`].
3000 ///
3001 /// Also, uses a derived payer id in the refund for payer privacy.
3002 ///
3003 /// # Limitations
3004 ///
3005 /// Requires a direct connection to an introduction node in the responding
3006 /// [`Bolt12Invoice::payment_paths`].
3007 ///
3008 /// # Errors
3009 ///
3010 /// Errors if:
3011 /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
3012 /// - `amount_msats` is invalid, or
3013 /// - the parameterized [`Router`] is unable to create a blinded path for the refund.
3014 ///
3015 /// [`Refund`]: crate::offers::refund::Refund
3016 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3017 /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
3018 /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
3019 #[must_use]
3020 #[no_mangle]
3021 pub extern "C" fn ChannelManager_create_refund_builder(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut amount_msats: u64, mut absolute_expiry: u64, mut payment_id: crate::c_types::ThirtyTwoBytes, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry, mut max_total_routing_fee_msat: crate::c_types::derived::COption_u64Z) -> crate::c_types::derived::CResult_RefundMaybeWithDerivedMetadataBuilderBolt12SemanticErrorZ {
3022         let mut local_max_total_routing_fee_msat = if max_total_routing_fee_msat.is_some() { Some( { max_total_routing_fee_msat.take() }) } else { None };
3023         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_refund_builder(amount_msats, core::time::Duration::from_secs(absolute_expiry), ::lightning::ln::channelmanager::PaymentId(payment_id.data), retry_strategy.into_native(), local_max_total_routing_fee_msat);
3024         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::refund::RefundMaybeWithDerivedMetadataBuilder { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() };
3025         local_ret
3026 }
3027
3028 /// Pays for an [`Offer`] using the given parameters by creating an [`InvoiceRequest`] and
3029 /// enqueuing it to be sent via an onion message. [`ChannelManager`] will pay the actual
3030 /// [`Bolt12Invoice`] once it is received.
3031 ///
3032 /// Uses [`InvoiceRequestBuilder`] such that the [`InvoiceRequest`] it builds is recognized by
3033 /// the [`ChannelManager`] when handling a [`Bolt12Invoice`] message in response to the request.
3034 /// The optional parameters are used in the builder, if `Some`:
3035 /// - `quantity` for [`InvoiceRequest::quantity`] which must be set if
3036 ///   [`Offer::expects_quantity`] is `true`.
3037 /// - `amount_msats` if overpaying what is required for the given `quantity` is desired, and
3038 /// - `payer_note` for [`InvoiceRequest::payer_note`].
3039 ///
3040 /// If `max_total_routing_fee_msat` is not specified, The default from
3041 /// [`RouteParameters::from_payment_params_and_value`] is applied.
3042 ///
3043 /// # Payment
3044 ///
3045 /// The provided `payment_id` is used to ensure that only one invoice is paid for the request
3046 /// when received. See [Avoiding Duplicate Payments] for other requirements once the payment has
3047 /// been sent.
3048 ///
3049 /// To revoke the request, use [`ChannelManager::abandon_payment`] prior to receiving the
3050 /// invoice. If abandoned, or an invoice isn't received in a reasonable amount of time, the
3051 /// payment will fail with an [`Event::InvoiceRequestFailed`].
3052 ///
3053 /// # Privacy
3054 ///
3055 /// Uses a one-hop [`BlindedPath`] for the reply path with [`ChannelManager::get_our_node_id`]
3056 /// as the introduction node and a derived payer id for payer privacy. As such, currently, the
3057 /// node must be announced. Otherwise, there is no way to find a path to the introduction node
3058 /// in order to send the [`Bolt12Invoice`].
3059 ///
3060 /// # Limitations
3061 ///
3062 /// Requires a direct connection to an introduction node in [`Offer::paths`] or to
3063 /// [`Offer::signing_pubkey`], if empty. A similar restriction applies to the responding
3064 /// [`Bolt12Invoice::payment_paths`].
3065 ///
3066 /// # Errors
3067 ///
3068 /// Errors if:
3069 /// - a duplicate `payment_id` is provided given the caveats in the aforementioned link,
3070 /// - the provided parameters are invalid for the offer,
3071 /// - the offer is for an unsupported chain, or
3072 /// - the parameterized [`Router`] is unable to create a blinded reply path for the invoice
3073 ///   request.
3074 ///
3075 /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
3076 /// [`InvoiceRequest::quantity`]: crate::offers::invoice_request::InvoiceRequest::quantity
3077 /// [`InvoiceRequest::payer_note`]: crate::offers::invoice_request::InvoiceRequest::payer_note
3078 /// [`InvoiceRequestBuilder`]: crate::offers::invoice_request::InvoiceRequestBuilder
3079 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3080 /// [`Bolt12Invoice::payment_paths`]: crate::offers::invoice::Bolt12Invoice::payment_paths
3081 /// [Avoiding Duplicate Payments]: #avoiding-duplicate-payments
3082 #[must_use]
3083 #[no_mangle]
3084 pub extern "C" fn ChannelManager_pay_for_offer(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, offer: &crate::lightning::offers::offer::Offer, mut quantity: crate::c_types::derived::COption_u64Z, mut amount_msats: crate::c_types::derived::COption_u64Z, mut payer_note: crate::c_types::derived::COption_StrZ, mut payment_id: crate::c_types::ThirtyTwoBytes, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry, mut max_total_routing_fee_msat: crate::c_types::derived::COption_u64Z) -> crate::c_types::derived::CResult_NoneBolt12SemanticErrorZ {
3085         let mut local_quantity = if quantity.is_some() { Some( { quantity.take() }) } else { None };
3086         let mut local_amount_msats = if amount_msats.is_some() { Some( { amount_msats.take() }) } else { None };
3087         let mut local_payer_note = { /*payer_note*/ let payer_note_opt = payer_note; if payer_note_opt.is_none() { None } else { Some({ { { payer_note_opt.take() }.into_string() }})} };
3088         let mut local_max_total_routing_fee_msat = if max_total_routing_fee_msat.is_some() { Some( { max_total_routing_fee_msat.take() }) } else { None };
3089         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_for_offer(offer.get_native_ref(), local_quantity, local_amount_msats, local_payer_note, ::lightning::ln::channelmanager::PaymentId(payment_id.data), retry_strategy.into_native(), local_max_total_routing_fee_msat);
3090         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() };
3091         local_ret
3092 }
3093
3094 /// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
3095 /// message.
3096 ///
3097 /// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
3098 /// [`BlindedPath`] containing the [`PaymentSecret`] needed to reconstruct the corresponding
3099 /// [`PaymentPreimage`]. It is returned purely for informational purposes.
3100 ///
3101 /// # Limitations
3102 ///
3103 /// Requires a direct connection to an introduction node in [`Refund::paths`] or to
3104 /// [`Refund::payer_id`], if empty. This request is best effort; an invoice will be sent to each
3105 /// node meeting the aforementioned criteria, but there's no guarantee that they will be
3106 /// received and no retries will be made.
3107 ///
3108 /// # Errors
3109 ///
3110 /// Errors if:
3111 /// - the refund is for an unsupported chain, or
3112 /// - the parameterized [`Router`] is unable to create a blinded payment path or reply path for
3113 ///   the invoice.
3114 ///
3115 /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
3116 #[must_use]
3117 #[no_mangle]
3118 pub extern "C" fn ChannelManager_request_refund_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, refund: &crate::lightning::offers::refund::Refund) -> crate::c_types::derived::CResult_Bolt12InvoiceBolt12SemanticErrorZ {
3119         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.request_refund_payment(refund.get_native_ref());
3120         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::offers::invoice::Bolt12Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::offers::parse::Bolt12SemanticError::native_into(e) }).into() };
3121         local_ret
3122 }
3123
3124 /// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
3125 /// to pay us.
3126 ///
3127 /// This differs from [`create_inbound_payment_for_hash`] only in that it generates the
3128 /// [`PaymentHash`] and [`PaymentPreimage`] for you.
3129 ///
3130 /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`] event, which
3131 /// will have the [`PaymentClaimable::purpose`] return `Some` for [`PaymentPurpose::preimage`]. That
3132 /// should then be passed directly to [`claim_funds`].
3133 ///
3134 /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements.
3135 ///
3136 /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
3137 /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
3138 ///
3139 /// # Note
3140 ///
3141 /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
3142 /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
3143 ///
3144 /// Errors if `min_value_msat` is greater than total bitcoin supply.
3145 ///
3146 /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
3147 /// on versions of LDK prior to 0.0.114.
3148 ///
3149 /// [`claim_funds`]: Self::claim_funds
3150 /// [`PaymentClaimable`]: events::Event::PaymentClaimable
3151 /// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose
3152 /// [`PaymentPurpose::preimage`]: events::PaymentPurpose::preimage
3153 /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash
3154 #[must_use]
3155 #[no_mangle]
3156 pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_C2Tuple_ThirtyTwoBytesThirtyTwoBytesZNoneZ {
3157         let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None };
3158         let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None };
3159         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment(local_min_value_msat, invoice_expiry_delta_secs, local_min_final_cltv_expiry_delta);
3160         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
3161         local_ret
3162 }
3163
3164 /// Gets a [`PaymentSecret`] for a given [`PaymentHash`], for which the payment preimage is
3165 /// stored external to LDK.
3166 ///
3167 /// A [`PaymentClaimable`] event will only be generated if the [`PaymentSecret`] matches a
3168 /// payment secret fetched via this method or [`create_inbound_payment`], and which is at least
3169 /// the `min_value_msat` provided here, if one is provided.
3170 ///
3171 /// The [`PaymentHash`] (and corresponding [`PaymentPreimage`]) should be globally unique, though
3172 /// note that LDK will not stop you from registering duplicate payment hashes for inbound
3173 /// payments.
3174 ///
3175 /// `min_value_msat` should be set if the invoice being generated contains a value. Any payment
3176 /// received for the returned [`PaymentHash`] will be required to be at least `min_value_msat`
3177 /// before a [`PaymentClaimable`] event will be generated, ensuring that we do not provide the
3178 /// sender \"proof-of-payment\" unless they have paid the required amount.
3179 ///
3180 /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for
3181 /// in excess of the current time. This should roughly match the expiry time set in the invoice.
3182 /// After this many seconds, we will remove the inbound payment, resulting in any attempts to
3183 /// pay the invoice failing. The BOLT spec suggests 3,600 secs as a default validity time for
3184 /// invoices when no timeout is set.
3185 ///
3186 /// Note that we use block header time to time-out pending inbound payments (with some margin
3187 /// to compensate for the inaccuracy of block header timestamps). Thus, in practice we will
3188 /// accept a payment and generate a [`PaymentClaimable`] event for some time after the expiry.
3189 /// If you need exact expiry semantics, you should enforce them upon receipt of
3190 /// [`PaymentClaimable`].
3191 ///
3192 /// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta`
3193 /// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`].
3194 ///
3195 /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by
3196 /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime.
3197 ///
3198 /// # Note
3199 ///
3200 /// If you register an inbound payment with this method, then serialize the `ChannelManager`, then
3201 /// deserialize it with a node running 0.0.103 and earlier, the payment will fail to be received.
3202 ///
3203 /// Errors if `min_value_msat` is greater than total bitcoin supply.
3204 ///
3205 /// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable
3206 /// on versions of LDK prior to 0.0.114.
3207 ///
3208 /// [`create_inbound_payment`]: Self::create_inbound_payment
3209 /// [`PaymentClaimable`]: events::Event::PaymentClaimable
3210 #[must_use]
3211 #[no_mangle]
3212 pub extern "C" fn ChannelManager_create_inbound_payment_for_hash(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_ThirtyTwoBytesNoneZ {
3213         let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None };
3214         let mut local_min_final_cltv_expiry = if min_final_cltv_expiry.is_some() { Some( { min_final_cltv_expiry.take() }) } else { None };
3215         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment_for_hash(::lightning::ln::types::PaymentHash(payment_hash.data), local_min_value_msat, invoice_expiry_delta_secs, local_min_final_cltv_expiry);
3216         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
3217         local_ret
3218 }
3219
3220 /// Gets an LDK-generated payment preimage from a payment hash and payment secret that were
3221 /// previously returned from [`create_inbound_payment`].
3222 ///
3223 /// [`create_inbound_payment`]: Self::create_inbound_payment
3224 #[must_use]
3225 #[no_mangle]
3226 pub extern "C" fn ChannelManager_get_payment_preimage(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_ThirtyTwoBytesAPIErrorZ {
3227         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_payment_preimage(::lightning::ln::types::PaymentHash(payment_hash.data), ::lightning::ln::types::PaymentSecret(payment_secret.data));
3228         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() };
3229         local_ret
3230 }
3231
3232 /// Gets a fake short channel id for use in receiving [phantom node payments]. These fake scids
3233 /// are used when constructing the phantom invoice's route hints.
3234 ///
3235 /// [phantom node payments]: crate::sign::PhantomKeysManager
3236 #[must_use]
3237 #[no_mangle]
3238 pub extern "C" fn ChannelManager_get_phantom_scid(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> u64 {
3239         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_phantom_scid();
3240         ret
3241 }
3242
3243 /// Gets route hints for use in receiving [phantom node payments].
3244 ///
3245 /// [phantom node payments]: crate::sign::PhantomKeysManager
3246 #[must_use]
3247 #[no_mangle]
3248 pub extern "C" fn ChannelManager_get_phantom_route_hints(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::channelmanager::PhantomRouteHints {
3249         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_phantom_route_hints();
3250         crate::lightning::ln::channelmanager::PhantomRouteHints { inner: ObjOps::heap_alloc(ret), is_owned: true }
3251 }
3252
3253 /// Gets a fake short channel id for use in receiving intercepted payments. These fake scids are
3254 /// used when constructing the route hints for HTLCs intended to be intercepted. See
3255 /// [`ChannelManager::forward_intercepted_htlc`].
3256 ///
3257 /// Note that this method is not guaranteed to return unique values, you may need to call it a few
3258 /// times to get a unique scid.
3259 #[must_use]
3260 #[no_mangle]
3261 pub extern "C" fn ChannelManager_get_intercept_scid(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> u64 {
3262         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_intercept_scid();
3263         ret
3264 }
3265
3266 /// Gets inflight HTLC information by processing pending outbound payments that are in
3267 /// our channels. May be used during pathfinding to account for in-use channel liquidity.
3268 #[must_use]
3269 #[no_mangle]
3270 pub extern "C" fn ChannelManager_compute_inflight_htlcs(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::routing::router::InFlightHtlcs {
3271         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.compute_inflight_htlcs();
3272         crate::lightning::routing::router::InFlightHtlcs { inner: ObjOps::heap_alloc(ret), is_owned: true }
3273 }
3274
3275 impl From<nativeChannelManager> for crate::lightning::events::MessageSendEventsProvider {
3276         fn from(obj: nativeChannelManager) -> Self {
3277                 let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
3278                 let mut ret = ChannelManager_as_MessageSendEventsProvider(&rust_obj);
3279                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
3280                 core::mem::forget(rust_obj);
3281                 ret.free = Some(ChannelManager_free_void);
3282                 ret
3283         }
3284 }
3285 /// Constructs a new MessageSendEventsProvider which calls the relevant methods on this_arg.
3286 /// This copies the `inner` pointer in this_arg and thus the returned MessageSendEventsProvider must be freed before this_arg is
3287 #[no_mangle]
3288 pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: &ChannelManager) -> crate::lightning::events::MessageSendEventsProvider {
3289         crate::lightning::events::MessageSendEventsProvider {
3290                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
3291                 free: None,
3292                 get_and_clear_pending_msg_events: ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events,
3293         }
3294 }
3295
3296 #[must_use]
3297 extern "C" fn ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MessageSendEventZ {
3298         let mut ret = <nativeChannelManager as lightning::events::MessageSendEventsProvider>::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
3299         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::events::MessageSendEvent::native_into(item) }); };
3300         local_ret.into()
3301 }
3302
3303 impl From<nativeChannelManager> for crate::lightning::events::EventsProvider {
3304         fn from(obj: nativeChannelManager) -> Self {
3305                 let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
3306                 let mut ret = ChannelManager_as_EventsProvider(&rust_obj);
3307                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
3308                 core::mem::forget(rust_obj);
3309                 ret.free = Some(ChannelManager_free_void);
3310                 ret
3311         }
3312 }
3313 /// Constructs a new EventsProvider which calls the relevant methods on this_arg.
3314 /// This copies the `inner` pointer in this_arg and thus the returned EventsProvider must be freed before this_arg is
3315 #[no_mangle]
3316 pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: &ChannelManager) -> crate::lightning::events::EventsProvider {
3317         crate::lightning::events::EventsProvider {
3318                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
3319                 free: None,
3320                 process_pending_events: ChannelManager_EventsProvider_process_pending_events,
3321         }
3322 }
3323
3324 extern "C" fn ChannelManager_EventsProvider_process_pending_events(this_arg: *const c_void, mut handler: crate::lightning::events::EventHandler) {
3325         <nativeChannelManager as lightning::events::EventsProvider>::process_pending_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, handler)
3326 }
3327
3328 impl From<nativeChannelManager> for crate::lightning::chain::Listen {
3329         fn from(obj: nativeChannelManager) -> Self {
3330                 let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
3331                 let mut ret = ChannelManager_as_Listen(&rust_obj);
3332                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
3333                 core::mem::forget(rust_obj);
3334                 ret.free = Some(ChannelManager_free_void);
3335                 ret
3336         }
3337 }
3338 /// Constructs a new Listen which calls the relevant methods on this_arg.
3339 /// This copies the `inner` pointer in this_arg and thus the returned Listen must be freed before this_arg is
3340 #[no_mangle]
3341 pub extern "C" fn ChannelManager_as_Listen(this_arg: &ChannelManager) -> crate::lightning::chain::Listen {
3342         crate::lightning::chain::Listen {
3343                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
3344                 free: None,
3345                 filtered_block_connected: ChannelManager_Listen_filtered_block_connected,
3346                 block_connected: ChannelManager_Listen_block_connected,
3347                 block_disconnected: ChannelManager_Listen_block_disconnected,
3348         }
3349 }
3350
3351 extern "C" fn ChannelManager_Listen_filtered_block_connected(this_arg: *const c_void, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32) {
3352         let mut local_txdata = Vec::new(); for mut item in txdata.into_rust().drain(..) { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item.to_rust(); let mut local_txdata_0 = (orig_txdata_0_0, orig_txdata_0_1.into_bitcoin()); local_txdata_0 }); };
3353         <nativeChannelManager as lightning::chain::Listen>::filtered_block_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height)
3354 }
3355 extern "C" fn ChannelManager_Listen_block_connected(this_arg: *const c_void, mut block: crate::c_types::u8slice, mut height: u32) {
3356         <nativeChannelManager as lightning::chain::Listen>::block_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height)
3357 }
3358 extern "C" fn ChannelManager_Listen_block_disconnected(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
3359         <nativeChannelManager as lightning::chain::Listen>::block_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
3360 }
3361
3362 impl From<nativeChannelManager> for crate::lightning::chain::Confirm {
3363         fn from(obj: nativeChannelManager) -> Self {
3364                 let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
3365                 let mut ret = ChannelManager_as_Confirm(&rust_obj);
3366                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
3367                 core::mem::forget(rust_obj);
3368                 ret.free = Some(ChannelManager_free_void);
3369                 ret
3370         }
3371 }
3372 /// Constructs a new Confirm which calls the relevant methods on this_arg.
3373 /// This copies the `inner` pointer in this_arg and thus the returned Confirm must be freed before this_arg is
3374 #[no_mangle]
3375 pub extern "C" fn ChannelManager_as_Confirm(this_arg: &ChannelManager) -> crate::lightning::chain::Confirm {
3376         crate::lightning::chain::Confirm {
3377                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
3378                 free: None,
3379                 transactions_confirmed: ChannelManager_Confirm_transactions_confirmed,
3380                 transaction_unconfirmed: ChannelManager_Confirm_transaction_unconfirmed,
3381                 best_block_updated: ChannelManager_Confirm_best_block_updated,
3382                 get_relevant_txids: ChannelManager_Confirm_get_relevant_txids,
3383         }
3384 }
3385
3386 extern "C" fn ChannelManager_Confirm_transactions_confirmed(this_arg: *const c_void, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32) {
3387         let mut local_txdata = Vec::new(); for mut item in txdata.into_rust().drain(..) { local_txdata.push( { let (mut orig_txdata_0_0, mut orig_txdata_0_1) = item.to_rust(); let mut local_txdata_0 = (orig_txdata_0_0, orig_txdata_0_1.into_bitcoin()); local_txdata_0 }); };
3388         <nativeChannelManager as lightning::chain::Confirm>::transactions_confirmed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height)
3389 }
3390 extern "C" fn ChannelManager_Confirm_transaction_unconfirmed(this_arg: *const c_void, txid: *const [u8; 32]) {
3391         <nativeChannelManager as lightning::chain::Confirm>::transaction_unconfirmed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap())
3392 }
3393 extern "C" fn ChannelManager_Confirm_best_block_updated(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
3394         <nativeChannelManager as lightning::chain::Confirm>::best_block_updated(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
3395 }
3396 #[must_use]
3397 extern "C" fn ChannelManager_Confirm_get_relevant_txids(this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_ThirtyTwoBytesu32COption_ThirtyTwoBytesZZZ {
3398         let mut ret = <nativeChannelManager as lightning::chain::Confirm>::get_relevant_txids(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
3399         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item; let mut local_orig_ret_0_2 = if orig_ret_0_2.is_none() { crate::c_types::derived::COption_ThirtyTwoBytesZ::None } else { crate::c_types::derived::COption_ThirtyTwoBytesZ::Some( { crate::c_types::ThirtyTwoBytes { data: *orig_ret_0_2.unwrap().as_ref() } }) }; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: *orig_ret_0_0.as_ref() }, orig_ret_0_1, local_orig_ret_0_2).into(); local_ret_0 }); };
3400         local_ret.into()
3401 }
3402
3403 /// Gets a [`Future`] that completes when this [`ChannelManager`] may need to be persisted or
3404 /// may have events that need processing.
3405 ///
3406 /// In order to check if this [`ChannelManager`] needs persisting, call
3407 /// [`Self::get_and_clear_needs_persistence`].
3408 ///
3409 /// Note that callbacks registered on the [`Future`] MUST NOT call back into this
3410 /// [`ChannelManager`] and should instead register actions to be taken later.
3411 #[must_use]
3412 #[no_mangle]
3413 pub extern "C" fn ChannelManager_get_event_or_persistence_needed_future(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::util::wakers::Future {
3414         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_event_or_persistence_needed_future();
3415         crate::lightning::util::wakers::Future { inner: ObjOps::heap_alloc(ret), is_owned: true }
3416 }
3417
3418 /// Returns true if this [`ChannelManager`] needs to be persisted.
3419 ///
3420 /// See [`Self::get_event_or_persistence_needed_future`] for retrieving a [`Future`] that
3421 /// indicates this should be checked.
3422 #[must_use]
3423 #[no_mangle]
3424 pub extern "C" fn ChannelManager_get_and_clear_needs_persistence(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> bool {
3425         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_and_clear_needs_persistence();
3426         ret
3427 }
3428
3429 /// Gets the latest best block which was connected either via the [`chain::Listen`] or
3430 /// [`chain::Confirm`] interfaces.
3431 #[must_use]
3432 #[no_mangle]
3433 pub extern "C" fn ChannelManager_current_best_block(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::chain::BestBlock {
3434         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.current_best_block();
3435         crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true }
3436 }
3437
3438 /// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
3439 /// [`ChannelManager`].
3440 #[must_use]
3441 #[no_mangle]
3442 pub extern "C" fn ChannelManager_node_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::NodeFeatures {
3443         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.node_features();
3444         crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
3445 }
3446
3447 /// Fetches the set of [`ChannelFeatures`] flags that are provided by or required by
3448 /// [`ChannelManager`].
3449 #[must_use]
3450 #[no_mangle]
3451 pub extern "C" fn ChannelManager_channel_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::ChannelFeatures {
3452         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.channel_features();
3453         crate::lightning::ln::features::ChannelFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
3454 }
3455
3456 /// Fetches the set of [`ChannelTypeFeatures`] flags that are provided by or required by
3457 /// [`ChannelManager`].
3458 #[must_use]
3459 #[no_mangle]
3460 pub extern "C" fn ChannelManager_channel_type_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::ChannelTypeFeatures {
3461         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.channel_type_features();
3462         crate::lightning::ln::features::ChannelTypeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
3463 }
3464
3465 /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
3466 /// [`ChannelManager`].
3467 #[must_use]
3468 #[no_mangle]
3469 pub extern "C" fn ChannelManager_init_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::InitFeatures {
3470         let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.init_features();
3471         crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
3472 }
3473
3474 impl From<nativeChannelManager> for crate::lightning::ln::msgs::ChannelMessageHandler {
3475         fn from(obj: nativeChannelManager) -> Self {
3476                 let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
3477                 let mut ret = ChannelManager_as_ChannelMessageHandler(&rust_obj);
3478                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
3479                 core::mem::forget(rust_obj);
3480                 ret.free = Some(ChannelManager_free_void);
3481                 ret
3482         }
3483 }
3484 /// Constructs a new ChannelMessageHandler which calls the relevant methods on this_arg.
3485 /// This copies the `inner` pointer in this_arg and thus the returned ChannelMessageHandler must be freed before this_arg is
3486 #[no_mangle]
3487 pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelManager) -> crate::lightning::ln::msgs::ChannelMessageHandler {
3488         crate::lightning::ln::msgs::ChannelMessageHandler {
3489                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
3490                 free: None,
3491                 handle_open_channel: ChannelManager_ChannelMessageHandler_handle_open_channel,
3492                 handle_open_channel_v2: ChannelManager_ChannelMessageHandler_handle_open_channel_v2,
3493                 handle_accept_channel: ChannelManager_ChannelMessageHandler_handle_accept_channel,
3494                 handle_accept_channel_v2: ChannelManager_ChannelMessageHandler_handle_accept_channel_v2,
3495                 handle_funding_created: ChannelManager_ChannelMessageHandler_handle_funding_created,
3496                 handle_funding_signed: ChannelManager_ChannelMessageHandler_handle_funding_signed,
3497                 handle_channel_ready: ChannelManager_ChannelMessageHandler_handle_channel_ready,
3498                 handle_shutdown: ChannelManager_ChannelMessageHandler_handle_shutdown,
3499                 handle_closing_signed: ChannelManager_ChannelMessageHandler_handle_closing_signed,
3500                 handle_stfu: ChannelManager_ChannelMessageHandler_handle_stfu,
3501                 handle_tx_add_input: ChannelManager_ChannelMessageHandler_handle_tx_add_input,
3502                 handle_tx_add_output: ChannelManager_ChannelMessageHandler_handle_tx_add_output,
3503                 handle_tx_remove_input: ChannelManager_ChannelMessageHandler_handle_tx_remove_input,
3504                 handle_tx_remove_output: ChannelManager_ChannelMessageHandler_handle_tx_remove_output,
3505                 handle_tx_complete: ChannelManager_ChannelMessageHandler_handle_tx_complete,
3506                 handle_tx_signatures: ChannelManager_ChannelMessageHandler_handle_tx_signatures,
3507                 handle_tx_init_rbf: ChannelManager_ChannelMessageHandler_handle_tx_init_rbf,
3508                 handle_tx_ack_rbf: ChannelManager_ChannelMessageHandler_handle_tx_ack_rbf,
3509                 handle_tx_abort: ChannelManager_ChannelMessageHandler_handle_tx_abort,
3510                 handle_update_add_htlc: ChannelManager_ChannelMessageHandler_handle_update_add_htlc,
3511                 handle_update_fulfill_htlc: ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc,
3512                 handle_update_fail_htlc: ChannelManager_ChannelMessageHandler_handle_update_fail_htlc,
3513                 handle_update_fail_malformed_htlc: ChannelManager_ChannelMessageHandler_handle_update_fail_malformed_htlc,
3514                 handle_commitment_signed: ChannelManager_ChannelMessageHandler_handle_commitment_signed,
3515                 handle_revoke_and_ack: ChannelManager_ChannelMessageHandler_handle_revoke_and_ack,
3516                 handle_update_fee: ChannelManager_ChannelMessageHandler_handle_update_fee,
3517                 handle_announcement_signatures: ChannelManager_ChannelMessageHandler_handle_announcement_signatures,
3518                 peer_disconnected: ChannelManager_ChannelMessageHandler_peer_disconnected,
3519                 peer_connected: ChannelManager_ChannelMessageHandler_peer_connected,
3520                 handle_channel_reestablish: ChannelManager_ChannelMessageHandler_handle_channel_reestablish,
3521                 handle_channel_update: ChannelManager_ChannelMessageHandler_handle_channel_update,
3522                 handle_error: ChannelManager_ChannelMessageHandler_handle_error,
3523                 provided_node_features: ChannelManager_ChannelMessageHandler_provided_node_features,
3524                 provided_init_features: ChannelManager_ChannelMessageHandler_provided_init_features,
3525                 get_chain_hashes: ChannelManager_ChannelMessageHandler_get_chain_hashes,
3526                 MessageSendEventsProvider: crate::lightning::events::MessageSendEventsProvider {
3527                         this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
3528                         free: None,
3529                         get_and_clear_pending_msg_events: ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events,
3530                 },
3531         }
3532 }
3533
3534 extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::OpenChannel) {
3535         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3536 }
3537 extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel_v2(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::OpenChannelV2) {
3538         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_open_channel_v2(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3539 }
3540 extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AcceptChannel) {
3541         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3542 }
3543 extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel_v2(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AcceptChannelV2) {
3544         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_accept_channel_v2(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3545 }
3546 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_created(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingCreated) {
3547         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3548 }
3549 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_signed(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingSigned) {
3550         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3551 }
3552 extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_ready(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReady) {
3553         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_channel_ready(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3554 }
3555 extern "C" fn ChannelManager_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Shutdown) {
3556         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3557 }
3558 extern "C" fn ChannelManager_ChannelMessageHandler_handle_closing_signed(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ClosingSigned) {
3559         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3560 }
3561 extern "C" fn ChannelManager_ChannelMessageHandler_handle_stfu(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Stfu) {
3562         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_stfu(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3563 }
3564 extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_add_input(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxAddInput) {
3565         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_tx_add_input(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3566 }
3567 extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_add_output(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxAddOutput) {
3568         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_tx_add_output(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3569 }
3570 extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_remove_input(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxRemoveInput) {
3571         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_tx_remove_input(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3572 }
3573 extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_remove_output(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxRemoveOutput) {
3574         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_tx_remove_output(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3575 }
3576 extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_complete(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxComplete) {
3577         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_tx_complete(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3578 }
3579 extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_signatures(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxSignatures) {
3580         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_tx_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3581 }
3582 extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_init_rbf(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxInitRbf) {
3583         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_tx_init_rbf(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3584 }
3585 extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_ack_rbf(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxAckRbf) {
3586         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_tx_ack_rbf(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3587 }
3588 extern "C" fn ChannelManager_ChannelMessageHandler_handle_tx_abort(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::TxAbort) {
3589         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_tx_abort(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3590 }
3591 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_add_htlc(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateAddHTLC) {
3592         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_update_add_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3593 }
3594 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFulfillHTLC) {
3595         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_update_fulfill_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3596 }
3597 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_htlc(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailHTLC) {
3598         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_update_fail_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3599 }
3600 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_malformed_htlc(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailMalformedHTLC) {
3601         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_update_fail_malformed_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3602 }
3603 extern "C" fn ChannelManager_ChannelMessageHandler_handle_commitment_signed(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::CommitmentSigned) {
3604         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3605 }
3606 extern "C" fn ChannelManager_ChannelMessageHandler_handle_revoke_and_ack(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::RevokeAndACK) {
3607         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_revoke_and_ack(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3608 }
3609 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fee(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFee) {
3610         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3611 }
3612 extern "C" fn ChannelManager_ChannelMessageHandler_handle_announcement_signatures(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AnnouncementSignatures) {
3613         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3614 }
3615 extern "C" fn ChannelManager_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) {
3616         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust())
3617 }
3618 #[must_use]
3619 extern "C" fn ChannelManager_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Init, mut inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ {
3620         let mut ret = <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref(), inbound);
3621         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() };
3622         local_ret
3623 }
3624 extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_reestablish(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReestablish) {
3625         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3626 }
3627 extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_update(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelUpdate) {
3628         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3629 }
3630 extern "C" fn ChannelManager_ChannelMessageHandler_handle_error(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ErrorMessage) {
3631         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::handle_error(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref())
3632 }
3633 #[must_use]
3634 extern "C" fn ChannelManager_ChannelMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures {
3635         let mut ret = <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::provided_node_features(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
3636         crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
3637 }
3638 #[must_use]
3639 extern "C" fn ChannelManager_ChannelMessageHandler_provided_init_features(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) -> crate::lightning::ln::features::InitFeatures {
3640         let mut ret = <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::provided_init_features(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust());
3641         crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
3642 }
3643 #[must_use]
3644 extern "C" fn ChannelManager_ChannelMessageHandler_get_chain_hashes(this_arg: *const c_void) -> crate::c_types::derived::COption_CVec_ThirtyTwoBytesZZ {
3645         let mut ret = <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler>::get_chain_hashes(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
3646         let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_CVec_ThirtyTwoBytesZZ::None } else { crate::c_types::derived::COption_CVec_ThirtyTwoBytesZZ::Some( { let mut local_ret_0 = Vec::new(); for mut item in ret.unwrap().drain(..) { local_ret_0.push( { crate::c_types::ThirtyTwoBytes { data: *item.as_ref() } }); }; local_ret_0.into() }) };
3647         local_ret
3648 }
3649
3650 impl From<nativeChannelManager> for crate::lightning::onion_message::offers::OffersMessageHandler {
3651         fn from(obj: nativeChannelManager) -> Self {
3652                 let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
3653                 let mut ret = ChannelManager_as_OffersMessageHandler(&rust_obj);
3654                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
3655                 core::mem::forget(rust_obj);
3656                 ret.free = Some(ChannelManager_free_void);
3657                 ret
3658         }
3659 }
3660 /// Constructs a new OffersMessageHandler which calls the relevant methods on this_arg.
3661 /// This copies the `inner` pointer in this_arg and thus the returned OffersMessageHandler must be freed before this_arg is
3662 #[no_mangle]
3663 pub extern "C" fn ChannelManager_as_OffersMessageHandler(this_arg: &ChannelManager) -> crate::lightning::onion_message::offers::OffersMessageHandler {
3664         crate::lightning::onion_message::offers::OffersMessageHandler {
3665                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
3666                 free: None,
3667                 handle_message: ChannelManager_OffersMessageHandler_handle_message,
3668                 release_pending_messages: ChannelManager_OffersMessageHandler_release_pending_messages,
3669         }
3670 }
3671
3672 #[must_use]
3673 extern "C" fn ChannelManager_OffersMessageHandler_handle_message(this_arg: *const c_void, mut message: crate::lightning::onion_message::offers::OffersMessage) -> crate::c_types::derived::COption_OffersMessageZ {
3674         let mut ret = <nativeChannelManager as lightning::onion_message::offers::OffersMessageHandler>::handle_message(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, message.into_native());
3675         let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_OffersMessageZ::None } else { crate::c_types::derived::COption_OffersMessageZ::Some( { crate::lightning::onion_message::offers::OffersMessage::native_into(ret.unwrap()) }) };
3676         local_ret
3677 }
3678 #[must_use]
3679 extern "C" fn ChannelManager_OffersMessageHandler_release_pending_messages(this_arg: *const c_void) -> crate::c_types::derived::CVec_C3Tuple_OffersMessageDestinationBlindedPathZZ {
3680         let mut ret = <nativeChannelManager as lightning::onion_message::offers::OffersMessageHandler>::release_pending_messages(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
3681         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = item; let mut local_orig_ret_0_2 = crate::lightning::blinded_path::BlindedPath { inner: if orig_ret_0_2.is_none() { core::ptr::null_mut() } else {  { ObjOps::heap_alloc((orig_ret_0_2.unwrap())) } }, is_owned: true }; let mut local_ret_0 = (crate::lightning::onion_message::offers::OffersMessage::native_into(orig_ret_0_0), crate::lightning::onion_message::messenger::Destination::native_into(orig_ret_0_1), local_orig_ret_0_2).into(); local_ret_0 }); };
3682         local_ret.into()
3683 }
3684
3685 impl From<nativeChannelManager> for crate::lightning::blinded_path::NodeIdLookUp {
3686         fn from(obj: nativeChannelManager) -> Self {
3687                 let rust_obj = crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true };
3688                 let mut ret = ChannelManager_as_NodeIdLookUp(&rust_obj);
3689                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so forget it and set ret's free() fn
3690                 core::mem::forget(rust_obj);
3691                 ret.free = Some(ChannelManager_free_void);
3692                 ret
3693         }
3694 }
3695 /// Constructs a new NodeIdLookUp which calls the relevant methods on this_arg.
3696 /// This copies the `inner` pointer in this_arg and thus the returned NodeIdLookUp must be freed before this_arg is
3697 #[no_mangle]
3698 pub extern "C" fn ChannelManager_as_NodeIdLookUp(this_arg: &ChannelManager) -> crate::lightning::blinded_path::NodeIdLookUp {
3699         crate::lightning::blinded_path::NodeIdLookUp {
3700                 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
3701                 free: None,
3702                 next_node_id: ChannelManager_NodeIdLookUp_next_node_id,
3703         }
3704 }
3705
3706 #[must_use]
3707 extern "C" fn ChannelManager_NodeIdLookUp_next_node_id(this_arg: *const c_void, mut short_channel_id: u64) -> crate::c_types::PublicKey {
3708         let mut ret = <nativeChannelManager as lightning::blinded_path::NodeIdLookUp>::next_node_id(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, short_channel_id);
3709         let mut local_ret = if ret.is_none() { crate::c_types::PublicKey::null() } else {  { crate::c_types::PublicKey::from_rust(&(ret.unwrap())) } };
3710         local_ret
3711 }
3712
3713 /// Fetches the set of [`InitFeatures`] flags that are provided by or required by
3714 /// [`ChannelManager`].
3715 #[no_mangle]
3716 pub extern "C" fn provided_init_features(config: &crate::lightning::util::config::UserConfig) -> crate::lightning::ln::features::InitFeatures {
3717         let mut ret = lightning::ln::channelmanager::provided_init_features(config.get_native_ref());
3718         crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true }
3719 }
3720
3721 #[no_mangle]
3722 /// Serialize the PhantomRouteHints object into a byte array which can be read by PhantomRouteHints_read
3723 pub extern "C" fn PhantomRouteHints_write(obj: &crate::lightning::ln::channelmanager::PhantomRouteHints) -> crate::c_types::derived::CVec_u8Z {
3724         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
3725 }
3726 #[allow(unused)]
3727 pub(crate) extern "C" fn PhantomRouteHints_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
3728         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativePhantomRouteHints) })
3729 }
3730 #[no_mangle]
3731 /// Read a PhantomRouteHints from a byte array, created by PhantomRouteHints_write
3732 pub extern "C" fn PhantomRouteHints_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PhantomRouteHintsDecodeErrorZ {
3733         let res: Result<lightning::ln::channelmanager::PhantomRouteHints, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
3734         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::PhantomRouteHints { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
3735         local_res
3736 }
3737 #[no_mangle]
3738 /// Serialize the BlindedForward object into a byte array which can be read by BlindedForward_read
3739 pub extern "C" fn BlindedForward_write(obj: &crate::lightning::ln::channelmanager::BlindedForward) -> crate::c_types::derived::CVec_u8Z {
3740         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
3741 }
3742 #[allow(unused)]
3743 pub(crate) extern "C" fn BlindedForward_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
3744         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeBlindedForward) })
3745 }
3746 #[no_mangle]
3747 /// Read a BlindedForward from a byte array, created by BlindedForward_write
3748 pub extern "C" fn BlindedForward_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BlindedForwardDecodeErrorZ {
3749         let res: Result<lightning::ln::channelmanager::BlindedForward, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
3750         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::BlindedForward { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
3751         local_res
3752 }
3753 #[no_mangle]
3754 /// Serialize the PendingHTLCRouting object into a byte array which can be read by PendingHTLCRouting_read
3755 pub extern "C" fn PendingHTLCRouting_write(obj: &crate::lightning::ln::channelmanager::PendingHTLCRouting) -> crate::c_types::derived::CVec_u8Z {
3756         crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
3757 }
3758 #[allow(unused)]
3759 pub(crate) extern "C" fn PendingHTLCRouting_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
3760         PendingHTLCRouting_write(unsafe { &*(obj as *const PendingHTLCRouting) })
3761 }
3762 #[no_mangle]
3763 /// Read a PendingHTLCRouting from a byte array, created by PendingHTLCRouting_write
3764 pub extern "C" fn PendingHTLCRouting_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PendingHTLCRoutingDecodeErrorZ {
3765         let res: Result<lightning::ln::channelmanager::PendingHTLCRouting, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
3766         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::PendingHTLCRouting::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
3767         local_res
3768 }
3769 #[no_mangle]
3770 /// Serialize the PendingHTLCInfo object into a byte array which can be read by PendingHTLCInfo_read
3771 pub extern "C" fn PendingHTLCInfo_write(obj: &crate::lightning::ln::channelmanager::PendingHTLCInfo) -> crate::c_types::derived::CVec_u8Z {
3772         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
3773 }
3774 #[allow(unused)]
3775 pub(crate) extern "C" fn PendingHTLCInfo_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
3776         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativePendingHTLCInfo) })
3777 }
3778 #[no_mangle]
3779 /// Read a PendingHTLCInfo from a byte array, created by PendingHTLCInfo_write
3780 pub extern "C" fn PendingHTLCInfo_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PendingHTLCInfoDecodeErrorZ {
3781         let res: Result<lightning::ln::channelmanager::PendingHTLCInfo, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
3782         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::PendingHTLCInfo { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
3783         local_res
3784 }
3785 #[no_mangle]
3786 /// Serialize the BlindedFailure object into a byte array which can be read by BlindedFailure_read
3787 pub extern "C" fn BlindedFailure_write(obj: &crate::lightning::ln::channelmanager::BlindedFailure) -> crate::c_types::derived::CVec_u8Z {
3788         crate::c_types::serialize_obj(&unsafe { &*obj }.to_native())
3789 }
3790 #[allow(unused)]
3791 pub(crate) extern "C" fn BlindedFailure_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
3792         BlindedFailure_write(unsafe { &*(obj as *const BlindedFailure) })
3793 }
3794 #[no_mangle]
3795 /// Read a BlindedFailure from a byte array, created by BlindedFailure_write
3796 pub extern "C" fn BlindedFailure_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BlindedFailureDecodeErrorZ {
3797         let res: Result<lightning::ln::channelmanager::BlindedFailure, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
3798         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::channelmanager::BlindedFailure::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
3799         local_res
3800 }
3801 #[no_mangle]
3802 /// Serialize the ChannelManager object into a byte array which can be read by ChannelManager_read
3803 pub extern "C" fn ChannelManager_write(obj: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_u8Z {
3804         crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
3805 }
3806 #[allow(unused)]
3807 pub(crate) extern "C" fn ChannelManager_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
3808         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelManager) })
3809 }
3810
3811 use lightning::ln::channelmanager::ChannelManagerReadArgs as nativeChannelManagerReadArgsImport;
3812 pub(crate) type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::sign::EntropySource, crate::lightning::sign::NodeSigner, crate::lightning::sign::SignerProvider, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::routing::router::Router, crate::lightning::util::logger::Logger, >;
3813
3814 /// Arguments for the creation of a ChannelManager that are not deserialized.
3815 ///
3816 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
3817 /// is:
3818 /// 1) Deserialize all stored [`ChannelMonitor`]s.
3819 /// 2) Deserialize the [`ChannelManager`] by filling in this struct and calling:
3820 ///    `<(BlockHash, ChannelManager)>::read(reader, args)`
3821 ///    This may result in closing some channels if the [`ChannelMonitor`] is newer than the stored
3822 ///    [`ChannelManager`] state to ensure no loss of funds. Thus, transactions may be broadcasted.
3823 /// 3) If you are not fetching full blocks, register all relevant [`ChannelMonitor`] outpoints the
3824 ///    same way you would handle a [`chain::Filter`] call using
3825 ///    [`ChannelMonitor::get_outputs_to_watch`] and [`ChannelMonitor::get_funding_txo`].
3826 /// 4) Reconnect blocks on your [`ChannelMonitor`]s.
3827 /// 5) Disconnect/connect blocks on the [`ChannelManager`].
3828 /// 6) Re-persist the [`ChannelMonitor`]s to ensure the latest state is on disk.
3829 ///    Note that if you're using a [`ChainMonitor`] for your [`chain::Watch`] implementation, you
3830 ///    will likely accomplish this as a side-effect of calling [`chain::Watch::watch_channel`] in
3831 ///    the next step.
3832 /// 7) Move the [`ChannelMonitor`]s into your local [`chain::Watch`]. If you're using a
3833 ///    [`ChainMonitor`], this is done by calling [`chain::Watch::watch_channel`].
3834 ///
3835 /// Note that the ordering of #4-7 is not of importance, however all four must occur before you
3836 /// call any other methods on the newly-deserialized [`ChannelManager`].
3837 ///
3838 /// Note that because some channels may be closed during deserialization, it is critical that you
3839 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
3840 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
3841 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
3842 /// not force-close the same channels but consider them live), you may end up revoking a state for
3843 /// which you've already broadcasted the transaction.
3844 ///
3845 /// [`ChainMonitor`]: crate::chain::chainmonitor::ChainMonitor
3846 #[must_use]
3847 #[repr(C)]
3848 pub struct ChannelManagerReadArgs {
3849         /// A pointer to the opaque Rust object.
3850
3851         /// Nearly everywhere, inner must be non-null, however in places where
3852         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
3853         pub inner: *mut nativeChannelManagerReadArgs,
3854         /// Indicates that this is the only struct which contains the same pointer.
3855
3856         /// Rust functions which take ownership of an object provided via an argument require
3857         /// this to be true and invalidate the object pointed to by inner.
3858         pub is_owned: bool,
3859 }
3860
3861 impl Drop for ChannelManagerReadArgs {
3862         fn drop(&mut self) {
3863                 if self.is_owned && !<*mut nativeChannelManagerReadArgs>::is_null(self.inner) {
3864                         let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
3865                 }
3866         }
3867 }
3868 /// Frees any resources used by the ChannelManagerReadArgs, if is_owned is set and inner is non-NULL.
3869 #[no_mangle]
3870 pub extern "C" fn ChannelManagerReadArgs_free(this_obj: ChannelManagerReadArgs) { }
3871 #[allow(unused)]
3872 /// Used only if an object of this type is returned as a trait impl by a method
3873 pub(crate) extern "C" fn ChannelManagerReadArgs_free_void(this_ptr: *mut c_void) {
3874         let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelManagerReadArgs) };
3875 }
3876 #[allow(unused)]
3877 impl ChannelManagerReadArgs {
3878         pub(crate) fn get_native_ref(&self) -> &'static nativeChannelManagerReadArgs {
3879                 unsafe { &*ObjOps::untweak_ptr(self.inner) }
3880         }
3881         pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelManagerReadArgs {
3882                 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
3883         }
3884         /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
3885         pub(crate) fn take_inner(mut self) -> *mut nativeChannelManagerReadArgs {
3886                 assert!(self.is_owned);
3887                 let ret = ObjOps::untweak_ptr(self.inner);
3888                 self.inner = core::ptr::null_mut();
3889                 ret
3890         }
3891 }
3892 /// A cryptographically secure source of entropy.
3893 #[no_mangle]
3894 pub extern "C" fn ChannelManagerReadArgs_get_entropy_source(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::sign::EntropySource {
3895         let mut inner_val = &mut this_ptr.get_native_mut_ref().entropy_source;
3896         inner_val
3897 }
3898 /// A cryptographically secure source of entropy.
3899 #[no_mangle]
3900 pub extern "C" fn ChannelManagerReadArgs_set_entropy_source(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::sign::EntropySource) {
3901         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.entropy_source = val;
3902 }
3903 /// A signer that is able to perform node-scoped cryptographic operations.
3904 #[no_mangle]
3905 pub extern "C" fn ChannelManagerReadArgs_get_node_signer(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::sign::NodeSigner {
3906         let mut inner_val = &mut this_ptr.get_native_mut_ref().node_signer;
3907         inner_val
3908 }
3909 /// A signer that is able to perform node-scoped cryptographic operations.
3910 #[no_mangle]
3911 pub extern "C" fn ChannelManagerReadArgs_set_node_signer(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::sign::NodeSigner) {
3912         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_signer = val;
3913 }
3914 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3915 /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
3916 /// signing data.
3917 #[no_mangle]
3918 pub extern "C" fn ChannelManagerReadArgs_get_signer_provider(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::sign::SignerProvider {
3919         let mut inner_val = &mut this_ptr.get_native_mut_ref().signer_provider;
3920         inner_val
3921 }
3922 /// The keys provider which will give us relevant keys. Some keys will be loaded during
3923 /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
3924 /// signing data.
3925 #[no_mangle]
3926 pub extern "C" fn ChannelManagerReadArgs_set_signer_provider(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::sign::SignerProvider) {
3927         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.signer_provider = val;
3928 }
3929 /// The fee_estimator for use in the ChannelManager in the future.
3930 ///
3931 /// No calls to the FeeEstimator will be made during deserialization.
3932 #[no_mangle]
3933 pub extern "C" fn ChannelManagerReadArgs_get_fee_estimator(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::chaininterface::FeeEstimator {
3934         let mut inner_val = &mut this_ptr.get_native_mut_ref().fee_estimator;
3935         inner_val
3936 }
3937 /// The fee_estimator for use in the ChannelManager in the future.
3938 ///
3939 /// No calls to the FeeEstimator will be made during deserialization.
3940 #[no_mangle]
3941 pub extern "C" fn ChannelManagerReadArgs_set_fee_estimator(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::chaininterface::FeeEstimator) {
3942         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_estimator = val;
3943 }
3944 /// The chain::Watch for use in the ChannelManager in the future.
3945 ///
3946 /// No calls to the chain::Watch will be made during deserialization. It is assumed that
3947 /// you have deserialized ChannelMonitors separately and will add them to your
3948 /// chain::Watch after deserializing this ChannelManager.
3949 #[no_mangle]
3950 pub extern "C" fn ChannelManagerReadArgs_get_chain_monitor(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::Watch {
3951         let mut inner_val = &mut this_ptr.get_native_mut_ref().chain_monitor;
3952         inner_val
3953 }
3954 /// The chain::Watch for use in the ChannelManager in the future.
3955 ///
3956 /// No calls to the chain::Watch will be made during deserialization. It is assumed that
3957 /// you have deserialized ChannelMonitors separately and will add them to your
3958 /// chain::Watch after deserializing this ChannelManager.
3959 #[no_mangle]
3960 pub extern "C" fn ChannelManagerReadArgs_set_chain_monitor(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::Watch) {
3961         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_monitor = val;
3962 }
3963 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3964 /// used to broadcast the latest local commitment transactions of channels which must be
3965 /// force-closed during deserialization.
3966 #[no_mangle]
3967 pub extern "C" fn ChannelManagerReadArgs_get_tx_broadcaster(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::chaininterface::BroadcasterInterface {
3968         let mut inner_val = &mut this_ptr.get_native_mut_ref().tx_broadcaster;
3969         inner_val
3970 }
3971 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
3972 /// used to broadcast the latest local commitment transactions of channels which must be
3973 /// force-closed during deserialization.
3974 #[no_mangle]
3975 pub extern "C" fn ChannelManagerReadArgs_set_tx_broadcaster(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::chaininterface::BroadcasterInterface) {
3976         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.tx_broadcaster = val;
3977 }
3978 /// The router which will be used in the ChannelManager in the future for finding routes
3979 /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
3980 ///
3981 /// No calls to the router will be made during deserialization.
3982 #[no_mangle]
3983 pub extern "C" fn ChannelManagerReadArgs_get_router(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::routing::router::Router {
3984         let mut inner_val = &mut this_ptr.get_native_mut_ref().router;
3985         inner_val
3986 }
3987 /// The router which will be used in the ChannelManager in the future for finding routes
3988 /// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding.
3989 ///
3990 /// No calls to the router will be made during deserialization.
3991 #[no_mangle]
3992 pub extern "C" fn ChannelManagerReadArgs_set_router(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::routing::router::Router) {
3993         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.router = val;
3994 }
3995 /// The Logger for use in the ChannelManager and which may be used to log information during
3996 /// deserialization.
3997 #[no_mangle]
3998 pub extern "C" fn ChannelManagerReadArgs_get_logger(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::util::logger::Logger {
3999         let mut inner_val = &mut this_ptr.get_native_mut_ref().logger;
4000         inner_val
4001 }
4002 /// The Logger for use in the ChannelManager and which may be used to log information during
4003 /// deserialization.
4004 #[no_mangle]
4005 pub extern "C" fn ChannelManagerReadArgs_set_logger(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::util::logger::Logger) {
4006         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.logger = val;
4007 }
4008 /// Default settings used for new channels. Any existing channels will continue to use the
4009 /// runtime settings which were stored when the ChannelManager was serialized.
4010 #[no_mangle]
4011 pub extern "C" fn ChannelManagerReadArgs_get_default_config(this_ptr: &ChannelManagerReadArgs) -> crate::lightning::util::config::UserConfig {
4012         let mut inner_val = &mut this_ptr.get_native_mut_ref().default_config;
4013         crate::lightning::util::config::UserConfig { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::util::config::UserConfig<>) as *mut _) }, is_owned: false }
4014 }
4015 /// Default settings used for new channels. Any existing channels will continue to use the
4016 /// runtime settings which were stored when the ChannelManager was serialized.
4017 #[no_mangle]
4018 pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::util::config::UserConfig) {
4019         unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.default_config = *unsafe { Box::from_raw(val.take_inner()) };
4020 }
4021 /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
4022 /// HashMap for you. This is primarily useful for C bindings where it is not practical to
4023 /// populate a HashMap directly from C.
4024 #[must_use]
4025 #[no_mangle]
4026 pub extern "C" fn ChannelManagerReadArgs_new(mut entropy_source: crate::lightning::sign::EntropySource, mut node_signer: crate::lightning::sign::NodeSigner, mut signer_provider: crate::lightning::sign::SignerProvider, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut router: crate::lightning::routing::router::Router, mut logger: crate::lightning::util::logger::Logger, mut default_config: crate::lightning::util::config::UserConfig, mut channel_monitors: crate::c_types::derived::CVec_ChannelMonitorZ) -> crate::lightning::ln::channelmanager::ChannelManagerReadArgs {
4027         let mut local_channel_monitors = Vec::new(); for mut item in channel_monitors.into_rust().drain(..) { local_channel_monitors.push( { item.get_native_mut_ref() }); };
4028         let mut ret = lightning::ln::channelmanager::ChannelManagerReadArgs::new(entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, *unsafe { Box::from_raw(default_config.take_inner()) }, local_channel_monitors);
4029         crate::lightning::ln::channelmanager::ChannelManagerReadArgs { inner: ObjOps::heap_alloc(ret), is_owned: true }
4030 }
4031
4032 #[no_mangle]
4033 /// Read a C2Tuple_ThirtyTwoBytesChannelManagerZ from a byte array, created by C2Tuple_ThirtyTwoBytesChannelManagerZ_write
4034 pub extern "C" fn C2Tuple_ThirtyTwoBytesChannelManagerZ_read(ser: crate::c_types::u8slice, arg: crate::lightning::ln::channelmanager::ChannelManagerReadArgs) -> crate::c_types::derived::CResult_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ {
4035         let arg_conv = *unsafe { Box::from_raw(arg.take_inner()) };
4036         let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager<crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::sign::EntropySource, crate::lightning::sign::NodeSigner, crate::lightning::sign::SignerProvider, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::routing::router::Router, crate::lightning::util::logger::Logger>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
4037         let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_res_0_0, mut orig_res_0_1) = o; let mut local_res_0 = (crate::c_types::ThirtyTwoBytes { data: *orig_res_0_0.as_ref() }, crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(orig_res_0_1), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
4038         local_res
4039 }