Update auto-generated bindings to latest upstream
[ldk-c-bindings] / lightning-c-bindings / src / 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 routing::router::get_route 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
20 use std::ffi::c_void;
21 use bitcoin::hashes::Hash;
22 use crate::c_types::*;
23
24
25 use lightning::ln::channelmanager::ChannelManager as nativeChannelManagerImport;
26 type nativeChannelManager = nativeChannelManagerImport<crate::chain::keysinterface::Sign, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
27
28 /// Manager which keeps track of a number of channels and sends messages to the appropriate
29 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
30 ///
31 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
32 /// to individual Channels.
33 ///
34 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
35 /// all peers during write/read (though does not modify this instance, only the instance being
36 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
37 /// called funding_transaction_generated for outbound channels).
38 ///
39 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
40 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
41 /// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
42 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
43 /// the serialization process). If the deserialized version is out-of-date compared to the
44 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
45 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
46 ///
47 /// Note that the deserializer is only implemented for (BlockHash, ChannelManager), which
48 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
49 /// the \"reorg path\" (ie call block_disconnected() until you get to a common block and then call
50 /// block_connected() to step towards your best block) upon deserialization before using the
51 /// object!
52 ///
53 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
54 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
55 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
56 /// offline for a full minute. In order to track this, you must call
57 /// timer_tick_occurred roughly once per minute, though it doesn't have to be perfect.
58 ///
59 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
60 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
61 /// essentially you should default to using a SimpleRefChannelManager, and use a
62 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
63 /// you're using lightning-net-tokio.
64 #[must_use]
65 #[repr(C)]
66 pub struct ChannelManager {
67         /// A pointer to the opaque Rust object.
68
69         /// Nearly everywhere, inner must be non-null, however in places where
70         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
71         pub inner: *mut nativeChannelManager,
72         /// Indicates that this is the only struct which contains the same pointer.
73
74         /// Rust functions which take ownership of an object provided via an argument require
75         /// this to be true and invalidate the object pointed to by inner.
76         pub is_owned: bool,
77 }
78
79 impl Drop for ChannelManager {
80         fn drop(&mut self) {
81                 if self.is_owned && !<*mut nativeChannelManager>::is_null(self.inner) {
82                         let _ = unsafe { Box::from_raw(self.inner) };
83                 }
84         }
85 }
86 /// Frees any resources used by the ChannelManager, if is_owned is set and inner is non-NULL.
87 #[no_mangle]
88 pub extern "C" fn ChannelManager_free(this_obj: ChannelManager) { }
89 #[allow(unused)]
90 /// Used only if an object of this type is returned as a trait impl by a method
91 extern "C" fn ChannelManager_free_void(this_ptr: *mut c_void) {
92         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelManager); }
93 }
94 #[allow(unused)]
95 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
96 impl ChannelManager {
97         pub(crate) fn take_inner(mut self) -> *mut nativeChannelManager {
98                 assert!(self.is_owned);
99                 let ret = self.inner;
100                 self.inner = std::ptr::null_mut();
101                 ret
102         }
103 }
104
105 use lightning::ln::channelmanager::ChainParameters as nativeChainParametersImport;
106 type nativeChainParameters = nativeChainParametersImport;
107
108 /// Chain-related parameters used to construct a new `ChannelManager`.
109 ///
110 /// Typically, the block-specific parameters are derived from the best block hash for the network,
111 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
112 /// are not needed when deserializing a previously constructed `ChannelManager`.
113 #[must_use]
114 #[repr(C)]
115 pub struct ChainParameters {
116         /// A pointer to the opaque Rust object.
117
118         /// Nearly everywhere, inner must be non-null, however in places where
119         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
120         pub inner: *mut nativeChainParameters,
121         /// Indicates that this is the only struct which contains the same pointer.
122
123         /// Rust functions which take ownership of an object provided via an argument require
124         /// this to be true and invalidate the object pointed to by inner.
125         pub is_owned: bool,
126 }
127
128 impl Drop for ChainParameters {
129         fn drop(&mut self) {
130                 if self.is_owned && !<*mut nativeChainParameters>::is_null(self.inner) {
131                         let _ = unsafe { Box::from_raw(self.inner) };
132                 }
133         }
134 }
135 /// Frees any resources used by the ChainParameters, if is_owned is set and inner is non-NULL.
136 #[no_mangle]
137 pub extern "C" fn ChainParameters_free(this_obj: ChainParameters) { }
138 #[allow(unused)]
139 /// Used only if an object of this type is returned as a trait impl by a method
140 extern "C" fn ChainParameters_free_void(this_ptr: *mut c_void) {
141         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainParameters); }
142 }
143 #[allow(unused)]
144 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
145 impl ChainParameters {
146         pub(crate) fn take_inner(mut self) -> *mut nativeChainParameters {
147                 assert!(self.is_owned);
148                 let ret = self.inner;
149                 self.inner = std::ptr::null_mut();
150                 ret
151         }
152 }
153 /// The network for determining the `chain_hash` in Lightning messages.
154 #[no_mangle]
155 pub extern "C" fn ChainParameters_get_network(this_ptr: &ChainParameters) -> crate::bitcoin::network::Network {
156         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.network;
157         crate::bitcoin::network::Network::from_bitcoin((*inner_val))
158 }
159 /// The network for determining the `chain_hash` in Lightning messages.
160 #[no_mangle]
161 pub extern "C" fn ChainParameters_set_network(this_ptr: &mut ChainParameters, mut val: crate::bitcoin::network::Network) {
162         unsafe { &mut *this_ptr.inner }.network = val.into_bitcoin();
163 }
164 /// The hash and height of the latest block successfully connected.
165 ///
166 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
167 #[no_mangle]
168 pub extern "C" fn ChainParameters_get_best_block(this_ptr: &ChainParameters) -> crate::ln::channelmanager::BestBlock {
169         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.best_block;
170         crate::ln::channelmanager::BestBlock { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
171 }
172 /// The hash and height of the latest block successfully connected.
173 ///
174 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
175 #[no_mangle]
176 pub extern "C" fn ChainParameters_set_best_block(this_ptr: &mut ChainParameters, mut val: crate::ln::channelmanager::BestBlock) {
177         unsafe { &mut *this_ptr.inner }.best_block = *unsafe { Box::from_raw(val.take_inner()) };
178 }
179 /// Constructs a new ChainParameters given each field
180 #[must_use]
181 #[no_mangle]
182 pub extern "C" fn ChainParameters_new(mut network_arg: crate::bitcoin::network::Network, mut best_block_arg: crate::ln::channelmanager::BestBlock) -> ChainParameters {
183         ChainParameters { inner: Box::into_raw(Box::new(nativeChainParameters {
184                 network: network_arg.into_bitcoin(),
185                 best_block: *unsafe { Box::from_raw(best_block_arg.take_inner()) },
186         })), is_owned: true }
187 }
188
189 use lightning::ln::channelmanager::BestBlock as nativeBestBlockImport;
190 type nativeBestBlock = nativeBestBlockImport;
191
192 /// The best known block as identified by its hash and height.
193 #[must_use]
194 #[repr(C)]
195 pub struct BestBlock {
196         /// A pointer to the opaque Rust object.
197
198         /// Nearly everywhere, inner must be non-null, however in places where
199         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
200         pub inner: *mut nativeBestBlock,
201         /// Indicates that this is the only struct which contains the same pointer.
202
203         /// Rust functions which take ownership of an object provided via an argument require
204         /// this to be true and invalidate the object pointed to by inner.
205         pub is_owned: bool,
206 }
207
208 impl Drop for BestBlock {
209         fn drop(&mut self) {
210                 if self.is_owned && !<*mut nativeBestBlock>::is_null(self.inner) {
211                         let _ = unsafe { Box::from_raw(self.inner) };
212                 }
213         }
214 }
215 /// Frees any resources used by the BestBlock, if is_owned is set and inner is non-NULL.
216 #[no_mangle]
217 pub extern "C" fn BestBlock_free(this_obj: BestBlock) { }
218 #[allow(unused)]
219 /// Used only if an object of this type is returned as a trait impl by a method
220 extern "C" fn BestBlock_free_void(this_ptr: *mut c_void) {
221         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeBestBlock); }
222 }
223 #[allow(unused)]
224 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
225 impl BestBlock {
226         pub(crate) fn take_inner(mut self) -> *mut nativeBestBlock {
227                 assert!(self.is_owned);
228                 let ret = self.inner;
229                 self.inner = std::ptr::null_mut();
230                 ret
231         }
232 }
233 impl Clone for BestBlock {
234         fn clone(&self) -> Self {
235                 Self {
236                         inner: if <*mut nativeBestBlock>::is_null(self.inner) { std::ptr::null_mut() } else {
237                                 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
238                         is_owned: true,
239                 }
240         }
241 }
242 #[allow(unused)]
243 /// Used only if an object of this type is returned as a trait impl by a method
244 pub(crate) extern "C" fn BestBlock_clone_void(this_ptr: *const c_void) -> *mut c_void {
245         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBestBlock)).clone() })) as *mut c_void
246 }
247 #[no_mangle]
248 /// Creates a copy of the BestBlock
249 pub extern "C" fn BestBlock_clone(orig: &BestBlock) -> BestBlock {
250         orig.clone()
251 }
252 /// Returns the best block from the genesis of the given network.
253 #[must_use]
254 #[no_mangle]
255 pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::Network) -> BestBlock {
256         let mut ret = lightning::ln::channelmanager::BestBlock::from_genesis(network.into_bitcoin());
257         BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true }
258 }
259
260 /// Returns the best block as identified by the given block hash and height.
261 #[must_use]
262 #[no_mangle]
263 pub extern "C" fn BestBlock_new(mut block_hash: crate::c_types::ThirtyTwoBytes, mut height: u32) -> BestBlock {
264         let mut ret = lightning::ln::channelmanager::BestBlock::new(::bitcoin::hash_types::BlockHash::from_slice(&block_hash.data[..]).unwrap(), height);
265         BestBlock { inner: Box::into_raw(Box::new(ret)), is_owned: true }
266 }
267
268 /// Returns the best block hash.
269 #[must_use]
270 #[no_mangle]
271 pub extern "C" fn BestBlock_block_hash(this_arg: &BestBlock) -> crate::c_types::ThirtyTwoBytes {
272         let mut ret = unsafe { &*this_arg.inner }.block_hash();
273         crate::c_types::ThirtyTwoBytes { data: ret.into_inner() }
274 }
275
276 /// Returns the best block height.
277 #[must_use]
278 #[no_mangle]
279 pub extern "C" fn BestBlock_height(this_arg: &BestBlock) -> u32 {
280         let mut ret = unsafe { &*this_arg.inner }.height();
281         ret
282 }
283
284 /// The amount of time in blocks we require our counterparty wait to claim their money (ie time
285 /// between when we, or our watchtower, must check for them having broadcast a theft transaction).
286 ///
287 /// This can be increased (but not decreased) through [`ChannelHandshakeConfig::our_to_self_delay`]
288 ///
289 /// [`ChannelHandshakeConfig::our_to_self_delay`]: crate::util::config::ChannelHandshakeConfig::our_to_self_delay
290
291 #[no_mangle]
292 pub static BREAKDOWN_TIMEOUT: u16 = lightning::ln::channelmanager::BREAKDOWN_TIMEOUT;
293 /// The minimum number of blocks between an inbound HTLC's CLTV and the corresponding outbound
294 /// HTLC's CLTV. The current default represents roughly six hours of blocks at six blocks/hour.
295 ///
296 /// This can be increased (but not decreased) through [`ChannelConfig::cltv_expiry_delta`]
297 ///
298 /// [`ChannelConfig::cltv_expiry_delta`]: crate::util::config::ChannelConfig::cltv_expiry_delta
299
300 #[no_mangle]
301 pub static MIN_CLTV_EXPIRY_DELTA: u16 = lightning::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA;
302
303 use lightning::ln::channelmanager::ChannelDetails as nativeChannelDetailsImport;
304 type nativeChannelDetails = nativeChannelDetailsImport;
305
306 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
307 #[must_use]
308 #[repr(C)]
309 pub struct ChannelDetails {
310         /// A pointer to the opaque Rust object.
311
312         /// Nearly everywhere, inner must be non-null, however in places where
313         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
314         pub inner: *mut nativeChannelDetails,
315         /// Indicates that this is the only struct which contains the same pointer.
316
317         /// Rust functions which take ownership of an object provided via an argument require
318         /// this to be true and invalidate the object pointed to by inner.
319         pub is_owned: bool,
320 }
321
322 impl Drop for ChannelDetails {
323         fn drop(&mut self) {
324                 if self.is_owned && !<*mut nativeChannelDetails>::is_null(self.inner) {
325                         let _ = unsafe { Box::from_raw(self.inner) };
326                 }
327         }
328 }
329 /// Frees any resources used by the ChannelDetails, if is_owned is set and inner is non-NULL.
330 #[no_mangle]
331 pub extern "C" fn ChannelDetails_free(this_obj: ChannelDetails) { }
332 #[allow(unused)]
333 /// Used only if an object of this type is returned as a trait impl by a method
334 extern "C" fn ChannelDetails_free_void(this_ptr: *mut c_void) {
335         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelDetails); }
336 }
337 #[allow(unused)]
338 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
339 impl ChannelDetails {
340         pub(crate) fn take_inner(mut self) -> *mut nativeChannelDetails {
341                 assert!(self.is_owned);
342                 let ret = self.inner;
343                 self.inner = std::ptr::null_mut();
344                 ret
345         }
346 }
347 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
348 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
349 /// Note that this means this value is *not* persistent - it can change once during the
350 /// lifetime of the channel.
351 #[no_mangle]
352 pub extern "C" fn ChannelDetails_get_channel_id(this_ptr: &ChannelDetails) -> *const [u8; 32] {
353         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id;
354         &(*inner_val)
355 }
356 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
357 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
358 /// Note that this means this value is *not* persistent - it can change once during the
359 /// lifetime of the channel.
360 #[no_mangle]
361 pub extern "C" fn ChannelDetails_set_channel_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::ThirtyTwoBytes) {
362         unsafe { &mut *this_ptr.inner }.channel_id = val.data;
363 }
364 /// The position of the funding transaction in the chain. None if the funding transaction has
365 /// not yet been confirmed and the channel fully opened.
366 #[no_mangle]
367 pub extern "C" fn ChannelDetails_get_short_channel_id(this_ptr: &ChannelDetails) -> crate::c_types::derived::COption_u64Z {
368         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.short_channel_id;
369         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()) } };
370         local_inner_val
371 }
372 /// The position of the funding transaction in the chain. None if the funding transaction has
373 /// not yet been confirmed and the channel fully opened.
374 #[no_mangle]
375 pub extern "C" fn ChannelDetails_set_short_channel_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::derived::COption_u64Z) {
376         let mut local_val = if val.is_some() { Some( { val.take() }) } else { None };
377         unsafe { &mut *this_ptr.inner }.short_channel_id = local_val;
378 }
379 /// The node_id of our counterparty
380 #[no_mangle]
381 pub extern "C" fn ChannelDetails_get_remote_network_id(this_ptr: &ChannelDetails) -> crate::c_types::PublicKey {
382         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.remote_network_id;
383         crate::c_types::PublicKey::from_rust(&(*inner_val))
384 }
385 /// The node_id of our counterparty
386 #[no_mangle]
387 pub extern "C" fn ChannelDetails_set_remote_network_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::PublicKey) {
388         unsafe { &mut *this_ptr.inner }.remote_network_id = val.into_rust();
389 }
390 /// The Features the channel counterparty provided upon last connection.
391 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
392 /// many routing-relevant features are present in the init context.
393 #[no_mangle]
394 pub extern "C" fn ChannelDetails_get_counterparty_features(this_ptr: &ChannelDetails) -> crate::ln::features::InitFeatures {
395         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_features;
396         crate::ln::features::InitFeatures { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
397 }
398 /// The Features the channel counterparty provided upon last connection.
399 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
400 /// many routing-relevant features are present in the init context.
401 #[no_mangle]
402 pub extern "C" fn ChannelDetails_set_counterparty_features(this_ptr: &mut ChannelDetails, mut val: crate::ln::features::InitFeatures) {
403         unsafe { &mut *this_ptr.inner }.counterparty_features = *unsafe { Box::from_raw(val.take_inner()) };
404 }
405 /// The value, in satoshis, of this channel as appears in the funding output
406 #[no_mangle]
407 pub extern "C" fn ChannelDetails_get_channel_value_satoshis(this_ptr: &ChannelDetails) -> u64 {
408         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_value_satoshis;
409         (*inner_val)
410 }
411 /// The value, in satoshis, of this channel as appears in the funding output
412 #[no_mangle]
413 pub extern "C" fn ChannelDetails_set_channel_value_satoshis(this_ptr: &mut ChannelDetails, mut val: u64) {
414         unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val;
415 }
416 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
417 #[no_mangle]
418 pub extern "C" fn ChannelDetails_get_user_id(this_ptr: &ChannelDetails) -> u64 {
419         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.user_id;
420         (*inner_val)
421 }
422 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
423 #[no_mangle]
424 pub extern "C" fn ChannelDetails_set_user_id(this_ptr: &mut ChannelDetails, mut val: u64) {
425         unsafe { &mut *this_ptr.inner }.user_id = val;
426 }
427 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
428 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
429 /// available for inclusion in new outbound HTLCs). This further does not include any pending
430 /// outgoing HTLCs which are awaiting some other resolution to be sent.
431 #[no_mangle]
432 pub extern "C" fn ChannelDetails_get_outbound_capacity_msat(this_ptr: &ChannelDetails) -> u64 {
433         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outbound_capacity_msat;
434         (*inner_val)
435 }
436 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
437 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
438 /// available for inclusion in new outbound HTLCs). This further does not include any pending
439 /// outgoing HTLCs which are awaiting some other resolution to be sent.
440 #[no_mangle]
441 pub extern "C" fn ChannelDetails_set_outbound_capacity_msat(this_ptr: &mut ChannelDetails, mut val: u64) {
442         unsafe { &mut *this_ptr.inner }.outbound_capacity_msat = val;
443 }
444 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
445 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
446 /// available for inclusion in new inbound HTLCs).
447 /// Note that there are some corner cases not fully handled here, so the actual available
448 /// inbound capacity may be slightly higher than this.
449 #[no_mangle]
450 pub extern "C" fn ChannelDetails_get_inbound_capacity_msat(this_ptr: &ChannelDetails) -> u64 {
451         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.inbound_capacity_msat;
452         (*inner_val)
453 }
454 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
455 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
456 /// available for inclusion in new inbound HTLCs).
457 /// Note that there are some corner cases not fully handled here, so the actual available
458 /// inbound capacity may be slightly higher than this.
459 #[no_mangle]
460 pub extern "C" fn ChannelDetails_set_inbound_capacity_msat(this_ptr: &mut ChannelDetails, mut val: u64) {
461         unsafe { &mut *this_ptr.inner }.inbound_capacity_msat = val;
462 }
463 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
464 /// the peer is connected, and (c) no monitor update failure is pending resolution.
465 #[no_mangle]
466 pub extern "C" fn ChannelDetails_get_is_live(this_ptr: &ChannelDetails) -> bool {
467         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_live;
468         (*inner_val)
469 }
470 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
471 /// the peer is connected, and (c) no monitor update failure is pending resolution.
472 #[no_mangle]
473 pub extern "C" fn ChannelDetails_set_is_live(this_ptr: &mut ChannelDetails, mut val: bool) {
474         unsafe { &mut *this_ptr.inner }.is_live = val;
475 }
476 impl Clone for ChannelDetails {
477         fn clone(&self) -> Self {
478                 Self {
479                         inner: if <*mut nativeChannelDetails>::is_null(self.inner) { std::ptr::null_mut() } else {
480                                 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
481                         is_owned: true,
482                 }
483         }
484 }
485 #[allow(unused)]
486 /// Used only if an object of this type is returned as a trait impl by a method
487 pub(crate) extern "C" fn ChannelDetails_clone_void(this_ptr: *const c_void) -> *mut c_void {
488         Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelDetails)).clone() })) as *mut c_void
489 }
490 #[no_mangle]
491 /// Creates a copy of the ChannelDetails
492 pub extern "C" fn ChannelDetails_clone(orig: &ChannelDetails) -> ChannelDetails {
493         orig.clone()
494 }
495 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
496 /// Err() type describing which state the payment is in, see the description of individual enum
497 /// states for more.
498 #[must_use]
499 #[derive(Clone)]
500 #[repr(C)]
501 pub enum PaymentSendFailure {
502         /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
503         /// send the payment at all. No channel state has been changed or messages sent to peers, and
504         /// once you've changed the parameter at error, you can freely retry the payment in full.
505         ParameterError(crate::util::errors::APIError),
506         /// A parameter in a single path which was passed to send_payment was invalid, preventing us
507         /// from attempting to send the payment at all. No channel state has been changed or messages
508         /// sent to peers, and once you've changed the parameter at error, you can freely retry the
509         /// payment in full.
510         ///
511         /// The results here are ordered the same as the paths in the route object which was passed to
512         /// send_payment.
513         PathParameterError(crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ),
514         /// All paths which were attempted failed to send, with no channel state change taking place.
515         /// You can freely retry the payment in full (though you probably want to do so over different
516         /// paths than the ones selected).
517         AllFailedRetrySafe(crate::c_types::derived::CVec_APIErrorZ),
518         /// Some paths which were attempted failed to send, though possibly not all. At least some
519         /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
520         /// in over-/re-payment.
521         ///
522         /// The results here are ordered the same as the paths in the route object which was passed to
523         /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
524         /// retried (though there is currently no API with which to do so).
525         ///
526         /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
527         /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
528         /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
529         /// with the latest update_id.
530         PartialFailure(crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ),
531 }
532 use lightning::ln::channelmanager::PaymentSendFailure as nativePaymentSendFailure;
533 impl PaymentSendFailure {
534         #[allow(unused)]
535         pub(crate) fn to_native(&self) -> nativePaymentSendFailure {
536                 match self {
537                         PaymentSendFailure::ParameterError (ref a, ) => {
538                                 let mut a_nonref = (*a).clone();
539                                 nativePaymentSendFailure::ParameterError (
540                                         a_nonref.into_native(),
541                                 )
542                         },
543                         PaymentSendFailure::PathParameterError (ref a, ) => {
544                                 let mut a_nonref = (*a).clone();
545                                 let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_nonref_0 }); };
546                                 nativePaymentSendFailure::PathParameterError (
547                                         local_a_nonref,
548                                 )
549                         },
550                         PaymentSendFailure::AllFailedRetrySafe (ref a, ) => {
551                                 let mut a_nonref = (*a).clone();
552                                 let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { item.into_native() }); };
553                                 nativePaymentSendFailure::AllFailedRetrySafe (
554                                         local_a_nonref,
555                                 )
556                         },
557                         PaymentSendFailure::PartialFailure (ref a, ) => {
558                                 let mut a_nonref = (*a).clone();
559                                 let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_nonref_0 }); };
560                                 nativePaymentSendFailure::PartialFailure (
561                                         local_a_nonref,
562                                 )
563                         },
564                 }
565         }
566         #[allow(unused)]
567         pub(crate) fn into_native(self) -> nativePaymentSendFailure {
568                 match self {
569                         PaymentSendFailure::ParameterError (mut a, ) => {
570                                 nativePaymentSendFailure::ParameterError (
571                                         a.into_native(),
572                                 )
573                         },
574                         PaymentSendFailure::PathParameterError (mut a, ) => {
575                                 let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { let mut local_a_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_0 }); };
576                                 nativePaymentSendFailure::PathParameterError (
577                                         local_a,
578                                 )
579                         },
580                         PaymentSendFailure::AllFailedRetrySafe (mut a, ) => {
581                                 let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { item.into_native() }); };
582                                 nativePaymentSendFailure::AllFailedRetrySafe (
583                                         local_a,
584                                 )
585                         },
586                         PaymentSendFailure::PartialFailure (mut a, ) => {
587                                 let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { let mut local_a_0 = match item.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut item.contents.err)) }).into_native() })}; local_a_0 }); };
588                                 nativePaymentSendFailure::PartialFailure (
589                                         local_a,
590                                 )
591                         },
592                 }
593         }
594         #[allow(unused)]
595         pub(crate) fn from_native(native: &nativePaymentSendFailure) -> Self {
596                 match native {
597                         nativePaymentSendFailure::ParameterError (ref a, ) => {
598                                 let mut a_nonref = (*a).clone();
599                                 PaymentSendFailure::ParameterError (
600                                         crate::util::errors::APIError::native_into(a_nonref),
601                                 )
602                         },
603                         nativePaymentSendFailure::PathParameterError (ref a, ) => {
604                                 let mut a_nonref = (*a).clone();
605                                 let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); };
606                                 PaymentSendFailure::PathParameterError (
607                                         local_a_nonref.into(),
608                                 )
609                         },
610                         nativePaymentSendFailure::AllFailedRetrySafe (ref a, ) => {
611                                 let mut a_nonref = (*a).clone();
612                                 let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { crate::util::errors::APIError::native_into(item) }); };
613                                 PaymentSendFailure::AllFailedRetrySafe (
614                                         local_a_nonref.into(),
615                                 )
616                         },
617                         nativePaymentSendFailure::PartialFailure (ref a, ) => {
618                                 let mut a_nonref = (*a).clone();
619                                 let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { let mut local_a_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); };
620                                 PaymentSendFailure::PartialFailure (
621                                         local_a_nonref.into(),
622                                 )
623                         },
624                 }
625         }
626         #[allow(unused)]
627         pub(crate) fn native_into(native: nativePaymentSendFailure) -> Self {
628                 match native {
629                         nativePaymentSendFailure::ParameterError (mut a, ) => {
630                                 PaymentSendFailure::ParameterError (
631                                         crate::util::errors::APIError::native_into(a),
632                                 )
633                         },
634                         nativePaymentSendFailure::PathParameterError (mut a, ) => {
635                                 let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); };
636                                 PaymentSendFailure::PathParameterError (
637                                         local_a.into(),
638                                 )
639                         },
640                         nativePaymentSendFailure::AllFailedRetrySafe (mut a, ) => {
641                                 let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { crate::util::errors::APIError::native_into(item) }); };
642                                 PaymentSendFailure::AllFailedRetrySafe (
643                                         local_a.into(),
644                                 )
645                         },
646                         nativePaymentSendFailure::PartialFailure (mut a, ) => {
647                                 let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { let mut local_a_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); };
648                                 PaymentSendFailure::PartialFailure (
649                                         local_a.into(),
650                                 )
651                         },
652                 }
653         }
654 }
655 /// Frees any resources used by the PaymentSendFailure
656 #[no_mangle]
657 pub extern "C" fn PaymentSendFailure_free(this_ptr: PaymentSendFailure) { }
658 /// Creates a copy of the PaymentSendFailure
659 #[no_mangle]
660 pub extern "C" fn PaymentSendFailure_clone(orig: &PaymentSendFailure) -> PaymentSendFailure {
661         orig.clone()
662 }
663 /// Constructs a new ChannelManager to hold several channels and route between them.
664 ///
665 /// This is the main \"logic hub\" for all channel-related actions, and implements
666 /// ChannelMessageHandler.
667 ///
668 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
669 ///
670 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
671 ///
672 /// Users need to notify the new ChannelManager when a new block is connected or
673 /// disconnected using its `block_connected` and `block_disconnected` methods, starting
674 /// from after `params.latest_hash`.
675 #[must_use]
676 #[no_mangle]
677 pub extern "C" fn ChannelManager_new(mut fee_est: crate::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::chain::Watch, mut tx_broadcaster: crate::chain::chaininterface::BroadcasterInterface, mut logger: crate::util::logger::Logger, mut keys_manager: crate::chain::keysinterface::KeysInterface, mut config: crate::util::config::UserConfig, mut params: crate::ln::channelmanager::ChainParameters) -> ChannelManager {
678         let mut ret = lightning::ln::channelmanager::ChannelManager::new(fee_est, chain_monitor, tx_broadcaster, logger, keys_manager, *unsafe { Box::from_raw(config.take_inner()) }, *unsafe { Box::from_raw(params.take_inner()) });
679         ChannelManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
680 }
681
682 /// Gets the current configuration applied to all new channels,  as
683 #[must_use]
684 #[no_mangle]
685 pub extern "C" fn ChannelManager_get_current_default_configuration(this_arg: &ChannelManager) -> crate::util::config::UserConfig {
686         let mut ret = unsafe { &*this_arg.inner }.get_current_default_configuration();
687         crate::util::config::UserConfig { inner: unsafe { ( (&(*ret) as *const _) as *mut _) }, is_owned: false }
688 }
689
690 /// Creates a new outbound channel to the given remote node and with the given value.
691 ///
692 /// user_id will be provided back as user_channel_id in FundingGenerationReady events to allow
693 /// tracking of which events correspond with which create_channel call. Note that the
694 /// user_channel_id defaults to 0 for inbound channels, so you may wish to avoid using 0 for
695 /// user_id here. user_id has no meaning inside of LDK, it is simply copied to events and
696 /// otherwise ignored.
697 ///
698 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
699 /// PeerManager::process_events afterwards.
700 ///
701 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
702 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
703 #[must_use]
704 #[no_mangle]
705 pub extern "C" fn ChannelManager_create_channel(this_arg: &ChannelManager, mut their_network_key: crate::c_types::PublicKey, mut channel_value_satoshis: u64, mut push_msat: u64, mut user_id: u64, mut override_config: crate::util::config::UserConfig) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
706         let mut local_override_config = if override_config.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(override_config.take_inner()) } }) };
707         let mut ret = unsafe { &*this_arg.inner }.create_channel(their_network_key.into_rust(), channel_value_satoshis, push_msat, user_id, local_override_config);
708         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() };
709         local_ret
710 }
711
712 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
713 /// more information.
714 #[must_use]
715 #[no_mangle]
716 pub extern "C" fn ChannelManager_list_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
717         let mut ret = unsafe { &*this_arg.inner }.list_channels();
718         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
719         local_ret.into()
720 }
721
722 /// Gets the list of usable channels, in random order. Useful as an argument to
723 /// get_route to ensure non-announced channels are used.
724 ///
725 /// These are guaranteed to have their is_live value set to true, see the documentation for
726 /// ChannelDetails::is_live for more info on exactly what the criteria are.
727 #[must_use]
728 #[no_mangle]
729 pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
730         let mut ret = unsafe { &*this_arg.inner }.list_usable_channels();
731         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::ln::channelmanager::ChannelDetails { inner: Box::into_raw(Box::new(item)), is_owned: true } }); };
732         local_ret.into()
733 }
734
735 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
736 /// will be accepted on the given channel, and after additional timeout/the closing of all
737 /// pending HTLCs, the channel will be closed on chain.
738 ///
739 /// May generate a SendShutdown message event on success, which should be relayed.
740 #[must_use]
741 #[no_mangle]
742 pub extern "C" fn ChannelManager_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
743         let mut ret = unsafe { &*this_arg.inner }.close_channel(unsafe { &*channel_id});
744         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() };
745         local_ret
746 }
747
748 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
749 /// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
750 #[must_use]
751 #[no_mangle]
752 pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
753         let mut ret = unsafe { &*this_arg.inner }.force_close_channel(unsafe { &*channel_id});
754         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() };
755         local_ret
756 }
757
758 /// Force close all channels, immediately broadcasting the latest local commitment transaction
759 /// for each to the chain and rejecting new HTLCs on each.
760 #[no_mangle]
761 pub extern "C" fn ChannelManager_force_close_all_channels(this_arg: &ChannelManager) {
762         unsafe { &*this_arg.inner }.force_close_all_channels()
763 }
764
765 /// Sends a payment along a given route.
766 ///
767 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
768 /// fields for more info.
769 ///
770 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
771 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
772 /// next hop knows the preimage to payment_hash they can claim an additional amount as
773 /// specified in the last hop in the route! Thus, you should probably do your own
774 /// payment_preimage tracking (which you should already be doing as they represent \"proof of
775 /// payment\") and prevent double-sends yourself.
776 ///
777 /// May generate SendHTLCs message(s) event on success, which should be relayed.
778 ///
779 /// Each path may have a different return value, and PaymentSendValue may return a Vec with
780 /// each entry matching the corresponding-index entry in the route paths, see
781 /// PaymentSendFailure for more info.
782 ///
783 /// In general, a path may raise:
784 ///  * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
785 ///    node public key) is specified.
786 ///  * APIError::ChannelUnavailable if the next-hop channel is not available for updates
787 ///    (including due to previous monitor update failure or new permanent monitor update
788 ///    failure).
789 ///  * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
790 ///    relevant updates.
791 ///
792 /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
793 /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
794 /// different route unless you intend to pay twice!
795 ///
796 /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
797 /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
798 /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
799 /// must not contain multiple paths as multi-path payments require a recipient-provided
800 /// payment_secret.
801 /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
802 /// bit set (either as required or as available). If multiple paths are present in the Route,
803 /// we assume the invoice had the basic_mpp feature set.
804 #[must_use]
805 #[no_mangle]
806 pub extern "C" fn ChannelManager_send_payment(this_arg: &ChannelManager, route: &crate::routing::router::Route, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ {
807         let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentSecret(payment_secret.data) }) };
808         let mut ret = unsafe { &*this_arg.inner }.send_payment(unsafe { &*route.inner }, ::lightning::ln::channelmanager::PaymentHash(payment_hash.data), &local_payment_secret);
809         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() };
810         local_ret
811 }
812
813 /// Call this upon creation of a funding transaction for the given channel.
814 ///
815 /// Returns an [`APIError::APIMisuseError`] if the funding_transaction spent non-SegWit outputs
816 /// or if no output was found which matches the parameters in [`Event::FundingGenerationReady`].
817 ///
818 /// Panics if a funding transaction has already been provided for this channel.
819 ///
820 /// May panic if the output found in the funding transaction is duplicative with some other
821 /// channel (note that this should be trivially prevented by using unique funding transaction
822 /// keys per-channel).
823 ///
824 /// Do NOT broadcast the funding transaction yourself. When we have safely received our
825 /// counterparty's signature the funding transaction will automatically be broadcast via the
826 /// [`BroadcasterInterface`] provided when this `ChannelManager` was constructed.
827 ///
828 /// Note that this includes RBF or similar transaction replacement strategies - lightning does
829 /// not currently support replacing a funding transaction on an existing channel. Instead,
830 /// create a new channel with a conflicting funding transaction.
831 #[must_use]
832 #[no_mangle]
833 pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &ChannelManager, temporary_channel_id: *const [u8; 32], mut funding_transaction: crate::c_types::Transaction) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
834         let mut ret = unsafe { &*this_arg.inner }.funding_transaction_generated(unsafe { &*temporary_channel_id}, funding_transaction.into_bitcoin());
835         let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { 0u8 /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::util::errors::APIError::native_into(e) }).into() };
836         local_ret
837 }
838
839 /// Generates a signed node_announcement from the given arguments and creates a
840 /// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
841 /// seen a channel_announcement from us (ie unless we have public channels open).
842 ///
843 /// RGB is a node \"color\" and alias is a printable human-readable string to describe this node
844 /// to humans. They carry no in-protocol meaning.
845 ///
846 /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
847 /// incoming connections. These will be broadcast to the network, publicly tying these
848 /// addresses together. If you wish to preserve user privacy, addresses should likely contain
849 /// only Tor Onion addresses.
850 ///
851 /// Panics if addresses is absurdly large (more than 500).
852 #[no_mangle]
853 pub extern "C" fn ChannelManager_broadcast_node_announcement(this_arg: &ChannelManager, mut rgb: crate::c_types::ThreeBytes, mut alias: crate::c_types::ThirtyTwoBytes, mut addresses: crate::c_types::derived::CVec_NetAddressZ) {
854         let mut local_addresses = Vec::new(); for mut item in addresses.into_rust().drain(..) { local_addresses.push( { item.into_native() }); };
855         unsafe { &*this_arg.inner }.broadcast_node_announcement(rgb.data, alias.data, local_addresses)
856 }
857
858 /// Processes HTLCs which are pending waiting on random forward delay.
859 ///
860 /// Should only really ever be called in response to a PendingHTLCsForwardable event.
861 /// Will likely generate further events.
862 #[no_mangle]
863 pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &ChannelManager) {
864         unsafe { &*this_arg.inner }.process_pending_htlc_forwards()
865 }
866
867 /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
868 /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
869 /// to inform the network about the uselessness of these channels.
870 ///
871 /// This method handles all the details, and must be called roughly once per minute.
872 ///
873 /// Note that in some rare cases this may generate a `chain::Watch::update_channel` call.
874 #[no_mangle]
875 pub extern "C" fn ChannelManager_timer_tick_occurred(this_arg: &ChannelManager) {
876         unsafe { &*this_arg.inner }.timer_tick_occurred()
877 }
878
879 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
880 /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
881 /// along the path (including in our own channel on which we received it).
882 /// Returns false if no payment was found to fail backwards, true if the process of failing the
883 /// HTLC backwards has been started.
884 #[must_use]
885 #[no_mangle]
886 pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &ChannelManager, payment_hash: *const [u8; 32], mut payment_secret: crate::c_types::ThirtyTwoBytes) -> bool {
887         let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentSecret(payment_secret.data) }) };
888         let mut ret = unsafe { &*this_arg.inner }.fail_htlc_backwards(&::lightning::ln::channelmanager::PaymentHash(unsafe { *payment_hash }), &local_payment_secret);
889         ret
890 }
891
892 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
893 /// generating message events for the net layer to claim the payment, if possible. Thus, you
894 /// should probably kick the net layer to go send messages if this returns true!
895 ///
896 /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
897 /// available within a few percent of the expected amount. This is critical for several
898 /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
899 /// payment_preimage without having provided the full value and b) it avoids certain
900 /// privacy-breaking recipient-probing attacks which may reveal payment activity to
901 /// motivated attackers.
902 ///
903 /// Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
904 /// set. Thus, for such payments we will claim any payments which do not under-pay.
905 ///
906 /// May panic if called except in response to a PaymentReceived event.
907 #[must_use]
908 #[no_mangle]
909 pub extern "C" fn ChannelManager_claim_funds(this_arg: &ChannelManager, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes, mut expected_amount: u64) -> bool {
910         let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentSecret(payment_secret.data) }) };
911         let mut ret = unsafe { &*this_arg.inner }.claim_funds(::lightning::ln::channelmanager::PaymentPreimage(payment_preimage.data), &local_payment_secret, expected_amount);
912         ret
913 }
914
915 /// Gets the node_id held by this ChannelManager
916 #[must_use]
917 #[no_mangle]
918 pub extern "C" fn ChannelManager_get_our_node_id(this_arg: &ChannelManager) -> crate::c_types::PublicKey {
919         let mut ret = unsafe { &*this_arg.inner }.get_our_node_id();
920         crate::c_types::PublicKey::from_rust(&ret)
921 }
922
923 /// Restores a single, given channel to normal operation after a
924 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
925 /// operation.
926 ///
927 /// All ChannelMonitor updates up to and including highest_applied_update_id must have been
928 /// fully committed in every copy of the given channels' ChannelMonitors.
929 ///
930 /// Note that there is no effect to calling with a highest_applied_update_id other than the
931 /// current latest ChannelMonitorUpdate and one call to this function after multiple
932 /// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
933 /// exists largely only to prevent races between this and concurrent update_monitor calls.
934 ///
935 /// Thus, the anticipated use is, at a high level:
936 ///  1) You register a chain::Watch with this ChannelManager,
937 ///  2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
938 ///     said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
939 ///     any time it cannot do so instantly,
940 ///  3) update(s) are applied to each remote copy of a ChannelMonitor,
941 ///  4) once all remote copies are updated, you call this function with the update_id that
942 ///     completed, and once it is the latest the Channel will be re-enabled.
943 #[no_mangle]
944 pub extern "C" fn ChannelManager_channel_monitor_updated(this_arg: &ChannelManager, funding_txo: &crate::chain::transaction::OutPoint, mut highest_applied_update_id: u64) {
945         unsafe { &*this_arg.inner }.channel_monitor_updated(unsafe { &*funding_txo.inner }, highest_applied_update_id)
946 }
947
948 impl From<nativeChannelManager> for crate::util::events::MessageSendEventsProvider {
949         fn from(obj: nativeChannelManager) -> Self {
950                 let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
951                 let mut ret = ChannelManager_as_MessageSendEventsProvider(&rust_obj);
952                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
953                 rust_obj.inner = std::ptr::null_mut();
954                 ret.free = Some(ChannelManager_free_void);
955                 ret
956         }
957 }
958 /// Constructs a new MessageSendEventsProvider which calls the relevant methods on this_arg.
959 /// This copies the `inner` pointer in this_arg and thus the returned MessageSendEventsProvider must be freed before this_arg is
960 #[no_mangle]
961 pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: &ChannelManager) -> crate::util::events::MessageSendEventsProvider {
962         crate::util::events::MessageSendEventsProvider {
963                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
964                 free: None,
965                 get_and_clear_pending_msg_events: ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events,
966         }
967 }
968
969 #[must_use]
970 extern "C" fn ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MessageSendEventZ {
971         let mut ret = <nativeChannelManager as lightning::util::events::MessageSendEventsProvider<>>::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
972         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::MessageSendEvent::native_into(item) }); };
973         local_ret.into()
974 }
975
976 impl From<nativeChannelManager> for crate::util::events::EventsProvider {
977         fn from(obj: nativeChannelManager) -> Self {
978                 let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
979                 let mut ret = ChannelManager_as_EventsProvider(&rust_obj);
980                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
981                 rust_obj.inner = std::ptr::null_mut();
982                 ret.free = Some(ChannelManager_free_void);
983                 ret
984         }
985 }
986 /// Constructs a new EventsProvider which calls the relevant methods on this_arg.
987 /// This copies the `inner` pointer in this_arg and thus the returned EventsProvider must be freed before this_arg is
988 #[no_mangle]
989 pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: &ChannelManager) -> crate::util::events::EventsProvider {
990         crate::util::events::EventsProvider {
991                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
992                 free: None,
993                 get_and_clear_pending_events: ChannelManager_EventsProvider_get_and_clear_pending_events,
994         }
995 }
996
997 #[must_use]
998 extern "C" fn ChannelManager_EventsProvider_get_and_clear_pending_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_EventZ {
999         let mut ret = <nativeChannelManager as lightning::util::events::EventsProvider<>>::get_and_clear_pending_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
1000         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
1001         local_ret.into()
1002 }
1003
1004 impl From<nativeChannelManager> for crate::chain::Listen {
1005         fn from(obj: nativeChannelManager) -> Self {
1006                 let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
1007                 let mut ret = ChannelManager_as_Listen(&rust_obj);
1008                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
1009                 rust_obj.inner = std::ptr::null_mut();
1010                 ret.free = Some(ChannelManager_free_void);
1011                 ret
1012         }
1013 }
1014 /// Constructs a new Listen which calls the relevant methods on this_arg.
1015 /// This copies the `inner` pointer in this_arg and thus the returned Listen must be freed before this_arg is
1016 #[no_mangle]
1017 pub extern "C" fn ChannelManager_as_Listen(this_arg: &ChannelManager) -> crate::chain::Listen {
1018         crate::chain::Listen {
1019                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
1020                 free: None,
1021                 block_connected: ChannelManager_Listen_block_connected,
1022                 block_disconnected: ChannelManager_Listen_block_disconnected,
1023         }
1024 }
1025
1026 extern "C" fn ChannelManager_Listen_block_connected(this_arg: *const c_void, mut block: crate::c_types::u8slice, mut height: u32) {
1027         <nativeChannelManager as lightning::chain::Listen<>>::block_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height)
1028 }
1029 extern "C" fn ChannelManager_Listen_block_disconnected(this_arg: *const c_void, header: *const [u8; 80], mut height: u32) {
1030         <nativeChannelManager as lightning::chain::Listen<>>::block_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
1031 }
1032
1033 /// Updates channel state to take note of transactions which were confirmed in the given block
1034 /// at the given height.
1035 ///
1036 /// Note that you must still call (or have called) [`update_best_block`] with the block
1037 /// information which is included here.
1038 ///
1039 /// This method may be called before or after [`update_best_block`] for a given block's
1040 /// transaction data and may be called multiple times with additional transaction data for a
1041 /// given block.
1042 ///
1043 /// This method may be called for a previous block after an [`update_best_block`] call has
1044 /// been made for a later block, however it must *not* be called with transaction data from a
1045 /// block which is no longer in the best chain (ie where [`update_best_block`] has already
1046 /// been informed about a blockchain reorganization which no longer includes the block which
1047 /// corresponds to `header`).
1048 ///
1049 /// [`update_best_block`]: `Self::update_best_block`
1050 #[no_mangle]
1051 pub extern "C" fn ChannelManager_transactions_confirmed(this_arg: &ChannelManager, header: *const [u8; 80], mut height: u32, mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ) {
1052         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 }); };
1053         unsafe { &*this_arg.inner }.transactions_confirmed(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height, &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..])
1054 }
1055
1056 /// Updates channel state with the current best blockchain tip. You should attempt to call this
1057 /// quickly after a new block becomes available, however if multiple new blocks become
1058 /// available at the same time, only a single `update_best_block()` call needs to be made.
1059 ///
1060 /// This method should also be called immediately after any block disconnections, once at the
1061 /// reorganization fork point, and once with the new chain tip. Calling this method at the
1062 /// blockchain reorganization fork point ensures we learn when a funding transaction which was
1063 /// previously confirmed is reorganized out of the blockchain, ensuring we do not continue to
1064 /// accept payments which cannot be enforced on-chain.
1065 ///
1066 /// In both the block-connection and block-disconnection case, this method may be called either
1067 /// once per block connected or disconnected, or simply at the fork point and new tip(s),
1068 /// skipping any intermediary blocks.
1069 #[no_mangle]
1070 pub extern "C" fn ChannelManager_update_best_block(this_arg: &ChannelManager, header: *const [u8; 80], mut height: u32) {
1071         unsafe { &*this_arg.inner }.update_best_block(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), height)
1072 }
1073
1074 /// Gets the set of txids which should be monitored for their confirmation state.
1075 ///
1076 /// If you're providing information about reorganizations via [`transaction_unconfirmed`], this
1077 /// is the set of transactions which you may need to call [`transaction_unconfirmed`] for.
1078 ///
1079 /// This may be useful to poll to determine the set of transactions which must be registered
1080 /// with an Electrum server or for which an Electrum server needs to be polled to determine
1081 /// transaction confirmation state.
1082 ///
1083 /// This may update after any [`transactions_confirmed`] or [`block_connected`] call.
1084 ///
1085 /// Note that this is NOT the set of transactions which must be included in calls to
1086 /// [`transactions_confirmed`] if they are confirmed, but a small subset of it.
1087 ///
1088 /// [`transactions_confirmed`]: Self::transactions_confirmed
1089 /// [`transaction_unconfirmed`]: Self::transaction_unconfirmed
1090 /// [`block_connected`]: chain::Listen::block_connected
1091 #[must_use]
1092 #[no_mangle]
1093 pub extern "C" fn ChannelManager_get_relevant_txids(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_TxidZ {
1094         let mut ret = unsafe { &*this_arg.inner }.get_relevant_txids();
1095         let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::ThirtyTwoBytes { data: item.into_inner() } }); };
1096         local_ret.into()
1097 }
1098
1099 /// Marks a transaction as having been reorganized out of the blockchain.
1100 ///
1101 /// If a transaction is included in [`get_relevant_txids`], and is no longer in the main branch
1102 /// of the blockchain, this function should be called to indicate that the transaction should
1103 /// be considered reorganized out.
1104 ///
1105 /// Once this is called, the given transaction will no longer appear on [`get_relevant_txids`],
1106 /// though this may be called repeatedly for a given transaction without issue.
1107 ///
1108 /// Note that if the transaction is confirmed on the main chain in a different block (indicated
1109 /// via a call to [`transactions_confirmed`]), it may re-appear in [`get_relevant_txids`], thus
1110 /// be very wary of race-conditions wherein the final state of a transaction indicated via
1111 /// these APIs is not the same as its state on the blockchain.
1112 ///
1113 /// [`transactions_confirmed`]: Self::transactions_confirmed
1114 /// [`get_relevant_txids`]: Self::get_relevant_txids
1115 #[no_mangle]
1116 pub extern "C" fn ChannelManager_transaction_unconfirmed(this_arg: &ChannelManager, txid: *const [u8; 32]) {
1117         unsafe { &*this_arg.inner }.transaction_unconfirmed(&::bitcoin::hash_types::Txid::from_slice(&unsafe { &*txid }[..]).unwrap())
1118 }
1119
1120 /// Blocks until ChannelManager needs to be persisted or a timeout is reached. It returns a bool
1121 /// indicating whether persistence is necessary. Only one listener on
1122 /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
1123 /// up.
1124 /// Note that the feature `allow_wallclock_use` must be enabled to use this function.
1125 #[must_use]
1126 #[no_mangle]
1127 pub extern "C" fn ChannelManager_await_persistable_update_timeout(this_arg: &ChannelManager, mut max_wait: u64) -> bool {
1128         let mut ret = unsafe { &*this_arg.inner }.await_persistable_update_timeout(std::time::Duration::from_secs(max_wait));
1129         ret
1130 }
1131
1132 /// Blocks until ChannelManager needs to be persisted. Only one listener on
1133 /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
1134 /// up.
1135 #[no_mangle]
1136 pub extern "C" fn ChannelManager_await_persistable_update(this_arg: &ChannelManager) {
1137         unsafe { &*this_arg.inner }.await_persistable_update()
1138 }
1139
1140 impl From<nativeChannelManager> for crate::ln::msgs::ChannelMessageHandler {
1141         fn from(obj: nativeChannelManager) -> Self {
1142                 let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
1143                 let mut ret = ChannelManager_as_ChannelMessageHandler(&rust_obj);
1144                 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
1145                 rust_obj.inner = std::ptr::null_mut();
1146                 ret.free = Some(ChannelManager_free_void);
1147                 ret
1148         }
1149 }
1150 /// Constructs a new ChannelMessageHandler which calls the relevant methods on this_arg.
1151 /// This copies the `inner` pointer in this_arg and thus the returned ChannelMessageHandler must be freed before this_arg is
1152 #[no_mangle]
1153 pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelManager) -> crate::ln::msgs::ChannelMessageHandler {
1154         crate::ln::msgs::ChannelMessageHandler {
1155                 this_arg: unsafe { (*this_arg).inner as *mut c_void },
1156                 free: None,
1157                 handle_open_channel: ChannelManager_ChannelMessageHandler_handle_open_channel,
1158                 handle_accept_channel: ChannelManager_ChannelMessageHandler_handle_accept_channel,
1159                 handle_funding_created: ChannelManager_ChannelMessageHandler_handle_funding_created,
1160                 handle_funding_signed: ChannelManager_ChannelMessageHandler_handle_funding_signed,
1161                 handle_funding_locked: ChannelManager_ChannelMessageHandler_handle_funding_locked,
1162                 handle_shutdown: ChannelManager_ChannelMessageHandler_handle_shutdown,
1163                 handle_closing_signed: ChannelManager_ChannelMessageHandler_handle_closing_signed,
1164                 handle_update_add_htlc: ChannelManager_ChannelMessageHandler_handle_update_add_htlc,
1165                 handle_update_fulfill_htlc: ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc,
1166                 handle_update_fail_htlc: ChannelManager_ChannelMessageHandler_handle_update_fail_htlc,
1167                 handle_update_fail_malformed_htlc: ChannelManager_ChannelMessageHandler_handle_update_fail_malformed_htlc,
1168                 handle_commitment_signed: ChannelManager_ChannelMessageHandler_handle_commitment_signed,
1169                 handle_revoke_and_ack: ChannelManager_ChannelMessageHandler_handle_revoke_and_ack,
1170                 handle_update_fee: ChannelManager_ChannelMessageHandler_handle_update_fee,
1171                 handle_announcement_signatures: ChannelManager_ChannelMessageHandler_handle_announcement_signatures,
1172                 peer_disconnected: ChannelManager_ChannelMessageHandler_peer_disconnected,
1173                 peer_connected: ChannelManager_ChannelMessageHandler_peer_connected,
1174                 handle_channel_reestablish: ChannelManager_ChannelMessageHandler_handle_channel_reestablish,
1175                 handle_channel_update: ChannelManager_ChannelMessageHandler_handle_channel_update,
1176                 handle_error: ChannelManager_ChannelMessageHandler_handle_error,
1177                 MessageSendEventsProvider: crate::util::events::MessageSendEventsProvider {
1178                         this_arg: unsafe { (*this_arg).inner as *mut c_void },
1179                         free: None,
1180                         get_and_clear_pending_msg_events: ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events,
1181                 },
1182         }
1183 }
1184
1185 extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut their_features: crate::ln::features::InitFeatures, msg: &crate::ln::msgs::OpenChannel) {
1186         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, unsafe { &*msg.inner })
1187 }
1188 extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut their_features: crate::ln::features::InitFeatures, msg: &crate::ln::msgs::AcceptChannel) {
1189         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, unsafe { &*msg.inner })
1190 }
1191 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_created(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::FundingCreated) {
1192         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1193 }
1194 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::FundingSigned) {
1195         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1196 }
1197 extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_locked(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::FundingLocked) {
1198         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_locked(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1199 }
1200 extern "C" fn ChannelManager_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, their_features: &crate::ln::features::InitFeatures, msg: &crate::ln::msgs::Shutdown) {
1201         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*their_features.inner }, unsafe { &*msg.inner })
1202 }
1203 extern "C" fn ChannelManager_ChannelMessageHandler_handle_closing_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::ClosingSigned) {
1204         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1205 }
1206 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_add_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateAddHTLC) {
1207         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_add_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1208 }
1209 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateFulfillHTLC) {
1210         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fulfill_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1211 }
1212 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateFailHTLC) {
1213         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fail_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1214 }
1215 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fail_malformed_htlc(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateFailMalformedHTLC) {
1216         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fail_malformed_htlc(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1217 }
1218 extern "C" fn ChannelManager_ChannelMessageHandler_handle_commitment_signed(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::CommitmentSigned) {
1219         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1220 }
1221 extern "C" fn ChannelManager_ChannelMessageHandler_handle_revoke_and_ack(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::RevokeAndACK) {
1222         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_revoke_and_ack(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1223 }
1224 extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fee(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::UpdateFee) {
1225         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1226 }
1227 extern "C" fn ChannelManager_ChannelMessageHandler_handle_announcement_signatures(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::AnnouncementSignatures) {
1228         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1229 }
1230 extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_update(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::ChannelUpdate) {
1231         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_channel_update(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1232 }
1233 extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_reestablish(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::ChannelReestablish) {
1234         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1235 }
1236 extern "C" fn ChannelManager_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) {
1237         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), no_connection_possible)
1238 }
1239 extern "C" fn ChannelManager_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, init_msg: &crate::ln::msgs::Init) {
1240         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*init_msg.inner })
1241 }
1242 extern "C" fn ChannelManager_ChannelMessageHandler_handle_error(this_arg: *const c_void, mut counterparty_node_id: crate::c_types::PublicKey, msg: &crate::ln::msgs::ErrorMessage) {
1243         <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_error(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
1244 }
1245
1246 #[no_mangle]
1247 /// Serialize the ChannelManager object into a byte array which can be read by ChannelManager_read
1248 pub extern "C" fn ChannelManager_write(obj: &ChannelManager) -> crate::c_types::derived::CVec_u8Z {
1249         crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
1250 }
1251 #[no_mangle]
1252 pub(crate) extern "C" fn ChannelManager_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1253         crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelManager) })
1254 }
1255
1256 use lightning::ln::channelmanager::ChannelManagerReadArgs as nativeChannelManagerReadArgsImport;
1257 type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::chain::keysinterface::Sign, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>;
1258
1259 /// Arguments for the creation of a ChannelManager that are not deserialized.
1260 ///
1261 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
1262 /// is:
1263 /// 1) Deserialize all stored ChannelMonitors.
1264 /// 2) Deserialize the ChannelManager by filling in this struct and calling:
1265 ///    <(BlockHash, ChannelManager)>::read(reader, args)
1266 ///    This may result in closing some Channels if the ChannelMonitor is newer than the stored
1267 ///    ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
1268 /// 3) If you are not fetching full blocks, register all relevant ChannelMonitor outpoints the same
1269 ///    way you would handle a `chain::Filter` call using ChannelMonitor::get_outputs_to_watch() and
1270 ///    ChannelMonitor::get_funding_txo().
1271 /// 4) Reconnect blocks on your ChannelMonitors.
1272 /// 5) Disconnect/connect blocks on the ChannelManager.
1273 /// 6) Move the ChannelMonitors into your local chain::Watch.
1274 ///
1275 /// Note that the ordering of #4-6 is not of importance, however all three must occur before you
1276 /// call any other methods on the newly-deserialized ChannelManager.
1277 ///
1278 /// Note that because some channels may be closed during deserialization, it is critical that you
1279 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
1280 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
1281 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
1282 /// not force-close the same channels but consider them live), you may end up revoking a state for
1283 /// which you've already broadcasted the transaction.
1284 #[must_use]
1285 #[repr(C)]
1286 pub struct ChannelManagerReadArgs {
1287         /// A pointer to the opaque Rust object.
1288
1289         /// Nearly everywhere, inner must be non-null, however in places where
1290         /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1291         pub inner: *mut nativeChannelManagerReadArgs,
1292         /// Indicates that this is the only struct which contains the same pointer.
1293
1294         /// Rust functions which take ownership of an object provided via an argument require
1295         /// this to be true and invalidate the object pointed to by inner.
1296         pub is_owned: bool,
1297 }
1298
1299 impl Drop for ChannelManagerReadArgs {
1300         fn drop(&mut self) {
1301                 if self.is_owned && !<*mut nativeChannelManagerReadArgs>::is_null(self.inner) {
1302                         let _ = unsafe { Box::from_raw(self.inner) };
1303                 }
1304         }
1305 }
1306 /// Frees any resources used by the ChannelManagerReadArgs, if is_owned is set and inner is non-NULL.
1307 #[no_mangle]
1308 pub extern "C" fn ChannelManagerReadArgs_free(this_obj: ChannelManagerReadArgs) { }
1309 #[allow(unused)]
1310 /// Used only if an object of this type is returned as a trait impl by a method
1311 extern "C" fn ChannelManagerReadArgs_free_void(this_ptr: *mut c_void) {
1312         unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelManagerReadArgs); }
1313 }
1314 #[allow(unused)]
1315 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1316 impl ChannelManagerReadArgs {
1317         pub(crate) fn take_inner(mut self) -> *mut nativeChannelManagerReadArgs {
1318                 assert!(self.is_owned);
1319                 let ret = self.inner;
1320                 self.inner = std::ptr::null_mut();
1321                 ret
1322         }
1323 }
1324 /// The keys provider which will give us relevant keys. Some keys will be loaded during
1325 /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
1326 /// signing data.
1327 #[no_mangle]
1328 pub extern "C" fn ChannelManagerReadArgs_get_keys_manager(this_ptr: &ChannelManagerReadArgs) -> *const crate::chain::keysinterface::KeysInterface {
1329         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.keys_manager;
1330         &(*inner_val)
1331 }
1332 /// The keys provider which will give us relevant keys. Some keys will be loaded during
1333 /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
1334 /// signing data.
1335 #[no_mangle]
1336 pub extern "C" fn ChannelManagerReadArgs_set_keys_manager(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::chain::keysinterface::KeysInterface) {
1337         unsafe { &mut *this_ptr.inner }.keys_manager = val;
1338 }
1339 /// The fee_estimator for use in the ChannelManager in the future.
1340 ///
1341 /// No calls to the FeeEstimator will be made during deserialization.
1342 #[no_mangle]
1343 pub extern "C" fn ChannelManagerReadArgs_get_fee_estimator(this_ptr: &ChannelManagerReadArgs) -> *const crate::chain::chaininterface::FeeEstimator {
1344         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fee_estimator;
1345         &(*inner_val)
1346 }
1347 /// The fee_estimator for use in the ChannelManager in the future.
1348 ///
1349 /// No calls to the FeeEstimator will be made during deserialization.
1350 #[no_mangle]
1351 pub extern "C" fn ChannelManagerReadArgs_set_fee_estimator(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::chain::chaininterface::FeeEstimator) {
1352         unsafe { &mut *this_ptr.inner }.fee_estimator = val;
1353 }
1354 /// The chain::Watch for use in the ChannelManager in the future.
1355 ///
1356 /// No calls to the chain::Watch will be made during deserialization. It is assumed that
1357 /// you have deserialized ChannelMonitors separately and will add them to your
1358 /// chain::Watch after deserializing this ChannelManager.
1359 #[no_mangle]
1360 pub extern "C" fn ChannelManagerReadArgs_get_chain_monitor(this_ptr: &ChannelManagerReadArgs) -> *const crate::chain::Watch {
1361         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_monitor;
1362         &(*inner_val)
1363 }
1364 /// The chain::Watch for use in the ChannelManager in the future.
1365 ///
1366 /// No calls to the chain::Watch will be made during deserialization. It is assumed that
1367 /// you have deserialized ChannelMonitors separately and will add them to your
1368 /// chain::Watch after deserializing this ChannelManager.
1369 #[no_mangle]
1370 pub extern "C" fn ChannelManagerReadArgs_set_chain_monitor(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::chain::Watch) {
1371         unsafe { &mut *this_ptr.inner }.chain_monitor = val;
1372 }
1373 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
1374 /// used to broadcast the latest local commitment transactions of channels which must be
1375 /// force-closed during deserialization.
1376 #[no_mangle]
1377 pub extern "C" fn ChannelManagerReadArgs_get_tx_broadcaster(this_ptr: &ChannelManagerReadArgs) -> *const crate::chain::chaininterface::BroadcasterInterface {
1378         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.tx_broadcaster;
1379         &(*inner_val)
1380 }
1381 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
1382 /// used to broadcast the latest local commitment transactions of channels which must be
1383 /// force-closed during deserialization.
1384 #[no_mangle]
1385 pub extern "C" fn ChannelManagerReadArgs_set_tx_broadcaster(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::chain::chaininterface::BroadcasterInterface) {
1386         unsafe { &mut *this_ptr.inner }.tx_broadcaster = val;
1387 }
1388 /// The Logger for use in the ChannelManager and which may be used to log information during
1389 /// deserialization.
1390 #[no_mangle]
1391 pub extern "C" fn ChannelManagerReadArgs_get_logger(this_ptr: &ChannelManagerReadArgs) -> *const crate::util::logger::Logger {
1392         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.logger;
1393         &(*inner_val)
1394 }
1395 /// The Logger for use in the ChannelManager and which may be used to log information during
1396 /// deserialization.
1397 #[no_mangle]
1398 pub extern "C" fn ChannelManagerReadArgs_set_logger(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::util::logger::Logger) {
1399         unsafe { &mut *this_ptr.inner }.logger = val;
1400 }
1401 /// Default settings used for new channels. Any existing channels will continue to use the
1402 /// runtime settings which were stored when the ChannelManager was serialized.
1403 #[no_mangle]
1404 pub extern "C" fn ChannelManagerReadArgs_get_default_config(this_ptr: &ChannelManagerReadArgs) -> crate::util::config::UserConfig {
1405         let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.default_config;
1406         crate::util::config::UserConfig { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
1407 }
1408 /// Default settings used for new channels. Any existing channels will continue to use the
1409 /// runtime settings which were stored when the ChannelManager was serialized.
1410 #[no_mangle]
1411 pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::util::config::UserConfig) {
1412         unsafe { &mut *this_ptr.inner }.default_config = *unsafe { Box::from_raw(val.take_inner()) };
1413 }
1414 /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
1415 /// HashMap for you. This is primarily useful for C bindings where it is not practical to
1416 /// populate a HashMap directly from C.
1417 #[must_use]
1418 #[no_mangle]
1419 pub extern "C" fn ChannelManagerReadArgs_new(mut keys_manager: crate::chain::keysinterface::KeysInterface, mut fee_estimator: crate::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::chain::Watch, mut tx_broadcaster: crate::chain::chaininterface::BroadcasterInterface, mut logger: crate::util::logger::Logger, mut default_config: crate::util::config::UserConfig, mut channel_monitors: crate::c_types::derived::CVec_ChannelMonitorZ) -> ChannelManagerReadArgs {
1420         let mut local_channel_monitors = Vec::new(); for mut item in channel_monitors.into_rust().drain(..) { local_channel_monitors.push( { unsafe { &mut *item.inner } }); };
1421         let mut ret = lightning::ln::channelmanager::ChannelManagerReadArgs::new(keys_manager, fee_estimator, chain_monitor, tx_broadcaster, logger, *unsafe { Box::from_raw(default_config.take_inner()) }, local_channel_monitors);
1422         ChannelManagerReadArgs { inner: Box::into_raw(Box::new(ret)), is_owned: true }
1423 }
1424
1425 #[no_mangle]
1426 /// Read a C2Tuple_BlockHashChannelManagerZ from a byte array, created by C2Tuple_BlockHashChannelManagerZ_write
1427 pub extern "C" fn C2Tuple_BlockHashChannelManagerZ_read(ser: crate::c_types::u8slice, arg: crate::ln::channelmanager::ChannelManagerReadArgs) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
1428         let arg_conv = *unsafe { Box::from_raw(arg.take_inner()) };
1429         let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager<crate::chain::keysinterface::Sign, crate::chain::Watch, crate::chain::chaininterface::BroadcasterInterface, crate::chain::keysinterface::KeysInterface, crate::chain::chaininterface::FeeEstimator, crate::util::logger::Logger>), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
1430         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.into_inner() }, crate::ln::channelmanager::ChannelManager { inner: Box::into_raw(Box::new(orig_res_0_1)), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::ln::msgs::DecodeError { inner: Box::into_raw(Box::new(e)), is_owned: true } }).into() };
1431         local_res
1432 }