1 //! The top-level channel management and payment tracking stuff lives here.
3 //! The ChannelManager is the main chunk of logic implementing the lightning protocol and is
4 //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those
5 //! upon reconnect to the relevant peer(s).
7 //! It does not manage routing logic (see routing::router::get_route for that) nor does it manage constructing
8 //! on-chain transactions (it only monitors the chain to watch for any force-closes that might
9 //! imply it needs to fail HTLCs/payments/channels it manages).
13 use bitcoin::hashes::Hash;
14 use crate::c_types::*;
17 use lightning::ln::channelmanager::ChannelManager as nativeChannelManagerImport;
18 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>;
20 /// Manager which keeps track of a number of channels and sends messages to the appropriate
21 /// channel, also tracking HTLC preimages and forwarding onion packets appropriately.
23 /// Implements ChannelMessageHandler, handling the multi-channel parts and passing things through
24 /// to individual Channels.
26 /// Implements Writeable to write out all channel state to disk. Implies peer_disconnected() for
27 /// all peers during write/read (though does not modify this instance, only the instance being
28 /// serialized). This will result in any channels which have not yet exchanged funding_created (ie
29 /// called funding_transaction_generated for outbound channels).
31 /// Note that you can be a bit lazier about writing out ChannelManager than you can be with
32 /// ChannelMonitors. With ChannelMonitors you MUST write each monitor update out to disk before
33 /// returning from chain::Watch::watch_/update_channel, with ChannelManagers, writing updates
34 /// happens out-of-band (and will prevent any other ChannelManager operations from occurring during
35 /// the serialization process). If the deserialized version is out-of-date compared to the
36 /// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
37 /// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
39 /// Note that the deserializer is only implemented for (BlockHash, ChannelManager), which
40 /// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
41 /// the \"reorg path\" (ie call block_disconnected() until you get to a common block and then call
42 /// block_connected() to step towards your best block) upon deserialization before using the
45 /// Note that ChannelManager is responsible for tracking liveness of its channels and generating
46 /// ChannelUpdate messages informing peers that the channel is temporarily disabled. To avoid
47 /// spam due to quick disconnection/reconnection, updates are not sent until the channel has been
48 /// offline for a full minute. In order to track this, you must call
49 /// timer_chan_freshness_every_min roughly once per minute, though it doesn't have to be perfect.
51 /// Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager
52 /// a SimpleRefChannelManager, for conciseness. See their documentation for more details, but
53 /// essentially you should default to using a SimpleRefChannelManager, and use a
54 /// SimpleArcChannelManager when you require a ChannelManager with a static lifetime, such as when
55 /// you're using lightning-net-tokio.
58 pub struct ChannelManager {
59 /// Nearly everywhere, inner must be non-null, however in places where
60 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
61 pub inner: *mut nativeChannelManager,
65 impl Drop for ChannelManager {
67 if self.is_owned && !<*mut nativeChannelManager>::is_null(self.inner) {
68 let _ = unsafe { Box::from_raw(self.inner) };
73 pub extern "C" fn ChannelManager_free(this_ptr: ChannelManager) { }
75 /// Used only if an object of this type is returned as a trait impl by a method
76 extern "C" fn ChannelManager_free_void(this_ptr: *mut c_void) {
77 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelManager); }
80 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
82 pub(crate) fn take_inner(mut self) -> *mut nativeChannelManager {
83 assert!(self.is_owned);
85 self.inner = std::ptr::null_mut();
90 use lightning::ln::channelmanager::ChainParameters as nativeChainParametersImport;
91 type nativeChainParameters = nativeChainParametersImport;
93 /// Chain-related parameters used to construct a new `ChannelManager`.
95 /// Typically, the block-specific parameters are derived from the best block hash for the network,
96 /// as a newly constructed `ChannelManager` will not have created any channels yet. These parameters
97 /// are not needed when deserializing a previously constructed `ChannelManager`.
100 pub struct ChainParameters {
101 /// Nearly everywhere, inner must be non-null, however in places where
102 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
103 pub inner: *mut nativeChainParameters,
107 impl Drop for ChainParameters {
109 if self.is_owned && !<*mut nativeChainParameters>::is_null(self.inner) {
110 let _ = unsafe { Box::from_raw(self.inner) };
115 pub extern "C" fn ChainParameters_free(this_ptr: ChainParameters) { }
117 /// Used only if an object of this type is returned as a trait impl by a method
118 extern "C" fn ChainParameters_free_void(this_ptr: *mut c_void) {
119 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChainParameters); }
122 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
123 impl ChainParameters {
124 pub(crate) fn take_inner(mut self) -> *mut nativeChainParameters {
125 assert!(self.is_owned);
126 let ret = self.inner;
127 self.inner = std::ptr::null_mut();
131 /// The network for determining the `chain_hash` in Lightning messages.
133 pub extern "C" fn ChainParameters_get_network(this_ptr: &ChainParameters) -> crate::bitcoin::network::Network {
134 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.network;
135 crate::bitcoin::network::Network::from_bitcoin((*inner_val))
137 /// The network for determining the `chain_hash` in Lightning messages.
139 pub extern "C" fn ChainParameters_set_network(this_ptr: &mut ChainParameters, mut val: crate::bitcoin::network::Network) {
140 unsafe { &mut *this_ptr.inner }.network = val.into_bitcoin();
142 /// The hash of the latest block successfully connected.
144 pub extern "C" fn ChainParameters_get_latest_hash(this_ptr: &ChainParameters) -> *const [u8; 32] {
145 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.latest_hash;
146 (*inner_val).as_inner()
148 /// The hash of the latest block successfully connected.
150 pub extern "C" fn ChainParameters_set_latest_hash(this_ptr: &mut ChainParameters, mut val: crate::c_types::ThirtyTwoBytes) {
151 unsafe { &mut *this_ptr.inner }.latest_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap();
153 /// The height of the latest block successfully connected.
155 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
157 pub extern "C" fn ChainParameters_get_latest_height(this_ptr: &ChainParameters) -> usize {
158 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.latest_height;
161 /// The height of the latest block successfully connected.
163 /// Used to track on-chain channel funding outputs and send payments with reliable timelocks.
165 pub extern "C" fn ChainParameters_set_latest_height(this_ptr: &mut ChainParameters, mut val: usize) {
166 unsafe { &mut *this_ptr.inner }.latest_height = val;
170 pub extern "C" fn ChainParameters_new(mut network_arg: crate::bitcoin::network::Network, mut latest_hash_arg: crate::c_types::ThirtyTwoBytes, mut latest_height_arg: usize) -> ChainParameters {
171 ChainParameters { inner: Box::into_raw(Box::new(nativeChainParameters {
172 network: network_arg.into_bitcoin(),
173 latest_hash: ::bitcoin::hash_types::BlockHash::from_slice(&latest_hash_arg.data[..]).unwrap(),
174 latest_height: latest_height_arg,
175 })), is_owned: true }
178 use lightning::ln::channelmanager::ChannelDetails as nativeChannelDetailsImport;
179 type nativeChannelDetails = nativeChannelDetailsImport;
181 /// Details of a channel, as returned by ChannelManager::list_channels and ChannelManager::list_usable_channels
184 pub struct ChannelDetails {
185 /// Nearly everywhere, inner must be non-null, however in places where
186 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
187 pub inner: *mut nativeChannelDetails,
191 impl Drop for ChannelDetails {
193 if self.is_owned && !<*mut nativeChannelDetails>::is_null(self.inner) {
194 let _ = unsafe { Box::from_raw(self.inner) };
199 pub extern "C" fn ChannelDetails_free(this_ptr: ChannelDetails) { }
201 /// Used only if an object of this type is returned as a trait impl by a method
202 extern "C" fn ChannelDetails_free_void(this_ptr: *mut c_void) {
203 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelDetails); }
206 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
207 impl ChannelDetails {
208 pub(crate) fn take_inner(mut self) -> *mut nativeChannelDetails {
209 assert!(self.is_owned);
210 let ret = self.inner;
211 self.inner = std::ptr::null_mut();
215 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
216 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
217 /// Note that this means this value is *not* persistent - it can change once during the
218 /// lifetime of the channel.
220 pub extern "C" fn ChannelDetails_get_channel_id(this_ptr: &ChannelDetails) -> *const [u8; 32] {
221 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_id;
224 /// The channel's ID (prior to funding transaction generation, this is a random 32 bytes,
225 /// thereafter this is the txid of the funding transaction xor the funding transaction output).
226 /// Note that this means this value is *not* persistent - it can change once during the
227 /// lifetime of the channel.
229 pub extern "C" fn ChannelDetails_set_channel_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::ThirtyTwoBytes) {
230 unsafe { &mut *this_ptr.inner }.channel_id = val.data;
232 /// The node_id of our counterparty
234 pub extern "C" fn ChannelDetails_get_remote_network_id(this_ptr: &ChannelDetails) -> crate::c_types::PublicKey {
235 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.remote_network_id;
236 crate::c_types::PublicKey::from_rust(&(*inner_val))
238 /// The node_id of our counterparty
240 pub extern "C" fn ChannelDetails_set_remote_network_id(this_ptr: &mut ChannelDetails, mut val: crate::c_types::PublicKey) {
241 unsafe { &mut *this_ptr.inner }.remote_network_id = val.into_rust();
243 /// The Features the channel counterparty provided upon last connection.
244 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
245 /// many routing-relevant features are present in the init context.
247 pub extern "C" fn ChannelDetails_get_counterparty_features(this_ptr: &ChannelDetails) -> crate::ln::features::InitFeatures {
248 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.counterparty_features;
249 crate::ln::features::InitFeatures { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
251 /// The Features the channel counterparty provided upon last connection.
252 /// Useful for routing as it is the most up-to-date copy of the counterparty's features and
253 /// many routing-relevant features are present in the init context.
255 pub extern "C" fn ChannelDetails_set_counterparty_features(this_ptr: &mut ChannelDetails, mut val: crate::ln::features::InitFeatures) {
256 unsafe { &mut *this_ptr.inner }.counterparty_features = *unsafe { Box::from_raw(val.take_inner()) };
258 /// The value, in satoshis, of this channel as appears in the funding output
260 pub extern "C" fn ChannelDetails_get_channel_value_satoshis(this_ptr: &ChannelDetails) -> u64 {
261 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.channel_value_satoshis;
264 /// The value, in satoshis, of this channel as appears in the funding output
266 pub extern "C" fn ChannelDetails_set_channel_value_satoshis(this_ptr: &mut ChannelDetails, mut val: u64) {
267 unsafe { &mut *this_ptr.inner }.channel_value_satoshis = val;
269 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
271 pub extern "C" fn ChannelDetails_get_user_id(this_ptr: &ChannelDetails) -> u64 {
272 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.user_id;
275 /// The user_id passed in to create_channel, or 0 if the channel was inbound.
277 pub extern "C" fn ChannelDetails_set_user_id(this_ptr: &mut ChannelDetails, mut val: u64) {
278 unsafe { &mut *this_ptr.inner }.user_id = val;
280 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
281 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
282 /// available for inclusion in new outbound HTLCs). This further does not include any pending
283 /// outgoing HTLCs which are awaiting some other resolution to be sent.
285 pub extern "C" fn ChannelDetails_get_outbound_capacity_msat(this_ptr: &ChannelDetails) -> u64 {
286 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.outbound_capacity_msat;
289 /// The available outbound capacity for sending HTLCs to the remote peer. This does not include
290 /// any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
291 /// available for inclusion in new outbound HTLCs). This further does not include any pending
292 /// outgoing HTLCs which are awaiting some other resolution to be sent.
294 pub extern "C" fn ChannelDetails_set_outbound_capacity_msat(this_ptr: &mut ChannelDetails, mut val: u64) {
295 unsafe { &mut *this_ptr.inner }.outbound_capacity_msat = val;
297 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
298 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
299 /// available for inclusion in new inbound HTLCs).
300 /// Note that there are some corner cases not fully handled here, so the actual available
301 /// inbound capacity may be slightly higher than this.
303 pub extern "C" fn ChannelDetails_get_inbound_capacity_msat(this_ptr: &ChannelDetails) -> u64 {
304 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.inbound_capacity_msat;
307 /// The available inbound capacity for the remote peer to send HTLCs to us. This does not
308 /// include any pending HTLCs which are not yet fully resolved (and, thus, who's balance is not
309 /// available for inclusion in new inbound HTLCs).
310 /// Note that there are some corner cases not fully handled here, so the actual available
311 /// inbound capacity may be slightly higher than this.
313 pub extern "C" fn ChannelDetails_set_inbound_capacity_msat(this_ptr: &mut ChannelDetails, mut val: u64) {
314 unsafe { &mut *this_ptr.inner }.inbound_capacity_msat = val;
316 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
317 /// the peer is connected, and (c) no monitor update failure is pending resolution.
319 pub extern "C" fn ChannelDetails_get_is_live(this_ptr: &ChannelDetails) -> bool {
320 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.is_live;
323 /// True if the channel is (a) confirmed and funding_locked messages have been exchanged, (b)
324 /// the peer is connected, and (c) no monitor update failure is pending resolution.
326 pub extern "C" fn ChannelDetails_set_is_live(this_ptr: &mut ChannelDetails, mut val: bool) {
327 unsafe { &mut *this_ptr.inner }.is_live = val;
329 impl Clone for ChannelDetails {
330 fn clone(&self) -> Self {
332 inner: if <*mut nativeChannelDetails>::is_null(self.inner) { std::ptr::null_mut() } else {
333 Box::into_raw(Box::new(unsafe { &*self.inner }.clone())) },
339 /// Used only if an object of this type is returned as a trait impl by a method
340 pub(crate) extern "C" fn ChannelDetails_clone_void(this_ptr: *const c_void) -> *mut c_void {
341 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelDetails)).clone() })) as *mut c_void
344 pub extern "C" fn ChannelDetails_clone(orig: &ChannelDetails) -> ChannelDetails {
347 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
348 /// Err() type describing which state the payment is in, see the description of individual enum
353 pub enum PaymentSendFailure {
354 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
355 /// send the payment at all. No channel state has been changed or messages sent to peers, and
356 /// once you've changed the parameter at error, you can freely retry the payment in full.
357 ParameterError(crate::util::errors::APIError),
358 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
359 /// from attempting to send the payment at all. No channel state has been changed or messages
360 /// sent to peers, and once you've changed the parameter at error, you can freely retry the
363 /// The results here are ordered the same as the paths in the route object which was passed to
365 PathParameterError(crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ),
366 /// All paths which were attempted failed to send, with no channel state change taking place.
367 /// You can freely retry the payment in full (though you probably want to do so over different
368 /// paths than the ones selected).
369 AllFailedRetrySafe(crate::c_types::derived::CVec_APIErrorZ),
370 /// Some paths which were attempted failed to send, though possibly not all. At least some
371 /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
372 /// in over-/re-payment.
374 /// The results here are ordered the same as the paths in the route object which was passed to
375 /// send_payment, and any Errs which are not APIError::MonitorUpdateFailed can be safely
376 /// retried (though there is currently no API with which to do so).
378 /// Any entries which contain Err(APIError::MonitorUpdateFailed) or Ok(()) MUST NOT be retried
379 /// as they will result in over-/re-payment. These HTLCs all either successfully sent (in the
380 /// case of Ok(())) or will send once channel_monitor_updated is called on the next-hop channel
381 /// with the latest update_id.
382 PartialFailure(crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ),
384 use lightning::ln::channelmanager::PaymentSendFailure as nativePaymentSendFailure;
385 impl PaymentSendFailure {
387 pub(crate) fn to_native(&self) -> nativePaymentSendFailure {
389 PaymentSendFailure::ParameterError (ref a, ) => {
390 let mut a_nonref = (*a).clone();
391 nativePaymentSendFailure::ParameterError (
392 a_nonref.into_native(),
395 PaymentSendFailure::PathParameterError (ref a, ) => {
396 let mut a_nonref = (*a).clone();
397 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 }); };
398 nativePaymentSendFailure::PathParameterError (
402 PaymentSendFailure::AllFailedRetrySafe (ref a, ) => {
403 let mut a_nonref = (*a).clone();
404 let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { item.into_native() }); };
405 nativePaymentSendFailure::AllFailedRetrySafe (
409 PaymentSendFailure::PartialFailure (ref a, ) => {
410 let mut a_nonref = (*a).clone();
411 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 }); };
412 nativePaymentSendFailure::PartialFailure (
419 pub(crate) fn into_native(self) -> nativePaymentSendFailure {
421 PaymentSendFailure::ParameterError (mut a, ) => {
422 nativePaymentSendFailure::ParameterError (
426 PaymentSendFailure::PathParameterError (mut a, ) => {
427 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 }); };
428 nativePaymentSendFailure::PathParameterError (
432 PaymentSendFailure::AllFailedRetrySafe (mut a, ) => {
433 let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { item.into_native() }); };
434 nativePaymentSendFailure::AllFailedRetrySafe (
438 PaymentSendFailure::PartialFailure (mut a, ) => {
439 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 }); };
440 nativePaymentSendFailure::PartialFailure (
447 pub(crate) fn from_native(native: &nativePaymentSendFailure) -> Self {
449 nativePaymentSendFailure::ParameterError (ref a, ) => {
450 let mut a_nonref = (*a).clone();
451 PaymentSendFailure::ParameterError (
452 crate::util::errors::APIError::native_into(a_nonref),
455 nativePaymentSendFailure::PathParameterError (ref a, ) => {
456 let mut a_nonref = (*a).clone();
457 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 }); };
458 PaymentSendFailure::PathParameterError (
459 local_a_nonref.into(),
462 nativePaymentSendFailure::AllFailedRetrySafe (ref a, ) => {
463 let mut a_nonref = (*a).clone();
464 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) }); };
465 PaymentSendFailure::AllFailedRetrySafe (
466 local_a_nonref.into(),
469 nativePaymentSendFailure::PartialFailure (ref a, ) => {
470 let mut a_nonref = (*a).clone();
471 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 }); };
472 PaymentSendFailure::PartialFailure (
473 local_a_nonref.into(),
479 pub(crate) fn native_into(native: nativePaymentSendFailure) -> Self {
481 nativePaymentSendFailure::ParameterError (mut a, ) => {
482 PaymentSendFailure::ParameterError (
483 crate::util::errors::APIError::native_into(a),
486 nativePaymentSendFailure::PathParameterError (mut a, ) => {
487 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 }); };
488 PaymentSendFailure::PathParameterError (
492 nativePaymentSendFailure::AllFailedRetrySafe (mut a, ) => {
493 let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { crate::util::errors::APIError::native_into(item) }); };
494 PaymentSendFailure::AllFailedRetrySafe (
498 nativePaymentSendFailure::PartialFailure (mut a, ) => {
499 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 }); };
500 PaymentSendFailure::PartialFailure (
508 pub extern "C" fn PaymentSendFailure_free(this_ptr: PaymentSendFailure) { }
510 pub extern "C" fn PaymentSendFailure_clone(orig: &PaymentSendFailure) -> PaymentSendFailure {
513 /// Constructs a new ChannelManager to hold several channels and route between them.
515 /// This is the main \"logic hub\" for all channel-related actions, and implements
516 /// ChannelMessageHandler.
518 /// Non-proportional fees are fixed according to our risk using the provided fee estimator.
520 /// panics if channel_value_satoshis is >= `MAX_FUNDING_SATOSHIS`!
522 /// Users need to notify the new ChannelManager when a new block is connected or
523 /// disconnected using its `block_connected` and `block_disconnected` methods, starting
524 /// from after `params.latest_hash`.
527 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 {
528 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()) });
529 ChannelManager { inner: Box::into_raw(Box::new(ret)), is_owned: true }
532 /// Creates a new outbound channel to the given remote node and with the given value.
534 /// user_id will be provided back as user_channel_id in FundingGenerationReady and
535 /// FundingBroadcastSafe events to allow tracking of which events correspond with which
536 /// create_channel call. Note that user_channel_id defaults to 0 for inbound channels, so you
537 /// may wish to avoid using 0 for user_id here.
539 /// If successful, will generate a SendOpenChannel message event, so you should probably poll
540 /// PeerManager::process_events afterwards.
542 /// Raises APIError::APIMisuseError when channel_value_satoshis > 2**24 or push_msat is
543 /// greater than channel_value_satoshis * 1k or channel_value_satoshis is < 1000.
546 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 {
547 let mut local_override_config = if override_config.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(override_config.take_inner()) } }) };
548 let mut ret = unsafe { &*this_arg.inner }.create_channel(their_network_key.into_rust(), channel_value_satoshis, push_msat, user_id, local_override_config);
549 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() };
553 /// Gets the list of open channels, in random order. See ChannelDetail field documentation for
554 /// more information.
557 pub extern "C" fn ChannelManager_list_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
558 let mut ret = unsafe { &*this_arg.inner }.list_channels();
559 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 } }); };
563 /// Gets the list of usable channels, in random order. Useful as an argument to
564 /// get_route to ensure non-announced channels are used.
566 /// These are guaranteed to have their is_live value set to true, see the documentation for
567 /// ChannelDetails::is_live for more info on exactly what the criteria are.
570 pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ {
571 let mut ret = unsafe { &*this_arg.inner }.list_usable_channels();
572 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 } }); };
576 /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs
577 /// will be accepted on the given channel, and after additional timeout/the closing of all
578 /// pending HTLCs, the channel will be closed on chain.
580 /// May generate a SendShutdown message event on success, which should be relayed.
583 pub extern "C" fn ChannelManager_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
584 let mut ret = unsafe { &*this_arg.inner }.close_channel(unsafe { &*channel_id});
585 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() };
589 /// Force closes a channel, immediately broadcasting the latest local commitment transaction to
590 /// the chain and rejecting new HTLCs on the given channel. Fails if channel_id is unknown to the manager.
593 pub extern "C" fn ChannelManager_force_close_channel(this_arg: &ChannelManager, channel_id: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneAPIErrorZ {
594 let mut ret = unsafe { &*this_arg.inner }.force_close_channel(unsafe { &*channel_id});
595 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() };
599 /// Force close all channels, immediately broadcasting the latest local commitment transaction
600 /// for each to the chain and rejecting new HTLCs on each.
602 pub extern "C" fn ChannelManager_force_close_all_channels(this_arg: &ChannelManager) {
603 unsafe { &*this_arg.inner }.force_close_all_channels()
606 /// Sends a payment along a given route.
608 /// Value parameters are provided via the last hop in route, see documentation for RouteHop
609 /// fields for more info.
611 /// Note that if the payment_hash already exists elsewhere (eg you're sending a duplicative
612 /// payment), we don't do anything to stop you! We always try to ensure that if the provided
613 /// next hop knows the preimage to payment_hash they can claim an additional amount as
614 /// specified in the last hop in the route! Thus, you should probably do your own
615 /// payment_preimage tracking (which you should already be doing as they represent \"proof of
616 /// payment\") and prevent double-sends yourself.
618 /// May generate SendHTLCs message(s) event on success, which should be relayed.
620 /// Each path may have a different return value, and PaymentSendValue may return a Vec with
621 /// each entry matching the corresponding-index entry in the route paths, see
622 /// PaymentSendFailure for more info.
624 /// In general, a path may raise:
625 /// * APIError::RouteError when an invalid route or forwarding parameter (cltv_delta, fee,
626 /// node public key) is specified.
627 /// * APIError::ChannelUnavailable if the next-hop channel is not available for updates
628 /// (including due to previous monitor update failure or new permanent monitor update
630 /// * APIError::MonitorUpdateFailed if a new monitor update failure prevented sending the
631 /// relevant updates.
633 /// Note that depending on the type of the PaymentSendFailure the HTLC may have been
634 /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a
635 /// different route unless you intend to pay twice!
637 /// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate
638 /// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For
639 /// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route
640 /// must not contain multiple paths as multi-path payments require a recipient-provided
642 /// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature
643 /// bit set (either as required or as available). If multiple paths are present in the Route,
644 /// we assume the invoice had the basic_mpp feature set.
647 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 {
648 let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentSecret(payment_secret.data) }) };
649 let mut ret = unsafe { &*this_arg.inner }.send_payment(unsafe { &*route.inner }, ::lightning::ln::channelmanager::PaymentHash(payment_hash.data), &local_payment_secret);
650 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() };
654 /// Call this upon creation of a funding transaction for the given channel.
656 /// Note that ALL inputs in the transaction pointed to by funding_txo MUST spend SegWit outputs
657 /// or your counterparty can steal your funds!
659 /// Panics if a funding transaction has already been provided for this channel.
661 /// May panic if the funding_txo is duplicative with some other channel (note that this should
662 /// be trivially prevented by using unique funding transaction keys per-channel).
664 pub extern "C" fn ChannelManager_funding_transaction_generated(this_arg: &ChannelManager, temporary_channel_id: *const [u8; 32], mut funding_txo: crate::chain::transaction::OutPoint) {
665 unsafe { &*this_arg.inner }.funding_transaction_generated(unsafe { &*temporary_channel_id}, *unsafe { Box::from_raw(funding_txo.take_inner()) })
668 /// Generates a signed node_announcement from the given arguments and creates a
669 /// BroadcastNodeAnnouncement event. Note that such messages will be ignored unless peers have
670 /// seen a channel_announcement from us (ie unless we have public channels open).
672 /// RGB is a node \"color\" and alias is a printable human-readable string to describe this node
673 /// to humans. They carry no in-protocol meaning.
675 /// addresses represent the set (possibly empty) of socket addresses on which this node accepts
676 /// incoming connections. These will be broadcast to the network, publicly tying these
677 /// addresses together. If you wish to preserve user privacy, addresses should likely contain
678 /// only Tor Onion addresses.
680 /// Panics if addresses is absurdly large (more than 500).
682 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) {
683 let mut local_addresses = Vec::new(); for mut item in addresses.into_rust().drain(..) { local_addresses.push( { item.into_native() }); };
684 unsafe { &*this_arg.inner }.broadcast_node_announcement(rgb.data, alias.data, local_addresses)
687 /// Processes HTLCs which are pending waiting on random forward delay.
689 /// Should only really ever be called in response to a PendingHTLCsForwardable event.
690 /// Will likely generate further events.
692 pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &ChannelManager) {
693 unsafe { &*this_arg.inner }.process_pending_htlc_forwards()
696 /// If a peer is disconnected we mark any channels with that peer as 'disabled'.
697 /// After some time, if channels are still disabled we need to broadcast a ChannelUpdate
698 /// to inform the network about the uselessness of these channels.
700 /// This method handles all the details, and must be called roughly once per minute.
702 /// Note that in some rare cases this may generate a `chain::Watch::update_channel` call.
704 pub extern "C" fn ChannelManager_timer_chan_freshness_every_min(this_arg: &ChannelManager) {
705 unsafe { &*this_arg.inner }.timer_chan_freshness_every_min()
708 /// Indicates that the preimage for payment_hash is unknown or the received amount is incorrect
709 /// after a PaymentReceived event, failing the HTLC back to its origin and freeing resources
710 /// along the path (including in our own channel on which we received it).
711 /// Returns false if no payment was found to fail backwards, true if the process of failing the
712 /// HTLC backwards has been started.
715 pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &ChannelManager, payment_hash: *const [u8; 32], mut payment_secret: crate::c_types::ThirtyTwoBytes) -> bool {
716 let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentSecret(payment_secret.data) }) };
717 let mut ret = unsafe { &*this_arg.inner }.fail_htlc_backwards(&::lightning::ln::channelmanager::PaymentHash(unsafe { *payment_hash }), &local_payment_secret);
721 /// Provides a payment preimage in response to a PaymentReceived event, returning true and
722 /// generating message events for the net layer to claim the payment, if possible. Thus, you
723 /// should probably kick the net layer to go send messages if this returns true!
725 /// You must specify the expected amounts for this HTLC, and we will only claim HTLCs
726 /// available within a few percent of the expected amount. This is critical for several
727 /// reasons : a) it avoids providing senders with `proof-of-payment` (in the form of the
728 /// payment_preimage without having provided the full value and b) it avoids certain
729 /// privacy-breaking recipient-probing attacks which may reveal payment activity to
730 /// motivated attackers.
732 /// Note that the privacy concerns in (b) are not relevant in payments with a payment_secret
733 /// set. Thus, for such payments we will claim any payments which do not under-pay.
735 /// May panic if called except in response to a PaymentReceived event.
738 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 {
739 let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentSecret(payment_secret.data) }) };
740 let mut ret = unsafe { &*this_arg.inner }.claim_funds(::lightning::ln::channelmanager::PaymentPreimage(payment_preimage.data), &local_payment_secret, expected_amount);
744 /// Gets the node_id held by this ChannelManager
747 pub extern "C" fn ChannelManager_get_our_node_id(this_arg: &ChannelManager) -> crate::c_types::PublicKey {
748 let mut ret = unsafe { &*this_arg.inner }.get_our_node_id();
749 crate::c_types::PublicKey::from_rust(&ret)
752 /// Restores a single, given channel to normal operation after a
753 /// ChannelMonitorUpdateErr::TemporaryFailure was returned from a channel monitor update
756 /// All ChannelMonitor updates up to and including highest_applied_update_id must have been
757 /// fully committed in every copy of the given channels' ChannelMonitors.
759 /// Note that there is no effect to calling with a highest_applied_update_id other than the
760 /// current latest ChannelMonitorUpdate and one call to this function after multiple
761 /// ChannelMonitorUpdateErr::TemporaryFailures is fine. The highest_applied_update_id field
762 /// exists largely only to prevent races between this and concurrent update_monitor calls.
764 /// Thus, the anticipated use is, at a high level:
765 /// 1) You register a chain::Watch with this ChannelManager,
766 /// 2) it stores each update to disk, and begins updating any remote (eg watchtower) copies of
767 /// said ChannelMonitors as it can, returning ChannelMonitorUpdateErr::TemporaryFailures
768 /// any time it cannot do so instantly,
769 /// 3) update(s) are applied to each remote copy of a ChannelMonitor,
770 /// 4) once all remote copies are updated, you call this function with the update_id that
771 /// completed, and once it is the latest the Channel will be re-enabled.
773 pub extern "C" fn ChannelManager_channel_monitor_updated(this_arg: &ChannelManager, funding_txo: &crate::chain::transaction::OutPoint, mut highest_applied_update_id: u64) {
774 unsafe { &*this_arg.inner }.channel_monitor_updated(unsafe { &*funding_txo.inner }, highest_applied_update_id)
777 impl From<nativeChannelManager> for crate::util::events::MessageSendEventsProvider {
778 fn from(obj: nativeChannelManager) -> Self {
779 let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
780 let mut ret = ChannelManager_as_MessageSendEventsProvider(&rust_obj);
781 // 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
782 rust_obj.inner = std::ptr::null_mut();
783 ret.free = Some(ChannelManager_free_void);
788 pub extern "C" fn ChannelManager_as_MessageSendEventsProvider(this_arg: &ChannelManager) -> crate::util::events::MessageSendEventsProvider {
789 crate::util::events::MessageSendEventsProvider {
790 this_arg: unsafe { (*this_arg).inner as *mut c_void },
792 get_and_clear_pending_msg_events: ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events,
797 extern "C" fn ChannelManager_MessageSendEventsProvider_get_and_clear_pending_msg_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MessageSendEventZ {
798 let mut ret = <nativeChannelManager as lightning::util::events::MessageSendEventsProvider<>>::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
799 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::MessageSendEvent::native_into(item) }); };
803 impl From<nativeChannelManager> for crate::util::events::EventsProvider {
804 fn from(obj: nativeChannelManager) -> Self {
805 let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
806 let mut ret = ChannelManager_as_EventsProvider(&rust_obj);
807 // 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
808 rust_obj.inner = std::ptr::null_mut();
809 ret.free = Some(ChannelManager_free_void);
814 pub extern "C" fn ChannelManager_as_EventsProvider(this_arg: &ChannelManager) -> crate::util::events::EventsProvider {
815 crate::util::events::EventsProvider {
816 this_arg: unsafe { (*this_arg).inner as *mut c_void },
818 get_and_clear_pending_events: ChannelManager_EventsProvider_get_and_clear_pending_events,
823 extern "C" fn ChannelManager_EventsProvider_get_and_clear_pending_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_EventZ {
824 let mut ret = <nativeChannelManager as lightning::util::events::EventsProvider<>>::get_and_clear_pending_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
825 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::Event::native_into(item) }); };
829 impl From<nativeChannelManager> for crate::chain::Listen {
830 fn from(obj: nativeChannelManager) -> Self {
831 let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
832 let mut ret = ChannelManager_as_Listen(&rust_obj);
833 // 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
834 rust_obj.inner = std::ptr::null_mut();
835 ret.free = Some(ChannelManager_free_void);
840 pub extern "C" fn ChannelManager_as_Listen(this_arg: &ChannelManager) -> crate::chain::Listen {
841 crate::chain::Listen {
842 this_arg: unsafe { (*this_arg).inner as *mut c_void },
844 block_connected: ChannelManager_Listen_block_connected,
845 block_disconnected: ChannelManager_Listen_block_disconnected,
849 extern "C" fn ChannelManager_Listen_block_connected(this_arg: *const c_void, mut block: crate::c_types::u8slice, mut height: u32) {
850 <nativeChannelManager as lightning::chain::Listen<>>::block_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(block.to_slice()).unwrap(), height)
852 extern "C" fn ChannelManager_Listen_block_disconnected(this_arg: *const c_void, header: *const [u8; 80], mut _height: u32) {
853 <nativeChannelManager as lightning::chain::Listen<>>::block_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), _height)
856 /// Updates channel state based on transactions seen in a connected block.
858 pub extern "C" fn ChannelManager_block_connected(this_arg: &ChannelManager, header: *const [u8; 80], mut txdata: crate::c_types::derived::CVec_C2Tuple_usizeTransactionZZ, mut height: u32) {
859 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 }); };
860 unsafe { &*this_arg.inner }.block_connected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap(), &local_txdata.iter().map(|(a, b)| (*a, b)).collect::<Vec<_>>()[..], height)
863 /// Updates channel state based on a disconnected block.
865 /// If necessary, the channel may be force-closed without letting the counterparty participate
868 pub extern "C" fn ChannelManager_block_disconnected(this_arg: &ChannelManager, header: *const [u8; 80]) {
869 unsafe { &*this_arg.inner }.block_disconnected(&::bitcoin::consensus::encode::deserialize(unsafe { &*header }).unwrap())
872 /// Blocks until ChannelManager needs to be persisted. Only one listener on
873 /// `await_persistable_update` or `await_persistable_update_timeout` is guaranteed to be woken
876 pub extern "C" fn ChannelManager_await_persistable_update(this_arg: &ChannelManager) {
877 unsafe { &*this_arg.inner }.await_persistable_update()
880 impl From<nativeChannelManager> for crate::ln::msgs::ChannelMessageHandler {
881 fn from(obj: nativeChannelManager) -> Self {
882 let mut rust_obj = ChannelManager { inner: Box::into_raw(Box::new(obj)), is_owned: true };
883 let mut ret = ChannelManager_as_ChannelMessageHandler(&rust_obj);
884 // 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
885 rust_obj.inner = std::ptr::null_mut();
886 ret.free = Some(ChannelManager_free_void);
891 pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelManager) -> crate::ln::msgs::ChannelMessageHandler {
892 crate::ln::msgs::ChannelMessageHandler {
893 this_arg: unsafe { (*this_arg).inner as *mut c_void },
895 handle_open_channel: ChannelManager_ChannelMessageHandler_handle_open_channel,
896 handle_accept_channel: ChannelManager_ChannelMessageHandler_handle_accept_channel,
897 handle_funding_created: ChannelManager_ChannelMessageHandler_handle_funding_created,
898 handle_funding_signed: ChannelManager_ChannelMessageHandler_handle_funding_signed,
899 handle_funding_locked: ChannelManager_ChannelMessageHandler_handle_funding_locked,
900 handle_shutdown: ChannelManager_ChannelMessageHandler_handle_shutdown,
901 handle_closing_signed: ChannelManager_ChannelMessageHandler_handle_closing_signed,
902 handle_update_add_htlc: ChannelManager_ChannelMessageHandler_handle_update_add_htlc,
903 handle_update_fulfill_htlc: ChannelManager_ChannelMessageHandler_handle_update_fulfill_htlc,
904 handle_update_fail_htlc: ChannelManager_ChannelMessageHandler_handle_update_fail_htlc,
905 handle_update_fail_malformed_htlc: ChannelManager_ChannelMessageHandler_handle_update_fail_malformed_htlc,
906 handle_commitment_signed: ChannelManager_ChannelMessageHandler_handle_commitment_signed,
907 handle_revoke_and_ack: ChannelManager_ChannelMessageHandler_handle_revoke_and_ack,
908 handle_update_fee: ChannelManager_ChannelMessageHandler_handle_update_fee,
909 handle_announcement_signatures: ChannelManager_ChannelMessageHandler_handle_announcement_signatures,
910 peer_disconnected: ChannelManager_ChannelMessageHandler_peer_disconnected,
911 peer_connected: ChannelManager_ChannelMessageHandler_peer_connected,
912 handle_channel_reestablish: ChannelManager_ChannelMessageHandler_handle_channel_reestablish,
913 handle_error: ChannelManager_ChannelMessageHandler_handle_error,
914 MessageSendEventsProvider: crate::util::events::MessageSendEventsProvider {
915 this_arg: unsafe { (*this_arg).inner as *mut c_void },
917 get_and_clear_pending_msg_events: ChannelManager_ChannelMessageHandler_get_and_clear_pending_msg_events,
922 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) {
923 <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 })
925 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) {
926 <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 })
928 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) {
929 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
931 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) {
932 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
934 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) {
935 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_funding_locked(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
937 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) {
938 <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 })
940 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) {
941 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
943 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) {
944 <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 })
946 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) {
947 <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 })
949 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) {
950 <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 })
952 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) {
953 <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 })
955 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) {
956 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_commitment_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
958 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) {
959 <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 })
961 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) {
962 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_update_fee(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
964 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) {
965 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
967 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) {
968 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_channel_reestablish(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
970 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) {
971 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), no_connection_possible)
973 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) {
974 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*init_msg.inner })
976 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) {
977 <nativeChannelManager as lightning::ln::msgs::ChannelMessageHandler<>>::handle_error(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &counterparty_node_id.into_rust(), unsafe { &*msg.inner })
980 extern "C" fn ChannelManager_ChannelMessageHandler_get_and_clear_pending_msg_events(this_arg: *const c_void) -> crate::c_types::derived::CVec_MessageSendEventZ {
981 let mut ret = <nativeChannelManager as lightning::util::events::MessageSendEventsProvider<>>::get_and_clear_pending_msg_events(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, );
982 let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::util::events::MessageSendEvent::native_into(item) }); };
987 pub extern "C" fn ChannelManager_write(obj: &ChannelManager) -> crate::c_types::derived::CVec_u8Z {
988 crate::c_types::serialize_obj(unsafe { &*unsafe { &*obj }.inner })
991 pub(crate) extern "C" fn ChannelManager_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
992 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelManager) })
995 use lightning::ln::channelmanager::ChannelManagerReadArgs as nativeChannelManagerReadArgsImport;
996 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>;
998 /// Arguments for the creation of a ChannelManager that are not deserialized.
1000 /// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
1002 /// 1) Deserialize all stored ChannelMonitors.
1003 /// 2) Deserialize the ChannelManager by filling in this struct and calling:
1004 /// <(BlockHash, ChannelManager)>::read(reader, args)
1005 /// This may result in closing some Channels if the ChannelMonitor is newer than the stored
1006 /// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
1007 /// 3) If you are not fetching full blocks, register all relevant ChannelMonitor outpoints the same
1008 /// way you would handle a `chain::Filter` call using ChannelMonitor::get_outputs_to_watch() and
1009 /// ChannelMonitor::get_funding_txo().
1010 /// 4) Reconnect blocks on your ChannelMonitors.
1011 /// 5) Disconnect/connect blocks on the ChannelManager.
1012 /// 6) Move the ChannelMonitors into your local chain::Watch.
1014 /// Note that the ordering of #4-6 is not of importance, however all three must occur before you
1015 /// call any other methods on the newly-deserialized ChannelManager.
1017 /// Note that because some channels may be closed during deserialization, it is critical that you
1018 /// always deserialize only the latest version of a ChannelManager and ChannelMonitors available to
1019 /// you. If you deserialize an old ChannelManager (during which force-closure transactions may be
1020 /// broadcast), and then later deserialize a newer version of the same ChannelManager (which will
1021 /// not force-close the same channels but consider them live), you may end up revoking a state for
1022 /// which you've already broadcasted the transaction.
1025 pub struct ChannelManagerReadArgs {
1026 /// Nearly everywhere, inner must be non-null, however in places where
1027 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1028 pub inner: *mut nativeChannelManagerReadArgs,
1032 impl Drop for ChannelManagerReadArgs {
1033 fn drop(&mut self) {
1034 if self.is_owned && !<*mut nativeChannelManagerReadArgs>::is_null(self.inner) {
1035 let _ = unsafe { Box::from_raw(self.inner) };
1040 pub extern "C" fn ChannelManagerReadArgs_free(this_ptr: ChannelManagerReadArgs) { }
1042 /// Used only if an object of this type is returned as a trait impl by a method
1043 extern "C" fn ChannelManagerReadArgs_free_void(this_ptr: *mut c_void) {
1044 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelManagerReadArgs); }
1047 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1048 impl ChannelManagerReadArgs {
1049 pub(crate) fn take_inner(mut self) -> *mut nativeChannelManagerReadArgs {
1050 assert!(self.is_owned);
1051 let ret = self.inner;
1052 self.inner = std::ptr::null_mut();
1056 /// The keys provider which will give us relevant keys. Some keys will be loaded during
1057 /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
1060 pub extern "C" fn ChannelManagerReadArgs_get_keys_manager(this_ptr: &ChannelManagerReadArgs) -> *const crate::chain::keysinterface::KeysInterface {
1061 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.keys_manager;
1064 /// The keys provider which will give us relevant keys. Some keys will be loaded during
1065 /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel
1068 pub extern "C" fn ChannelManagerReadArgs_set_keys_manager(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::chain::keysinterface::KeysInterface) {
1069 unsafe { &mut *this_ptr.inner }.keys_manager = val;
1071 /// The fee_estimator for use in the ChannelManager in the future.
1073 /// No calls to the FeeEstimator will be made during deserialization.
1075 pub extern "C" fn ChannelManagerReadArgs_get_fee_estimator(this_ptr: &ChannelManagerReadArgs) -> *const crate::chain::chaininterface::FeeEstimator {
1076 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.fee_estimator;
1079 /// The fee_estimator for use in the ChannelManager in the future.
1081 /// No calls to the FeeEstimator will be made during deserialization.
1083 pub extern "C" fn ChannelManagerReadArgs_set_fee_estimator(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::chain::chaininterface::FeeEstimator) {
1084 unsafe { &mut *this_ptr.inner }.fee_estimator = val;
1086 /// The chain::Watch for use in the ChannelManager in the future.
1088 /// No calls to the chain::Watch will be made during deserialization. It is assumed that
1089 /// you have deserialized ChannelMonitors separately and will add them to your
1090 /// chain::Watch after deserializing this ChannelManager.
1092 pub extern "C" fn ChannelManagerReadArgs_get_chain_monitor(this_ptr: &ChannelManagerReadArgs) -> *const crate::chain::Watch {
1093 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.chain_monitor;
1096 /// The chain::Watch for use in the ChannelManager in the future.
1098 /// No calls to the chain::Watch will be made during deserialization. It is assumed that
1099 /// you have deserialized ChannelMonitors separately and will add them to your
1100 /// chain::Watch after deserializing this ChannelManager.
1102 pub extern "C" fn ChannelManagerReadArgs_set_chain_monitor(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::chain::Watch) {
1103 unsafe { &mut *this_ptr.inner }.chain_monitor = val;
1105 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
1106 /// used to broadcast the latest local commitment transactions of channels which must be
1107 /// force-closed during deserialization.
1109 pub extern "C" fn ChannelManagerReadArgs_get_tx_broadcaster(this_ptr: &ChannelManagerReadArgs) -> *const crate::chain::chaininterface::BroadcasterInterface {
1110 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.tx_broadcaster;
1113 /// The BroadcasterInterface which will be used in the ChannelManager in the future and may be
1114 /// used to broadcast the latest local commitment transactions of channels which must be
1115 /// force-closed during deserialization.
1117 pub extern "C" fn ChannelManagerReadArgs_set_tx_broadcaster(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::chain::chaininterface::BroadcasterInterface) {
1118 unsafe { &mut *this_ptr.inner }.tx_broadcaster = val;
1120 /// The Logger for use in the ChannelManager and which may be used to log information during
1121 /// deserialization.
1123 pub extern "C" fn ChannelManagerReadArgs_get_logger(this_ptr: &ChannelManagerReadArgs) -> *const crate::util::logger::Logger {
1124 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.logger;
1127 /// The Logger for use in the ChannelManager and which may be used to log information during
1128 /// deserialization.
1130 pub extern "C" fn ChannelManagerReadArgs_set_logger(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::util::logger::Logger) {
1131 unsafe { &mut *this_ptr.inner }.logger = val;
1133 /// Default settings used for new channels. Any existing channels will continue to use the
1134 /// runtime settings which were stored when the ChannelManager was serialized.
1136 pub extern "C" fn ChannelManagerReadArgs_get_default_config(this_ptr: &ChannelManagerReadArgs) -> crate::util::config::UserConfig {
1137 let mut inner_val = &mut unsafe { &mut *this_ptr.inner }.default_config;
1138 crate::util::config::UserConfig { inner: unsafe { ( (&((*inner_val)) as *const _) as *mut _) }, is_owned: false }
1140 /// Default settings used for new channels. Any existing channels will continue to use the
1141 /// runtime settings which were stored when the ChannelManager was serialized.
1143 pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::util::config::UserConfig) {
1144 unsafe { &mut *this_ptr.inner }.default_config = *unsafe { Box::from_raw(val.take_inner()) };
1146 /// Simple utility function to create a ChannelManagerReadArgs which creates the monitor
1147 /// HashMap for you. This is primarily useful for C bindings where it is not practical to
1148 /// populate a HashMap directly from C.
1151 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 {
1152 let mut local_channel_monitors = Vec::new(); for mut item in channel_monitors.into_rust().drain(..) { local_channel_monitors.push( { unsafe { &mut *item.inner } }); };
1153 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);
1154 ChannelManagerReadArgs { inner: Box::into_raw(Box::new(ret)), is_owned: true }
1158 pub extern "C" fn C2Tuple_BlockHashChannelManagerZ_read(ser: crate::c_types::u8slice, arg: crate::ln::channelmanager::ChannelManagerReadArgs) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ {
1159 let arg_conv = *unsafe { Box::from_raw(arg.take_inner()) };
1160 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);
1161 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() };