From 11b997c3a0452ea1da5b7b352e7887798105db29 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Wed, 1 Mar 2023 05:53:56 +0000 Subject: [PATCH] Update auto-generated bindings --- lightning-c-bindings/include/ldk_rust_types.h | 14 +- lightning-c-bindings/include/lightning.h | 5360 ++++++++++------- lightning-c-bindings/include/lightningpp.hpp | 1483 +++-- lightning-c-bindings/src/c_types/derived.rs | 2133 ++++--- .../src/lightning/chain/chainmonitor.rs | 18 +- .../src/lightning/chain/channelmonitor.rs | 10 +- .../src/lightning/chain/keysinterface.rs | 1152 ++-- .../src/lightning/chain/mod.rs | 129 +- .../src/lightning/ln/channelmanager.rs | 702 ++- .../src/lightning/ln/features.rs | 356 +- .../src/lightning/ln/inbound_payment.rs | 23 +- lightning-c-bindings/src/lightning/ln/mod.rs | 1 + lightning-c-bindings/src/lightning/ln/msgs.rs | 712 ++- .../src/lightning/ln/outbound_payment.rs | 475 ++ .../src/lightning/ln/peer_handler.rs | 124 +- lightning-c-bindings/src/lightning/mod.rs | 55 + .../lightning/onion_message/blinded_path.rs | 4 +- .../src/lightning/onion_message/messenger.rs | 30 +- .../src/lightning/routing/gossip.rs | 84 +- .../src/lightning/routing/mod.rs | 1 + .../src/lightning/routing/router.rs | 137 +- .../src/lightning/routing/scoring.rs | 31 +- .../src/lightning/routing/utxo.rs | 358 ++ .../src/lightning/util/config.rs | 10 +- .../src/lightning/util/errors.rs | 20 +- .../src/lightning/util/events.rs | 313 +- .../src/lightning/util/indexed_map.rs | 18 + .../src/lightning/util/mod.rs | 24 +- .../src/lightning/util/persist.rs | 6 +- .../src/lightning/util/ser.rs | 11 +- .../src/lightning/util/ser_macros.rs | 22 + .../src/lightning_background_processor.rs | 2 +- .../src/lightning_invoice/constants.rs | 2 +- .../src/lightning_invoice/mod.rs | 92 +- .../src/lightning_invoice/payment.rs | 636 +- .../src/lightning_invoice/utils.rs | 138 +- .../src/lightning_persister.rs | 4 +- .../src/lightning_rapid_gossip_sync/mod.rs | 25 +- 38 files changed, 8927 insertions(+), 5788 deletions(-) create mode 100644 lightning-c-bindings/src/lightning/ln/outbound_payment.rs create mode 100644 lightning-c-bindings/src/lightning/routing/utxo.rs create mode 100644 lightning-c-bindings/src/lightning/util/indexed_map.rs create mode 100644 lightning-c-bindings/src/lightning/util/ser_macros.rs diff --git a/lightning-c-bindings/include/ldk_rust_types.h b/lightning-c-bindings/include/ldk_rust_types.h index 7432c15..5f546fe 100644 --- a/lightning-c-bindings/include/ldk_rust_types.h +++ b/lightning-c-bindings/include/ldk_rust_types.h @@ -92,6 +92,10 @@ struct nativeOfferFeaturesOpaque; typedef struct nativeOfferFeaturesOpaque LDKnativeOfferFeatures; struct nativeInvoiceRequestFeaturesOpaque; typedef struct nativeInvoiceRequestFeaturesOpaque LDKnativeInvoiceRequestFeatures; +struct nativeBolt12InvoiceFeaturesOpaque; +typedef struct nativeBolt12InvoiceFeaturesOpaque LDKnativeBolt12InvoiceFeatures; +struct nativeBlindedHopFeaturesOpaque; +typedef struct nativeBlindedHopFeaturesOpaque LDKnativeBlindedHopFeatures; struct nativeChannelTypeFeaturesOpaque; typedef struct nativeChannelTypeFeaturesOpaque LDKnativeChannelTypeFeatures; struct nativeNodeIdOpaque; @@ -120,7 +124,7 @@ struct nativeDelayedPaymentOutputDescriptorOpaque; typedef struct nativeDelayedPaymentOutputDescriptorOpaque LDKnativeDelayedPaymentOutputDescriptor; struct nativeStaticPaymentOutputDescriptorOpaque; typedef struct nativeStaticPaymentOutputDescriptorOpaque LDKnativeStaticPaymentOutputDescriptor; -struct LDKBaseSign; +struct LDKChannelSigner; struct nativeInMemorySignerOpaque; typedef struct nativeInMemorySignerOpaque LDKnativeInMemorySigner; struct nativeKeysManagerOpaque; @@ -159,8 +163,6 @@ struct nativePrintableStringOpaque; typedef struct nativePrintableStringOpaque LDKnativePrintableString; struct nativeOutPointOpaque; typedef struct nativeOutPointOpaque LDKnativeOutPoint; -struct nativeInvoicePayerOpaque; -typedef struct nativeInvoicePayerOpaque LDKnativeInvoicePayer; struct nativeChannelMonitorUpdateOpaque; typedef struct nativeChannelMonitorUpdateOpaque LDKnativeChannelMonitorUpdate; struct nativeHTLCUpdateOpaque; @@ -179,6 +181,8 @@ struct nativePeerHandleErrorOpaque; typedef struct nativePeerHandleErrorOpaque LDKnativePeerHandleError; struct nativePeerManagerOpaque; typedef struct nativePeerManagerOpaque LDKnativePeerManager; +struct nativeUtxoFutureOpaque; +typedef struct nativeUtxoFutureOpaque LDKnativeUtxoFuture; struct nativeOnionMessengerOpaque; typedef struct nativeOnionMessengerOpaque LDKnativeOnionMessenger; struct nativeInvoiceOpaque; @@ -199,8 +203,8 @@ struct nativePayeePubKeyOpaque; typedef struct nativePayeePubKeyOpaque LDKnativePayeePubKey; struct nativeExpiryTimeOpaque; typedef struct nativeExpiryTimeOpaque LDKnativeExpiryTime; -struct nativeMinFinalCltvExpiryOpaque; -typedef struct nativeMinFinalCltvExpiryOpaque LDKnativeMinFinalCltvExpiry; +struct nativeMinFinalCltvExpiryDeltaOpaque; +typedef struct nativeMinFinalCltvExpiryDeltaOpaque LDKnativeMinFinalCltvExpiryDelta; struct nativeInvoiceSignatureOpaque; typedef struct nativeInvoiceSignatureOpaque LDKnativeInvoiceSignature; struct nativePrivateRouteOpaque; diff --git a/lightning-c-bindings/include/lightning.h b/lightning-c-bindings/include/lightning.h index af9b134..401ba8d 100644 --- a/lightning-c-bindings/include/lightning.h +++ b/lightning-c-bindings/include/lightning.h @@ -10,24 +10,6 @@ #include #include "ldk_rust_types.h" -/** - * An error when accessing the chain via [`Access`]. - */ -typedef enum LDKAccessError { - /** - * The requested chain is unknown. - */ - LDKAccessError_UnknownChain, - /** - * The requested transaction doesn't exist or hasn't confirmed. - */ - LDKAccessError_UnknownTx, - /** - * Must be last for serialization purposes - */ - LDKAccessError_Sentinel, -} LDKAccessError; - /** * An enum which can either contain a or not */ @@ -185,6 +167,12 @@ typedef enum LDKCreationError { * [phantom invoices]: crate::utils::create_phantom_invoice */ LDKCreationError_MissingRouteHints, + /** + * The provided `min_final_cltv_expiry_delta` was less than [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. + * + * [`MIN_FINAL_CLTV_EXPIRY_DELTA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA + */ + LDKCreationError_MinFinalCltvExpiryDeltaTooShort, /** * Must be last for serialization purposes */ @@ -221,6 +209,36 @@ typedef enum LDKCurrency { LDKCurrency_Sentinel, } LDKCurrency; +/** + * This enum is used to specify which error data to send to peers when failing back an HTLC + * using [`ChannelManager::fail_htlc_backwards_with_reason`]. + * + * For more info on failure codes, see . + */ +typedef enum LDKFailureCode { + /** + * We had a temporary error processing the payment. Useful if no other error codes fit + * and you want to indicate that the payer may want to retry. + */ + LDKFailureCode_TemporaryNodeFailure, + /** + * We have a required feature which was not in this onion. For example, you may require + * some additional metadata that was not provided with this payment. + */ + LDKFailureCode_RequiredNodeFeatureMissing, + /** + * You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of + * the HTLC is too close to the current block height for safe handling. + * Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is + * equivalent to calling [`ChannelManager::fail_htlc_backwards`]. + */ + LDKFailureCode_IncorrectOrUnknownPaymentDetails, + /** + * Must be last for serialization purposes + */ + LDKFailureCode_Sentinel, +} LDKFailureCode; + /** * Describes the type of HTLC claim as determined by analyzing the witness. */ @@ -342,7 +360,7 @@ typedef enum LDKNetwork { /** * Specifies the recipient of an invoice. * - * This indicates to [`KeysInterface::sign_invoice`] what node secret key should be used to sign + * This indicates to [`NodeSigner::sign_invoice`] what node secret key should be used to sign * the invoice. */ typedef enum LDKRecipient { @@ -363,6 +381,41 @@ typedef enum LDKRecipient { LDKRecipient_Sentinel, } LDKRecipient; +/** + * Indicates an immediate error on [`ChannelManager::send_payment_with_retry`]. Further errors + * may be surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`]. + * + * [`ChannelManager::send_payment_with_retry`]: crate::ln::channelmanager::ChannelManager::send_payment_with_retry + * [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed + * [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed + */ +typedef enum LDKRetryableSendFailure { + /** + * The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note + * that this error is *not* caused by [`Retry::Timeout`]. + * + * [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time + */ + LDKRetryableSendFailure_PaymentExpired, + /** + * We were unable to find a route to the destination. + */ + LDKRetryableSendFailure_RouteNotFound, + /** + * Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not + * yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]). + * + * [`PaymentId`]: crate::ln::channelmanager::PaymentId + * [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent + * [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed + */ + LDKRetryableSendFailure_DuplicatePayment, + /** + * Must be last for serialization purposes + */ + LDKRetryableSendFailure_Sentinel, +} LDKRetryableSendFailure; + /** * Represents an error returned from libsecp256k1 during validation of some secp256k1 data */ @@ -495,6 +548,24 @@ typedef enum LDKSiPrefix { LDKSiPrefix_Sentinel, } LDKSiPrefix; +/** + * An error when accessing the chain via [`UtxoLookup`]. + */ +typedef enum LDKUtxoLookupError { + /** + * The requested chain is unknown. + */ + LDKUtxoLookupError_UnknownChain, + /** + * The requested transaction doesn't exist or hasn't confirmed. + */ + LDKUtxoLookupError_UnknownTx, + /** + * Must be last for serialization purposes + */ + LDKUtxoLookupError_Sentinel, +} LDKUtxoLookupError; + /** * A Rust str object, ie a reference to a UTF8-valid string. * This is *not* null-terminated so cannot be used directly as a C string! @@ -691,6 +762,197 @@ typedef struct LDKTxOut { uint64_t value; } LDKTxOut; + + +/** + * A script pubkey for shutting down a channel as defined by [BOLT #2]. + * + * [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md + */ +typedef struct MUST_USE_STRUCT LDKShutdownScript { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeShutdownScript *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKShutdownScript; + +/** + * Indicates an error on the client's part (usually some variant of attempting to use too-low or + * too-high values) + */ +typedef enum LDKAPIError_Tag { + /** + * Indicates the API was wholly misused (see err for more). Cases where these can be returned + * are documented, but generally indicates some precondition of a function was violated. + */ + LDKAPIError_APIMisuseError, + /** + * Due to a high feerate, we were unable to complete the request. + * For example, this may be returned if the feerate implies we cannot open a channel at the + * requested value, but opening a larger channel would succeed. + */ + LDKAPIError_FeeRateTooHigh, + /** + * A malformed Route was provided (eg overflowed value, node id mismatch, overly-looped route, + * too-many-hops, etc). + */ + LDKAPIError_InvalidRoute, + /** + * We were unable to complete the request as the Channel required to do so is unable to + * complete the request (or was not found). This can take many forms, including disconnected + * peer, channel at capacity, channel shutting down, etc. + */ + LDKAPIError_ChannelUnavailable, + /** + * An attempt to call [`chain::Watch::watch_channel`]/[`chain::Watch::update_channel`] + * returned a [`ChannelMonitorUpdateStatus::InProgress`] indicating the persistence of a + * monitor update is awaiting async resolution. Once it resolves the attempted action should + * complete automatically. + * + * [`chain::Watch::watch_channel`]: crate::chain::Watch::watch_channel + * [`chain::Watch::update_channel`]: crate::chain::Watch::update_channel + * [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress + */ + LDKAPIError_MonitorUpdateInProgress, + /** + * [`SignerProvider::get_shutdown_scriptpubkey`] returned a shutdown scriptpubkey incompatible + * with the channel counterparty as negotiated in [`InitFeatures`]. + * + * Using a SegWit v0 script should resolve this issue. If you cannot, you won't be able to open + * a channel or cooperatively close one with this peer (and will have to force-close instead). + * + * [`SignerProvider::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::SignerProvider::get_shutdown_scriptpubkey + * [`InitFeatures`]: crate::ln::features::InitFeatures + */ + LDKAPIError_IncompatibleShutdownScript, + /** + * Must be last for serialization purposes + */ + LDKAPIError_Sentinel, +} LDKAPIError_Tag; + +typedef struct LDKAPIError_LDKAPIMisuseError_Body { + /** + * A human-readable error message + */ + struct LDKStr err; +} LDKAPIError_LDKAPIMisuseError_Body; + +typedef struct LDKAPIError_LDKFeeRateTooHigh_Body { + /** + * A human-readable error message + */ + struct LDKStr err; + /** + * The feerate which was too high. + */ + uint32_t feerate; +} LDKAPIError_LDKFeeRateTooHigh_Body; + +typedef struct LDKAPIError_LDKInvalidRoute_Body { + /** + * A human-readable error message + */ + struct LDKStr err; +} LDKAPIError_LDKInvalidRoute_Body; + +typedef struct LDKAPIError_LDKChannelUnavailable_Body { + /** + * A human-readable error message + */ + struct LDKStr err; +} LDKAPIError_LDKChannelUnavailable_Body; + +typedef struct LDKAPIError_LDKIncompatibleShutdownScript_Body { + /** + * The incompatible shutdown script. + */ + struct LDKShutdownScript script; +} LDKAPIError_LDKIncompatibleShutdownScript_Body; + +typedef struct MUST_USE_STRUCT LDKAPIError { + LDKAPIError_Tag tag; + union { + LDKAPIError_LDKAPIMisuseError_Body api_misuse_error; + LDKAPIError_LDKFeeRateTooHigh_Body fee_rate_too_high; + LDKAPIError_LDKInvalidRoute_Body invalid_route; + LDKAPIError_LDKChannelUnavailable_Body channel_unavailable; + LDKAPIError_LDKIncompatibleShutdownScript_Body incompatible_shutdown_script; + }; +} LDKAPIError; + +/** + * The contents of CResult_NoneAPIErrorZ + */ +typedef union LDKCResult_NoneAPIErrorZPtr { + /** + * Note that this value is always NULL, as there are no contents in the OK variant + */ + void *result; + /** + * A pointer to the contents in the error state. + * Reading from this pointer when `result_ok` is set is undefined. + */ + struct LDKAPIError *err; +} LDKCResult_NoneAPIErrorZPtr; + +/** + * A CResult_NoneAPIErrorZ represents the result of a fallible operation, + * containing a () on success and a crate::lightning::util::errors::APIError on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult_NoneAPIErrorZ { + /** + * The contents of this CResult_NoneAPIErrorZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. + */ + union LDKCResult_NoneAPIErrorZPtr contents; + /** + * Whether this CResult_NoneAPIErrorZ represents a success state. + */ + bool result_ok; +} LDKCResult_NoneAPIErrorZ; + +/** + * A dynamically-allocated array of crate::c_types::derived::CResult_NoneAPIErrorZs of arbitrary size. + * This corresponds to std::vector in C++ + */ +typedef struct LDKCVec_CResult_NoneAPIErrorZZ { + /** + * The elements in the array. + * If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). + */ + struct LDKCResult_NoneAPIErrorZ *data; + /** + * The number of elements pointed to by `data`. + */ + uintptr_t datalen; +} LDKCVec_CResult_NoneAPIErrorZZ; + +/** + * A dynamically-allocated array of crate::lightning::util::errors::APIErrors of arbitrary size. + * This corresponds to std::vector in C++ + */ +typedef struct LDKCVec_APIErrorZ { + /** + * The elements in the array. + * If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). + */ + struct LDKAPIError *data; + /** + * The number of elements pointed to by `data`. + */ + uintptr_t datalen; +} LDKCVec_APIErrorZ; + /** * An enum which can either contain a crate::lightning::ln::chan_utils::HTLCClaim or not */ @@ -779,29 +1041,32 @@ typedef struct MUST_USE_STRUCT LDKCounterpartyCommitmentSecrets { typedef enum LDKDecodeError_Tag { /** * A version byte specified something we don't know how to handle. - * Includes unknown realm byte in an OnionHopData packet + * + * Includes unknown realm byte in an onion hop data packet. */ LDKDecodeError_UnknownVersion, /** - * Unknown feature mandating we fail to parse message (eg TLV with an even, unknown type) + * Unknown feature mandating we fail to parse message (e.g., TLV with an even, unknown type) */ LDKDecodeError_UnknownRequiredFeature, /** - * Value was invalid, eg a byte which was supposed to be a bool was something other than a 0 + * Value was invalid. + * + * For example, a byte which was supposed to be a bool was something other than a 0 * or 1, a public key/private key/signature was invalid, text wasn't UTF-8, TLV was - * syntactically incorrect, etc + * syntactically incorrect, etc. */ LDKDecodeError_InvalidValue, /** - * Buffer too short + * The buffer to be read was too short. */ LDKDecodeError_ShortRead, /** - * A length descriptor in the packet didn't describe the later data correctly + * A length descriptor in the packet didn't describe the later data correctly. */ LDKDecodeError_BadLengthDescriptor, /** - * Error from std::io + * Error from [`std::io`]. */ LDKDecodeError_Io, /** @@ -1500,32 +1765,10 @@ typedef struct LDKCResult_CVec_SignatureZNoneZ { bool result_ok; } LDKCResult_CVec_SignatureZNoneZ; - - /** - * A script pubkey for shutting down a channel as defined by [BOLT #2]. - * - * [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md + * The contents of CResult_ShutdownScriptDecodeErrorZ */ -typedef struct MUST_USE_STRUCT LDKShutdownScript { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeShutdownScript *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKShutdownScript; - -/** - * The contents of CResult_ShutdownScriptDecodeErrorZ - */ -typedef union LDKCResult_ShutdownScriptDecodeErrorZPtr { +typedef union LDKCResult_ShutdownScriptDecodeErrorZPtr { /** * A pointer to the contents in the success state. * Reading from this pointer when `result_ok` is not set is undefined. @@ -2291,7 +2534,7 @@ typedef struct LDKCResult_RouteDecodeErrorZ { * Parameters needed to find a [`Route`]. * * Passed to [`find_route`] and [`build_route_from_hops`], but also provided in - * [`Event::PaymentPathFailed`] for retrying a failed payment path. + * [`Event::PaymentPathFailed`]. * * [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed */ @@ -2640,6 +2883,232 @@ typedef struct LDKCResult_PaymentPurposeDecodeErrorZ { bool result_ok; } LDKCResult_PaymentPurposeDecodeErrorZ; + + +/** + * A [`channel_update`] message to be sent to or received from a peer. + * + * [`channel_update`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message + */ +typedef struct MUST_USE_STRUCT LDKChannelUpdate { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeChannelUpdate *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKChannelUpdate; + +/** + * Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion + * return packet by a node along the route. See [BOLT #4] for details. + * + * [BOLT #4]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md + */ +typedef enum LDKNetworkUpdate_Tag { + /** + * An error indicating a `channel_update` messages should be applied via + * [`NetworkGraph::update_channel`]. + */ + LDKNetworkUpdate_ChannelUpdateMessage, + /** + * An error indicating that a channel failed to route a payment, which should be applied via + * [`NetworkGraph::channel_failed`]. + */ + LDKNetworkUpdate_ChannelFailure, + /** + * An error indicating that a node failed to route a payment, which should be applied via + * [`NetworkGraph::node_failed_permanent`] if permanent. + */ + LDKNetworkUpdate_NodeFailure, + /** + * Must be last for serialization purposes + */ + LDKNetworkUpdate_Sentinel, +} LDKNetworkUpdate_Tag; + +typedef struct LDKNetworkUpdate_LDKChannelUpdateMessage_Body { + /** + * The update to apply via [`NetworkGraph::update_channel`]. + */ + struct LDKChannelUpdate msg; +} LDKNetworkUpdate_LDKChannelUpdateMessage_Body; + +typedef struct LDKNetworkUpdate_LDKChannelFailure_Body { + /** + * The short channel id of the closed channel. + */ + uint64_t short_channel_id; + /** + * Whether the channel should be permanently removed or temporarily disabled until a new + * `channel_update` message is received. + */ + bool is_permanent; +} LDKNetworkUpdate_LDKChannelFailure_Body; + +typedef struct LDKNetworkUpdate_LDKNodeFailure_Body { + /** + * The node id of the failed node. + */ + struct LDKPublicKey node_id; + /** + * Whether the node should be permanently removed from consideration or can be restored + * when a new `channel_update` message is received. + */ + bool is_permanent; +} LDKNetworkUpdate_LDKNodeFailure_Body; + +typedef struct MUST_USE_STRUCT LDKNetworkUpdate { + LDKNetworkUpdate_Tag tag; + union { + LDKNetworkUpdate_LDKChannelUpdateMessage_Body channel_update_message; + LDKNetworkUpdate_LDKChannelFailure_Body channel_failure; + LDKNetworkUpdate_LDKNodeFailure_Body node_failure; + }; +} LDKNetworkUpdate; + +/** + * An enum which can either contain a crate::lightning::routing::gossip::NetworkUpdate or not + */ +typedef enum LDKCOption_NetworkUpdateZ_Tag { + /** + * When we're in this state, this COption_NetworkUpdateZ contains a crate::lightning::routing::gossip::NetworkUpdate + */ + LDKCOption_NetworkUpdateZ_Some, + /** + * When we're in this state, this COption_NetworkUpdateZ contains nothing + */ + LDKCOption_NetworkUpdateZ_None, + /** + * Must be last for serialization purposes + */ + LDKCOption_NetworkUpdateZ_Sentinel, +} LDKCOption_NetworkUpdateZ_Tag; + +typedef struct LDKCOption_NetworkUpdateZ { + LDKCOption_NetworkUpdateZ_Tag tag; + union { + struct { + struct LDKNetworkUpdate some; + }; + }; +} LDKCOption_NetworkUpdateZ; + +/** + * When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may + * contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`]. + * + * [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate + * [`NetworkGraph`]: crate::routing::gossip::NetworkGraph + */ +typedef enum LDKPathFailure_Tag { + /** + * We failed to initially send the payment and no HTLC was committed to. Contains the relevant + * error. + */ + LDKPathFailure_InitialSend, + /** + * A hop on the path failed to forward our payment. + */ + LDKPathFailure_OnPath, + /** + * Must be last for serialization purposes + */ + LDKPathFailure_Sentinel, +} LDKPathFailure_Tag; + +typedef struct LDKPathFailure_LDKInitialSend_Body { + /** + * The error surfaced from initial send. + */ + struct LDKAPIError err; +} LDKPathFailure_LDKInitialSend_Body; + +typedef struct LDKPathFailure_LDKOnPath_Body { + /** + * If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing + * decisions can take into account the update. + * + * [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate + * [`NetworkGraph`]: crate::routing::gossip::NetworkGraph + */ + struct LDKCOption_NetworkUpdateZ network_update; +} LDKPathFailure_LDKOnPath_Body; + +typedef struct MUST_USE_STRUCT LDKPathFailure { + LDKPathFailure_Tag tag; + union { + LDKPathFailure_LDKInitialSend_Body initial_send; + LDKPathFailure_LDKOnPath_Body on_path; + }; +} LDKPathFailure; + +/** + * An enum which can either contain a crate::lightning::util::events::PathFailure or not + */ +typedef enum LDKCOption_PathFailureZ_Tag { + /** + * When we're in this state, this COption_PathFailureZ contains a crate::lightning::util::events::PathFailure + */ + LDKCOption_PathFailureZ_Some, + /** + * When we're in this state, this COption_PathFailureZ contains nothing + */ + LDKCOption_PathFailureZ_None, + /** + * Must be last for serialization purposes + */ + LDKCOption_PathFailureZ_Sentinel, +} LDKCOption_PathFailureZ_Tag; + +typedef struct LDKCOption_PathFailureZ { + LDKCOption_PathFailureZ_Tag tag; + union { + struct { + struct LDKPathFailure some; + }; + }; +} LDKCOption_PathFailureZ; + +/** + * The contents of CResult_COption_PathFailureZDecodeErrorZ + */ +typedef union LDKCResult_COption_PathFailureZDecodeErrorZPtr { + /** + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. + */ + struct LDKCOption_PathFailureZ *result; + /** + * A pointer to the contents in the error state. + * Reading from this pointer when `result_ok` is set is undefined. + */ + struct LDKDecodeError *err; +} LDKCResult_COption_PathFailureZDecodeErrorZPtr; + +/** + * A CResult_COption_PathFailureZDecodeErrorZ represents the result of a fallible operation, + * containing a crate::c_types::derived::COption_PathFailureZ on success and a crate::lightning::ln::msgs::DecodeError on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult_COption_PathFailureZDecodeErrorZ { + /** + * The contents of this CResult_COption_PathFailureZDecodeErrorZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. + */ + union LDKCResult_COption_PathFailureZDecodeErrorZPtr contents; + /** + * Whether this CResult_COption_PathFailureZDecodeErrorZ represents a success state. + */ + bool result_ok; +} LDKCResult_COption_PathFailureZDecodeErrorZ; + /** * The reason the channel was closed. See individual variants more details. */ @@ -2959,184 +3428,69 @@ typedef struct LDKCOption_u128Z { /** - * A channel_update message to be sent or received from a peer + * A reference to a transaction output. + * + * Differs from bitcoin::blockdata::transaction::OutPoint as the index is a u16 instead of u32 + * due to LN's restrictions on index values. Should reduce (possibly) unsafe conversions this way. */ -typedef struct MUST_USE_STRUCT LDKChannelUpdate { +typedef struct MUST_USE_STRUCT LDKOutPoint { /** * A pointer to the opaque Rust object. * Nearly everywhere, inner must be non-null, however in places where * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKnativeChannelUpdate *inner; + LDKnativeOutPoint *inner; /** * Indicates that this is the only struct which contains the same pointer. * Rust functions which take ownership of an object provided via an argument require * this to be true and invalidate the object pointed to by inner. */ bool is_owned; -} LDKChannelUpdate; +} LDKOutPoint; + + /** - * Update to the [`NetworkGraph`] based on payment failure information conveyed via the Onion - * return packet by a node along the route. See [BOLT #4] for details. + * Information about a spendable output to a P2WSH script. * - * [BOLT #4]: https://github.com/lightning/bolts/blob/master/04-onion-routing.md + * See [`SpendableOutputDescriptor::DelayedPaymentOutput`] for more details on how to spend this. */ -typedef enum LDKNetworkUpdate_Tag { +typedef struct MUST_USE_STRUCT LDKDelayedPaymentOutputDescriptor { /** - * An error indicating a `channel_update` messages should be applied via - * [`NetworkGraph::update_channel`]. + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKNetworkUpdate_ChannelUpdateMessage, + LDKnativeDelayedPaymentOutputDescriptor *inner; /** - * An error indicating that a channel failed to route a payment, which should be applied via - * [`NetworkGraph::channel_failed`]. + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. */ - LDKNetworkUpdate_ChannelFailure, + bool is_owned; +} LDKDelayedPaymentOutputDescriptor; + + + +/** + * Information about a spendable output to our \"payment key\". + * + * See [`SpendableOutputDescriptor::StaticPaymentOutput`] for more details on how to spend this. + */ +typedef struct MUST_USE_STRUCT LDKStaticPaymentOutputDescriptor { /** - * An error indicating that a node failed to route a payment, which should be applied via - * [`NetworkGraph::node_failed_permanent`] if permanent. + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKNetworkUpdate_NodeFailure, + LDKnativeStaticPaymentOutputDescriptor *inner; /** - * Must be last for serialization purposes + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. */ - LDKNetworkUpdate_Sentinel, -} LDKNetworkUpdate_Tag; - -typedef struct LDKNetworkUpdate_LDKChannelUpdateMessage_Body { - /** - * The update to apply via [`NetworkGraph::update_channel`]. - */ - struct LDKChannelUpdate msg; -} LDKNetworkUpdate_LDKChannelUpdateMessage_Body; - -typedef struct LDKNetworkUpdate_LDKChannelFailure_Body { - /** - * The short channel id of the closed channel. - */ - uint64_t short_channel_id; - /** - * Whether the channel should be permanently removed or temporarily disabled until a new - * `channel_update` message is received. - */ - bool is_permanent; -} LDKNetworkUpdate_LDKChannelFailure_Body; - -typedef struct LDKNetworkUpdate_LDKNodeFailure_Body { - /** - * The node id of the failed node. - */ - struct LDKPublicKey node_id; - /** - * Whether the node should be permanently removed from consideration or can be restored - * when a new `channel_update` message is received. - */ - bool is_permanent; -} LDKNetworkUpdate_LDKNodeFailure_Body; - -typedef struct MUST_USE_STRUCT LDKNetworkUpdate { - LDKNetworkUpdate_Tag tag; - union { - LDKNetworkUpdate_LDKChannelUpdateMessage_Body channel_update_message; - LDKNetworkUpdate_LDKChannelFailure_Body channel_failure; - LDKNetworkUpdate_LDKNodeFailure_Body node_failure; - }; -} LDKNetworkUpdate; - -/** - * An enum which can either contain a crate::lightning::routing::gossip::NetworkUpdate or not - */ -typedef enum LDKCOption_NetworkUpdateZ_Tag { - /** - * When we're in this state, this COption_NetworkUpdateZ contains a crate::lightning::routing::gossip::NetworkUpdate - */ - LDKCOption_NetworkUpdateZ_Some, - /** - * When we're in this state, this COption_NetworkUpdateZ contains nothing - */ - LDKCOption_NetworkUpdateZ_None, - /** - * Must be last for serialization purposes - */ - LDKCOption_NetworkUpdateZ_Sentinel, -} LDKCOption_NetworkUpdateZ_Tag; - -typedef struct LDKCOption_NetworkUpdateZ { - LDKCOption_NetworkUpdateZ_Tag tag; - union { - struct { - struct LDKNetworkUpdate some; - }; - }; -} LDKCOption_NetworkUpdateZ; - - - -/** - * A reference to a transaction output. - * - * Differs from bitcoin::blockdata::transaction::OutPoint as the index is a u16 instead of u32 - * due to LN's restrictions on index values. Should reduce (possibly) unsafe conversions this way. - */ -typedef struct MUST_USE_STRUCT LDKOutPoint { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeOutPoint *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKOutPoint; - - - -/** - * Information about a spendable output to a P2WSH script. - * - * See [`SpendableOutputDescriptor::DelayedPaymentOutput`] for more details on how to spend this. - */ -typedef struct MUST_USE_STRUCT LDKDelayedPaymentOutputDescriptor { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeDelayedPaymentOutputDescriptor *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKDelayedPaymentOutputDescriptor; - - - -/** - * Information about a spendable output to our \"payment key\". - * - * See [`SpendableOutputDescriptor::StaticPaymentOutput`] for more details on how to spend this. - */ -typedef struct MUST_USE_STRUCT LDKStaticPaymentOutputDescriptor { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeStaticPaymentOutputDescriptor *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKStaticPaymentOutputDescriptor; + bool is_owned; +} LDKStaticPaymentOutputDescriptor; /** * Describes the necessary information to spend a spendable output. @@ -3151,14 +3505,14 @@ typedef struct MUST_USE_STRUCT LDKStaticPaymentOutputDescriptor { */ typedef enum LDKSpendableOutputDescriptor_Tag { /** - * An output to a script which was provided via [`KeysInterface`] directly, either from + * An output to a script which was provided via [`SignerProvider`] directly, either from * [`get_destination_script`] or [`get_shutdown_scriptpubkey`], thus you should already * know how to spend it. No secret keys are provided as LDK was never given any key. * These may include outputs from a transaction punishing our counterparty or claiming an HTLC * on-chain using the payment preimage or after it has timed out. * - * [`get_shutdown_scriptpubkey`]: KeysInterface::get_shutdown_scriptpubkey - * [`get_destination_script`]: KeysInterface::get_shutdown_scriptpubkey + * [`get_shutdown_scriptpubkey`]: SignerProvider::get_shutdown_scriptpubkey + * [`get_destination_script`]: SignerProvider::get_shutdown_scriptpubkey */ LDKSpendableOutputDescriptor_StaticOutput, /** @@ -3183,15 +3537,15 @@ typedef enum LDKSpendableOutputDescriptor_Tag { * * To derive the delayed payment key which is used to sign this input, you must pass the * holder [`InMemorySigner::delayed_payment_base_key`] (i.e., the private key which corresponds to the - * [`ChannelPublicKeys::delayed_payment_basepoint`] in [`BaseSign::pubkeys`]) and the provided + * [`ChannelPublicKeys::delayed_payment_basepoint`] in [`ChannelSigner::pubkeys`]) and the provided * [`DelayedPaymentOutputDescriptor::per_commitment_point`] to [`chan_utils::derive_private_key`]. The public key can be * generated without the secret key using [`chan_utils::derive_public_key`] and only the - * [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in [`BaseSign::pubkeys`]. + * [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in [`ChannelSigner::pubkeys`]. * * To derive the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] provided here (which is * used in the witness script generation), you must pass the counterparty * [`ChannelPublicKeys::revocation_basepoint`] (which appears in the call to - * [`BaseSign::provide_channel_parameters`]) and the provided + * [`ChannelSigner::provide_channel_parameters`]) and the provided * [`DelayedPaymentOutputDescriptor::per_commitment_point`] to * [`chan_utils::derive_public_revocation_key`]. * @@ -3204,7 +3558,7 @@ typedef enum LDKSpendableOutputDescriptor_Tag { LDKSpendableOutputDescriptor_DelayedPaymentOutput, /** * An output to a P2WPKH, spendable exclusively by our payment key (i.e., the private key - * which corresponds to the `payment_point` in [`BaseSign::pubkeys`]). The witness + * which corresponds to the `payment_point` in [`ChannelSigner::pubkeys`]). The witness * in the spending input is, thus, simply: * ```bitcoin * @@ -3313,10 +3667,10 @@ typedef enum LDKEvent_Tag { * [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`]. * * Note that if the preimage is not known, you should call - * [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid - * network congestion. - * If you fail to call either [`ChannelManager::claim_funds`] or - * [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be + * [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`] + * to free up resources for this HTLC and avoid network congestion. + * If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`], + * or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be * automatically failed. * * # Note @@ -3328,6 +3682,7 @@ typedef enum LDKEvent_Tag { * * [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds * [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards + * [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason */ LDKEvent_PaymentClaimable, /** @@ -3357,12 +3712,13 @@ typedef enum LDKEvent_Tag { LDKEvent_PaymentSent, /** * Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events - * provide failure information for each MPP part in the payment. + * provide failure information for each path attempt in the payment, including retries. * * This event is provided once there are no further pending HTLCs for the payment and the - * payment is no longer retryable due to [`ChannelManager::abandon_payment`] having been - * called for the corresponding payment. + * payment is no longer retryable, due either to the [`Retry`] provided or + * [`ChannelManager::abandon_payment`] having been called for the corresponding payment. * + * [`Retry`]: crate::ln::channelmanager::Retry * [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment */ LDKEvent_PaymentFailed, @@ -3374,18 +3730,16 @@ typedef enum LDKEvent_Tag { */ LDKEvent_PaymentPathSuccessful, /** - * Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped - * something. You may wish to retry with a different route. - * - * If you have given up retrying this payment and wish to fail it, you MUST call - * [`ChannelManager::abandon_payment`] at least once for a given [`PaymentId`] or memory - * related to payment tracking will leak. + * Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to + * handle the HTLC. * * Note that this does *not* indicate that all paths for an MPP payment have failed, see - * [`Event::PaymentFailed`] and [`all_paths_failed`]. + * [`Event::PaymentFailed`]. + * + * See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have + * been exhausted. * * [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment - * [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed */ LDKEvent_PaymentPathFailed, /** @@ -3584,11 +3938,9 @@ typedef struct LDKEvent_LDKPaymentClaimed_Body { typedef struct LDKEvent_LDKPaymentSent_Body { /** - * The id returned by [`ChannelManager::send_payment`] and used with - * [`ChannelManager::retry_payment`]. + * The id returned by [`ChannelManager::send_payment`]. * * [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment - * [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment * * Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None */ @@ -3622,10 +3974,9 @@ typedef struct LDKEvent_LDKPaymentSent_Body { typedef struct LDKEvent_LDKPaymentFailed_Body { /** * The id returned by [`ChannelManager::send_payment`] and used with - * [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`]. + * [`ChannelManager::abandon_payment`]. * * [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment - * [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment * [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment */ struct LDKThirtyTwoBytes payment_id; @@ -3639,11 +3990,9 @@ typedef struct LDKEvent_LDKPaymentFailed_Body { typedef struct LDKEvent_LDKPaymentPathSuccessful_Body { /** - * The id returned by [`ChannelManager::send_payment`] and used with - * [`ChannelManager::retry_payment`]. + * The id returned by [`ChannelManager::send_payment`]. * * [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment - * [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment */ struct LDKThirtyTwoBytes payment_id; /** @@ -3665,10 +4014,9 @@ typedef struct LDKEvent_LDKPaymentPathSuccessful_Body { typedef struct LDKEvent_LDKPaymentPathFailed_Body { /** * The id returned by [`ChannelManager::send_payment`] and used with - * [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`]. + * [`ChannelManager::abandon_payment`]. * * [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment - * [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment * [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment * * Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None @@ -3682,40 +4030,17 @@ typedef struct LDKEvent_LDKPaymentPathFailed_Body { struct LDKThirtyTwoBytes payment_hash; /** * Indicates the payment was rejected for some reason by the recipient. This implies that - * the payment has failed, not just the route in question. If this is not set, you may - * retry the payment via a different route. + * the payment has failed, not just the route in question. If this is not set, the payment may + * be retried via a different route. */ bool payment_failed_permanently; /** - * Any failure information conveyed via the Onion return packet by a node along the failed - * payment route. - * - * Should be applied to the [`NetworkGraph`] so that routing decisions can take into - * account the update. + * Extra error details based on the failure type. May contain an update that needs to be + * applied to the [`NetworkGraph`]. * * [`NetworkGraph`]: crate::routing::gossip::NetworkGraph */ - struct LDKCOption_NetworkUpdateZ network_update; - /** - * For both single-path and multi-path payments, this is set if all paths of the payment have - * failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the - * larger MPP payment were still in flight when this event was generated. - * - * Note that if you are retrying individual MPP parts, using this value to determine if a - * payment has fully failed is race-y. Because multiple failures can happen prior to events - * being processed, you may retry in response to a first failure, with a second failure - * (with `all_paths_failed` set) still pending. Then, when the second failure is processed - * you will see `all_paths_failed` set even though the retry of the first failure still - * has an associated in-flight HTLC. See (1) for an example of such a failure. - * - * If you wish to retry individual MPP parts and learn when a payment has failed, you must - * call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event. - * - * (1) - * - * [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment - */ - bool all_paths_failed; + struct LDKPathFailure failure; /** * The payment path that failed. */ @@ -3732,12 +4057,9 @@ typedef struct LDKEvent_LDKPaymentPathFailed_Body { */ struct LDKCOption_u64Z short_channel_id; /** - * Parameters needed to compute a new [`Route`] when retrying the failed payment path. - * - * See [`find_route`] for details. + * Parameters used by LDK to compute a new [`Route`] when retrying the failed payment path. * * [`Route`]: crate::routing::router::Route - * [`find_route`]: crate::routing::router::find_route * * Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None */ @@ -4088,7 +4410,9 @@ typedef struct LDKCResult_COption_EventZDecodeErrorZ { /** - * An accept_channel message to be sent or received from a peer + * An [`accept_channel`] message to be sent to or received from a peer. + * + * [`accept_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-accept_channel-message */ typedef struct MUST_USE_STRUCT LDKAcceptChannel { /** @@ -4108,7 +4432,9 @@ typedef struct MUST_USE_STRUCT LDKAcceptChannel { /** - * An open_channel message to be sent or received from a peer + * An [`open_channel`] message to be sent to or received from a peer. + * + * [`open_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-open_channel-message */ typedef struct MUST_USE_STRUCT LDKOpenChannel { /** @@ -4128,7 +4454,9 @@ typedef struct MUST_USE_STRUCT LDKOpenChannel { /** - * A funding_created message to be sent or received from a peer + * A [`funding_created`] message to be sent to or received from a peer. + * + * [`funding_created`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-funding_created-message */ typedef struct MUST_USE_STRUCT LDKFundingCreated { /** @@ -4148,7 +4476,9 @@ typedef struct MUST_USE_STRUCT LDKFundingCreated { /** - * A funding_signed message to be sent or received from a peer + * A [`funding_signed`] message to be sent to or received from a peer. + * + * [`funding_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-funding_signed-message */ typedef struct MUST_USE_STRUCT LDKFundingSigned { /** @@ -4168,7 +4498,9 @@ typedef struct MUST_USE_STRUCT LDKFundingSigned { /** - * A channel_ready message to be sent or received from a peer + * A [`channel_ready`] message to be sent to or received from a peer. + * + * [`channel_ready`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-channel_ready-message */ typedef struct MUST_USE_STRUCT LDKChannelReady { /** @@ -4188,7 +4520,9 @@ typedef struct MUST_USE_STRUCT LDKChannelReady { /** - * An announcement_signatures message to be sent or received from a peer + * An [`announcement_signatures`] message to be sent to or received from a peer. + * + * [`announcement_signatures`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-announcement_signatures-message */ typedef struct MUST_USE_STRUCT LDKAnnouncementSignatures { /** @@ -4208,7 +4542,7 @@ typedef struct MUST_USE_STRUCT LDKAnnouncementSignatures { /** - * Struct used to return values from revoke_and_ack messages, containing a bunch of commitment + * Struct used to return values from [`RevokeAndACK`] messages, containing a bunch of commitment * transaction updates if they were pending. */ typedef struct MUST_USE_STRUCT LDKCommitmentUpdate { @@ -4229,7 +4563,9 @@ typedef struct MUST_USE_STRUCT LDKCommitmentUpdate { /** - * A revoke_and_ack message to be sent or received from a peer + * A [`revoke_and_ack`] message to be sent to or received from a peer. + * + * [`revoke_and_ack`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#completing-the-transition-to-the-updated-state-revoke_and_ack */ typedef struct MUST_USE_STRUCT LDKRevokeAndACK { /** @@ -4249,7 +4585,9 @@ typedef struct MUST_USE_STRUCT LDKRevokeAndACK { /** - * A closing_signed message to be sent or received from a peer + * A [`closing_signed`] message to be sent to or received from a peer. + * + * [`closing_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-negotiation-closing_signed */ typedef struct MUST_USE_STRUCT LDKClosingSigned { /** @@ -4269,7 +4607,9 @@ typedef struct MUST_USE_STRUCT LDKClosingSigned { /** - * A shutdown message to be sent or received from a peer + * A [`shutdown`] message to be sent to or received from a peer. + * + * [`shutdown`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-initiation-shutdown */ typedef struct MUST_USE_STRUCT LDKShutdown { /** @@ -4289,7 +4629,9 @@ typedef struct MUST_USE_STRUCT LDKShutdown { /** - * A channel_reestablish message to be sent or received from a peer + * A [`channel_reestablish`] message to be sent to or received from a peer. + * + * [`channel_reestablish`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#message-retransmission */ typedef struct MUST_USE_STRUCT LDKChannelReestablish { /** @@ -4309,7 +4651,9 @@ typedef struct MUST_USE_STRUCT LDKChannelReestablish { /** - * A channel_announcement message to be sent or received from a peer + * A [`channel_announcement`] message to be sent to or received from a peer. + * + * [`channel_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message */ typedef struct MUST_USE_STRUCT LDKChannelAnnouncement { /** @@ -4329,7 +4673,31 @@ typedef struct MUST_USE_STRUCT LDKChannelAnnouncement { /** - * An error message to be sent or received from a peer + * A [`node_announcement`] message to be sent to or received from a peer. + * + * [`node_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message + */ +typedef struct MUST_USE_STRUCT LDKNodeAnnouncement { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeNodeAnnouncement *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKNodeAnnouncement; + + + +/** + * An [`error`] message to be sent to or received from a peer. + * + * [`error`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-error-and-warning-messages */ typedef struct MUST_USE_STRUCT LDKErrorMessage { /** @@ -4349,7 +4717,9 @@ typedef struct MUST_USE_STRUCT LDKErrorMessage { /** - * A warning message to be sent or received from a peer + * A [`warning`] message to be sent to or received from a peer. + * + * [`warning`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-error-and-warning-messages */ typedef struct MUST_USE_STRUCT LDKWarningMessage { /** @@ -4367,7 +4737,7 @@ typedef struct MUST_USE_STRUCT LDKWarningMessage { } LDKWarningMessage; /** - * Used to put an error message in a LightningError + * Used to put an error message in a [`LightningError`]. */ typedef enum LDKErrorAction_Tag { /** @@ -4447,10 +4817,12 @@ typedef struct MUST_USE_STRUCT LDKErrorAction { /** - * A query_channel_range message is used to query a peer for channel + * A [`query_channel_range`] message is used to query a peer for channel * UTXOs in a range of blocks. The recipient of a query makes a best - * effort to reply to the query using one or more reply_channel_range + * effort to reply to the query using one or more [`ReplyChannelRange`] * messages. + * + * [`query_channel_range`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_channel_range-and-reply_channel_range-messages */ typedef struct MUST_USE_STRUCT LDKQueryChannelRange { /** @@ -4470,14 +4842,17 @@ typedef struct MUST_USE_STRUCT LDKQueryChannelRange { /** - * A query_short_channel_ids message is used to query a peer for - * routing gossip messages related to one or more short_channel_ids. + * A [`query_short_channel_ids`] message is used to query a peer for + * routing gossip messages related to one or more `short_channel_id`s. + * * The query recipient will reply with the latest, if available, - * channel_announcement, channel_update and node_announcement messages - * it maintains for the requested short_channel_ids followed by a - * reply_short_channel_ids_end message. The short_channel_ids sent in - * this query are encoded. We only support encoding_type=0 uncompressed - * serialization and do not support encoding_type=1 zlib serialization. + * [`ChannelAnnouncement`], [`ChannelUpdate`] and [`NodeAnnouncement`] messages + * it maintains for the requested `short_channel_id`s followed by a + * [`ReplyShortChannelIdsEnd`] message. The `short_channel_id`s sent in + * this query are encoded. We only support `encoding_type=0` uncompressed + * serialization and do not support `encoding_type=1` zlib serialization. + * + * [`query_short_channel_ids`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_short_channel_idsreply_short_channel_ids_end-messages */ typedef struct MUST_USE_STRUCT LDKQueryShortChannelIds { /** @@ -4497,13 +4872,17 @@ typedef struct MUST_USE_STRUCT LDKQueryShortChannelIds { /** - * A reply_channel_range message is a reply to a query_channel_range - * message. Multiple reply_channel_range messages can be sent in reply - * to a single query_channel_range message. The query recipient makes a + * A [`reply_channel_range`] message is a reply to a [`QueryChannelRange`] + * message. + * + * Multiple `reply_channel_range` messages can be sent in reply + * to a single [`QueryChannelRange`] message. The query recipient makes a * best effort to respond based on their local network view which may - * not be a perfect view of the network. The short_channel_ids in the - * reply are encoded. We only support encoding_type=0 uncompressed - * serialization and do not support encoding_type=1 zlib serialization. + * not be a perfect view of the network. The `short_channel_id`s in the + * reply are encoded. We only support `encoding_type=0` uncompressed + * serialization and do not support `encoding_type=1` zlib serialization. + * + * [`reply_channel_range`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_channel_range-and-reply_channel_range-messages */ typedef struct MUST_USE_STRUCT LDKReplyChannelRange { /** @@ -4523,9 +4902,11 @@ typedef struct MUST_USE_STRUCT LDKReplyChannelRange { /** - * A gossip_timestamp_filter message is used by a node to request + * A [`gossip_timestamp_filter`] message is used by a node to request * gossip relay for messages in the requested time range when the - * gossip_queries feature has been negotiated. + * `gossip_queries` feature has been negotiated. + * + * [`gossip_timestamp_filter`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-gossip_timestamp_filter-message */ typedef struct MUST_USE_STRUCT LDKGossipTimestampFilter { /** @@ -4617,6 +4998,10 @@ typedef enum LDKMessageSendEvent_Tag { * Used to indicate that a channel_update should be broadcast to all peers. */ LDKMessageSendEvent_BroadcastChannelUpdate, + /** + * Used to indicate that a node_announcement should be broadcast to all peers. + */ + LDKMessageSendEvent_BroadcastNodeAnnouncement, /** * Used to indicate that a channel_update should be sent to a single peer. * In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a @@ -4795,6 +5180,8 @@ typedef struct LDKMessageSendEvent_LDKBroadcastChannelAnnouncement_Body { struct LDKChannelAnnouncement msg; /** * The followup channel_update which should be sent. + * + * Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None */ struct LDKChannelUpdate update_msg; } LDKMessageSendEvent_LDKBroadcastChannelAnnouncement_Body; @@ -4806,6 +5193,13 @@ typedef struct LDKMessageSendEvent_LDKBroadcastChannelUpdate_Body { struct LDKChannelUpdate msg; } LDKMessageSendEvent_LDKBroadcastChannelUpdate_Body; +typedef struct LDKMessageSendEvent_LDKBroadcastNodeAnnouncement_Body { + /** + * The node_announcement which should be sent. + */ + struct LDKNodeAnnouncement msg; +} LDKMessageSendEvent_LDKBroadcastNodeAnnouncement_Body; + typedef struct LDKMessageSendEvent_LDKSendChannelUpdate_Body { /** * The node_id of the node which should receive this message @@ -4889,6 +5283,7 @@ typedef struct MUST_USE_STRUCT LDKMessageSendEvent { LDKMessageSendEvent_LDKSendChannelAnnouncement_Body send_channel_announcement; LDKMessageSendEvent_LDKBroadcastChannelAnnouncement_Body broadcast_channel_announcement; LDKMessageSendEvent_LDKBroadcastChannelUpdate_Body broadcast_channel_update; + LDKMessageSendEvent_LDKBroadcastNodeAnnouncement_Body broadcast_node_announcement; LDKMessageSendEvent_LDKSendChannelUpdate_Body send_channel_update; LDKMessageSendEvent_LDKHandleError_Body handle_error; LDKMessageSendEvent_LDKSendChannelRangeQuery_Body send_channel_range_query; @@ -4914,39 +5309,6 @@ typedef struct LDKCVec_MessageSendEventZ { uintptr_t datalen; } LDKCVec_MessageSendEventZ; -/** - * The contents of CResult_TxOutAccessErrorZ - */ -typedef union LDKCResult_TxOutAccessErrorZPtr { - /** - * A pointer to the contents in the success state. - * Reading from this pointer when `result_ok` is not set is undefined. - */ - struct LDKTxOut *result; - /** - * A pointer to the contents in the error state. - * Reading from this pointer when `result_ok` is set is undefined. - */ - enum LDKAccessError *err; -} LDKCResult_TxOutAccessErrorZPtr; - -/** - * A CResult_TxOutAccessErrorZ represents the result of a fallible operation, - * containing a crate::c_types::TxOut on success and a crate::lightning::chain::AccessError on failure. - * `result_ok` indicates the overall state, and the contents are provided via `contents`. - */ -typedef struct LDKCResult_TxOutAccessErrorZ { - /** - * The contents of this CResult_TxOutAccessErrorZ, accessible via either - * `err` or `result` depending on the state of `result_ok`. - */ - union LDKCResult_TxOutAccessErrorZPtr contents; - /** - * Whether this CResult_TxOutAccessErrorZ represents a success state. - */ - bool result_ok; -} LDKCResult_TxOutAccessErrorZ; - /** * A tuple of 2 elements. See the individual fields for the types contained. */ @@ -5236,6 +5598,71 @@ typedef struct LDKCOption_C2Tuple_u64u64ZZ { }; } LDKCOption_C2Tuple_u64u64ZZ; +/** + * 8 u16s + */ +typedef struct LDKEightU16s { + /** + * The eight 16-bit integers + */ + uint16_t data[8]; +} LDKEightU16s; + +/** + * A tuple of 2 elements. See the individual fields for the types contained. + */ +typedef struct LDKC2Tuple_Z { + /** + * The element at position 0 + */ + struct LDKEightU16s a; + /** + * The element at position 1 + */ + struct LDKEightU16s b; +} LDKC2Tuple_Z; + +/** + * A tuple of 2 elements. See the individual fields for the types contained. + */ +typedef struct LDKC2Tuple__u168_u168Z { + /** + * The element at position 0 + */ + struct LDKEightU16s a; + /** + * The element at position 1 + */ + struct LDKEightU16s b; +} LDKC2Tuple__u168_u168Z; + +/** + * An enum which can either contain a crate::c_types::derived::C2Tuple__u168_u168Z or not + */ +typedef enum LDKCOption_C2Tuple_EightU16sEightU16sZZ_Tag { + /** + * When we're in this state, this COption_C2Tuple_EightU16sEightU16sZZ contains a crate::c_types::derived::C2Tuple__u168_u168Z + */ + LDKCOption_C2Tuple_EightU16sEightU16sZZ_Some, + /** + * When we're in this state, this COption_C2Tuple_EightU16sEightU16sZZ contains nothing + */ + LDKCOption_C2Tuple_EightU16sEightU16sZZ_None, + /** + * Must be last for serialization purposes + */ + LDKCOption_C2Tuple_EightU16sEightU16sZZ_Sentinel, +} LDKCOption_C2Tuple_EightU16sEightU16sZZ_Tag; + +typedef struct LDKCOption_C2Tuple_EightU16sEightU16sZZ { + LDKCOption_C2Tuple_EightU16sEightU16sZZ_Tag tag; + union { + struct { + struct LDKC2Tuple__u168_u168Z some; + }; + }; +} LDKCOption_C2Tuple_EightU16sEightU16sZZ; + /** * A dynamically-allocated array of crate::lightning::routing::gossip::NodeIds of arbitrary size. * This corresponds to std::vector in C++ @@ -5613,144 +6040,91 @@ typedef struct LDKCResult_InvoiceFeaturesDecodeErrorZ { bool result_ok; } LDKCResult_InvoiceFeaturesDecodeErrorZ; + + /** - * The contents of CResult_ChannelTypeFeaturesDecodeErrorZ + * Features used within BOLT 4 encrypted_data_tlv and BOLT 12 blinded_payinfo */ -typedef union LDKCResult_ChannelTypeFeaturesDecodeErrorZPtr { - /** - * A pointer to the contents in the success state. - * Reading from this pointer when `result_ok` is not set is undefined. - */ - struct LDKChannelTypeFeatures *result; - /** - * A pointer to the contents in the error state. - * Reading from this pointer when `result_ok` is set is undefined. - */ - struct LDKDecodeError *err; -} LDKCResult_ChannelTypeFeaturesDecodeErrorZPtr; - -/** - * A CResult_ChannelTypeFeaturesDecodeErrorZ represents the result of a fallible operation, - * containing a crate::lightning::ln::features::ChannelTypeFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. - * `result_ok` indicates the overall state, and the contents are provided via `contents`. - */ -typedef struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ { - /** - * The contents of this CResult_ChannelTypeFeaturesDecodeErrorZ, accessible via either - * `err` or `result` depending on the state of `result_ok`. - */ - union LDKCResult_ChannelTypeFeaturesDecodeErrorZPtr contents; - /** - * Whether this CResult_ChannelTypeFeaturesDecodeErrorZ represents a success state. - */ - bool result_ok; -} LDKCResult_ChannelTypeFeaturesDecodeErrorZ; - - - -/** - * Features used within an `offer`. - */ -typedef struct MUST_USE_STRUCT LDKOfferFeatures { +typedef struct MUST_USE_STRUCT LDKBlindedHopFeatures { /** * A pointer to the opaque Rust object. * Nearly everywhere, inner must be non-null, however in places where * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKnativeOfferFeatures *inner; + LDKnativeBlindedHopFeatures *inner; /** * Indicates that this is the only struct which contains the same pointer. * Rust functions which take ownership of an object provided via an argument require * this to be true and invalidate the object pointed to by inner. */ bool is_owned; -} LDKOfferFeatures; +} LDKBlindedHopFeatures; /** - * The contents of CResult_OfferFeaturesDecodeErrorZ + * The contents of CResult_BlindedHopFeaturesDecodeErrorZ */ -typedef union LDKCResult_OfferFeaturesDecodeErrorZPtr { +typedef union LDKCResult_BlindedHopFeaturesDecodeErrorZPtr { /** * A pointer to the contents in the success state. * Reading from this pointer when `result_ok` is not set is undefined. */ - struct LDKOfferFeatures *result; + struct LDKBlindedHopFeatures *result; /** * A pointer to the contents in the error state. * Reading from this pointer when `result_ok` is set is undefined. */ struct LDKDecodeError *err; -} LDKCResult_OfferFeaturesDecodeErrorZPtr; +} LDKCResult_BlindedHopFeaturesDecodeErrorZPtr; /** - * A CResult_OfferFeaturesDecodeErrorZ represents the result of a fallible operation, - * containing a crate::lightning::ln::features::OfferFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. + * A CResult_BlindedHopFeaturesDecodeErrorZ represents the result of a fallible operation, + * containing a crate::lightning::ln::features::BlindedHopFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ -typedef struct LDKCResult_OfferFeaturesDecodeErrorZ { +typedef struct LDKCResult_BlindedHopFeaturesDecodeErrorZ { /** - * The contents of this CResult_OfferFeaturesDecodeErrorZ, accessible via either + * The contents of this CResult_BlindedHopFeaturesDecodeErrorZ, accessible via either * `err` or `result` depending on the state of `result_ok`. */ - union LDKCResult_OfferFeaturesDecodeErrorZPtr contents; + union LDKCResult_BlindedHopFeaturesDecodeErrorZPtr contents; /** - * Whether this CResult_OfferFeaturesDecodeErrorZ represents a success state. + * Whether this CResult_BlindedHopFeaturesDecodeErrorZ represents a success state. */ bool result_ok; -} LDKCResult_OfferFeaturesDecodeErrorZ; - - - -/** - * Features used within an `invoice_request`. - */ -typedef struct MUST_USE_STRUCT LDKInvoiceRequestFeatures { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeInvoiceRequestFeatures *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKInvoiceRequestFeatures; +} LDKCResult_BlindedHopFeaturesDecodeErrorZ; /** - * The contents of CResult_InvoiceRequestFeaturesDecodeErrorZ + * The contents of CResult_ChannelTypeFeaturesDecodeErrorZ */ -typedef union LDKCResult_InvoiceRequestFeaturesDecodeErrorZPtr { +typedef union LDKCResult_ChannelTypeFeaturesDecodeErrorZPtr { /** * A pointer to the contents in the success state. * Reading from this pointer when `result_ok` is not set is undefined. */ - struct LDKInvoiceRequestFeatures *result; + struct LDKChannelTypeFeatures *result; /** * A pointer to the contents in the error state. * Reading from this pointer when `result_ok` is set is undefined. */ struct LDKDecodeError *err; -} LDKCResult_InvoiceRequestFeaturesDecodeErrorZPtr; +} LDKCResult_ChannelTypeFeaturesDecodeErrorZPtr; /** - * A CResult_InvoiceRequestFeaturesDecodeErrorZ represents the result of a fallible operation, - * containing a crate::lightning::ln::features::InvoiceRequestFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. + * A CResult_ChannelTypeFeaturesDecodeErrorZ represents the result of a fallible operation, + * containing a crate::lightning::ln::features::ChannelTypeFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ -typedef struct LDKCResult_InvoiceRequestFeaturesDecodeErrorZ { +typedef struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ { /** - * The contents of this CResult_InvoiceRequestFeaturesDecodeErrorZ, accessible via either + * The contents of this CResult_ChannelTypeFeaturesDecodeErrorZ, accessible via either * `err` or `result` depending on the state of `result_ok`. */ - union LDKCResult_InvoiceRequestFeaturesDecodeErrorZPtr contents; + union LDKCResult_ChannelTypeFeaturesDecodeErrorZPtr contents; /** - * Whether this CResult_InvoiceRequestFeaturesDecodeErrorZ represents a success state. + * Whether this CResult_ChannelTypeFeaturesDecodeErrorZ represents a success state. */ bool result_ok; -} LDKCResult_InvoiceRequestFeaturesDecodeErrorZ; +} LDKCResult_ChannelTypeFeaturesDecodeErrorZ; /** * The contents of CResult_NodeIdDecodeErrorZ @@ -5819,10 +6193,103 @@ typedef struct LDKCResult_COption_NetworkUpdateZDecodeErrorZ { } LDKCResult_COption_NetworkUpdateZDecodeErrorZ; /** - * The `Access` trait defines behavior for accessing chain data and state, such as blocks and - * UTXOs. + * The contents of CResult_TxOutUtxoLookupErrorZ + */ +typedef union LDKCResult_TxOutUtxoLookupErrorZPtr { + /** + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. + */ + struct LDKTxOut *result; + /** + * A pointer to the contents in the error state. + * Reading from this pointer when `result_ok` is set is undefined. + */ + enum LDKUtxoLookupError *err; +} LDKCResult_TxOutUtxoLookupErrorZPtr; + +/** + * A CResult_TxOutUtxoLookupErrorZ represents the result of a fallible operation, + * containing a crate::c_types::TxOut on success and a crate::lightning::routing::utxo::UtxoLookupError on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult_TxOutUtxoLookupErrorZ { + /** + * The contents of this CResult_TxOutUtxoLookupErrorZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. + */ + union LDKCResult_TxOutUtxoLookupErrorZPtr contents; + /** + * Whether this CResult_TxOutUtxoLookupErrorZ represents a success state. + */ + bool result_ok; +} LDKCResult_TxOutUtxoLookupErrorZ; + + + +/** + * Represents a future resolution of a [`UtxoLookup::get_utxo`] query resolving async. + * + * See [`UtxoResult::Async`] and [`UtxoFuture::resolve`] for more info. + */ +typedef struct MUST_USE_STRUCT LDKUtxoFuture { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeUtxoFuture *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKUtxoFuture; + +/** + * The result of a [`UtxoLookup::get_utxo`] call. A call may resolve either synchronously, + * returning the `Sync` variant, or asynchronously, returning an [`UtxoFuture`] in the `Async` + * variant. + */ +typedef enum LDKUtxoResult_Tag { + /** + * A result which was resolved synchronously. It either includes a [`TxOut`] for the output + * requested or a [`UtxoLookupError`]. + */ + LDKUtxoResult_Sync, + /** + * A result which will be resolved asynchronously. It includes a [`UtxoFuture`], a `clone` of + * which you must keep locally and call [`UtxoFuture::resolve`] on once the lookup completes. + * + * Note that in order to avoid runaway memory usage, the number of parallel checks is limited, + * but only fairly loosely. Because a pending checks block all message processing, leaving + * checks pending for an extended time may cause DoS of other functions. It is recommended you + * keep a tight timeout on lookups, on the order of a few seconds. + */ + LDKUtxoResult_Async, + /** + * Must be last for serialization purposes + */ + LDKUtxoResult_Sentinel, +} LDKUtxoResult_Tag; + +typedef struct MUST_USE_STRUCT LDKUtxoResult { + LDKUtxoResult_Tag tag; + union { + struct { + struct LDKCResult_TxOutUtxoLookupErrorZ sync; + }; + struct { + struct LDKUtxoFuture async; + }; + }; +} LDKUtxoResult; + +/** + * The `UtxoLookup` trait defines behavior for accessing on-chain UTXOs. */ -typedef struct LDKAccess { +typedef struct LDKUtxoLookup { /** * An opaque pointer which is passed to your function implementations as an argument. * This has no meaning in the LDK, and can be NULL or any other value. @@ -5835,40 +6302,40 @@ typedef struct LDKAccess { * * [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id */ - struct LDKCResult_TxOutAccessErrorZ (*get_utxo)(const void *this_arg, const uint8_t (*genesis_hash)[32], uint64_t short_channel_id); + struct LDKUtxoResult (*get_utxo)(const void *this_arg, const uint8_t (*genesis_hash)[32], uint64_t short_channel_id); /** * Frees any resources associated with this object given its this_arg pointer. * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. */ void (*free)(void *this_arg); -} LDKAccess; +} LDKUtxoLookup; /** - * An enum which can either contain a crate::lightning::chain::Access or not + * An enum which can either contain a crate::lightning::routing::utxo::UtxoLookup or not */ -typedef enum LDKCOption_AccessZ_Tag { +typedef enum LDKCOption_UtxoLookupZ_Tag { /** - * When we're in this state, this COption_AccessZ contains a crate::lightning::chain::Access + * When we're in this state, this COption_UtxoLookupZ contains a crate::lightning::routing::utxo::UtxoLookup */ - LDKCOption_AccessZ_Some, + LDKCOption_UtxoLookupZ_Some, /** - * When we're in this state, this COption_AccessZ contains nothing + * When we're in this state, this COption_UtxoLookupZ contains nothing */ - LDKCOption_AccessZ_None, + LDKCOption_UtxoLookupZ_None, /** * Must be last for serialization purposes */ - LDKCOption_AccessZ_Sentinel, -} LDKCOption_AccessZ_Tag; + LDKCOption_UtxoLookupZ_Sentinel, +} LDKCOption_UtxoLookupZ_Tag; -typedef struct LDKCOption_AccessZ { - LDKCOption_AccessZ_Tag tag; +typedef struct LDKCOption_UtxoLookupZ { + LDKCOption_UtxoLookupZ_Tag tag; union { struct { - struct LDKAccess some; + struct LDKUtxoLookup some; }; }; -} LDKCOption_AccessZ; +} LDKCOption_UtxoLookupZ; /** * The contents of CResult_boolLightningErrorZ @@ -6167,7 +6634,9 @@ typedef struct LDKTwelveBytes { * Only the character set and length will be validated. * The character set consists of ASCII alphanumeric characters, hyphens, and periods. * Its length is guaranteed to be representable by a single byte. - * This serialization is used by BOLT 7 hostnames. + * This serialization is used by [`BOLT 7`] hostnames. + * + * [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md */ typedef struct MUST_USE_STRUCT LDKHostname { /** @@ -6185,7 +6654,7 @@ typedef struct MUST_USE_STRUCT LDKHostname { } LDKHostname; /** - * An address which can be used to connect to a remote peer + * An address which can be used to connect to a remote peer. */ typedef enum LDKNetAddress_Tag { /** @@ -6205,7 +6674,8 @@ typedef enum LDKNetAddress_Tag { LDKNetAddress_OnionV2, /** * A new-style Tor onion address/port on which the peer is listening. - * To create the human-readable \"hostname\", concatenate ed25519_pubkey, checksum, and version, + * + * To create the human-readable \"hostname\", concatenate the ED25519 pubkey, checksum, and version, * wrap as base32 and append \".onion\". */ LDKNetAddress_OnionV3, @@ -6715,94 +7185,6 @@ typedef struct LDKCResult_SignatureNoneZ { bool result_ok; } LDKCResult_SignatureNoneZ; -/** - * A tuple of 2 elements. See the individual fields for the types contained. - */ -typedef struct LDKC2Tuple_SignatureSignatureZ { - /** - * The element at position 0 - */ - struct LDKSignature a; - /** - * The element at position 1 - */ - struct LDKSignature b; -} LDKC2Tuple_SignatureSignatureZ; - -/** - * The contents of CResult_C2Tuple_SignatureSignatureZNoneZ - */ -typedef union LDKCResult_C2Tuple_SignatureSignatureZNoneZPtr { - /** - * A pointer to the contents in the success state. - * Reading from this pointer when `result_ok` is not set is undefined. - */ - struct LDKC2Tuple_SignatureSignatureZ *result; - /** - * Note that this value is always NULL, as there are no contents in the Err variant - */ - void *err; -} LDKCResult_C2Tuple_SignatureSignatureZNoneZPtr; - -/** - * A CResult_C2Tuple_SignatureSignatureZNoneZ represents the result of a fallible operation, - * containing a crate::c_types::derived::C2Tuple_SignatureSignatureZ on success and a () on failure. - * `result_ok` indicates the overall state, and the contents are provided via `contents`. - */ -typedef struct LDKCResult_C2Tuple_SignatureSignatureZNoneZ { - /** - * The contents of this CResult_C2Tuple_SignatureSignatureZNoneZ, accessible via either - * `err` or `result` depending on the state of `result_ok`. - */ - union LDKCResult_C2Tuple_SignatureSignatureZNoneZPtr contents; - /** - * Whether this CResult_C2Tuple_SignatureSignatureZNoneZ represents a success state. - */ - bool result_ok; -} LDKCResult_C2Tuple_SignatureSignatureZNoneZ; - -/** - * Represents a valid secp256k1 secret key serialized as a 32 byte array. - */ -typedef struct LDKSecretKey { - /** - * The bytes of the secret key - */ - uint8_t bytes[32]; -} LDKSecretKey; - -/** - * The contents of CResult_SecretKeyNoneZ - */ -typedef union LDKCResult_SecretKeyNoneZPtr { - /** - * A pointer to the contents in the success state. - * Reading from this pointer when `result_ok` is not set is undefined. - */ - struct LDKSecretKey *result; - /** - * Note that this value is always NULL, as there are no contents in the Err variant - */ - void *err; -} LDKCResult_SecretKeyNoneZPtr; - -/** - * A CResult_SecretKeyNoneZ represents the result of a fallible operation, - * containing a crate::c_types::SecretKey on success and a () on failure. - * `result_ok` indicates the overall state, and the contents are provided via `contents`. - */ -typedef struct LDKCResult_SecretKeyNoneZ { - /** - * The contents of this CResult_SecretKeyNoneZ, accessible via either - * `err` or `result` depending on the state of `result_ok`. - */ - union LDKCResult_SecretKeyNoneZPtr contents; - /** - * Whether this CResult_SecretKeyNoneZ represents a success state. - */ - bool result_ok; -} LDKCResult_SecretKeyNoneZ; - /** * The contents of CResult_PublicKeyNoneZ */ @@ -6894,65 +7276,129 @@ typedef struct LDKCResult_SharedSecretNoneZ { bool result_ok; } LDKCResult_SharedSecretNoneZ; - +/** + * Integer in the range `0..32` + */ +typedef struct LDKU5 { + uint8_t _0; +} LDKU5; /** - * This class tracks the per-transaction information needed to build a closing transaction and will - * actually build it and sign. - * - * This class can be used inside a signer implementation to generate a signature given the relevant - * secret key. + * A dynamically-allocated array of crate::c_types::U5s of arbitrary size. + * This corresponds to std::vector in C++ */ -typedef struct MUST_USE_STRUCT LDKClosingTransaction { +typedef struct LDKCVec_U5Z { /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. + * The elements in the array. + * If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). */ - LDKnativeClosingTransaction *inner; + struct LDKU5 *data; /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. + * The number of elements pointed to by `data`. */ - bool is_owned; -} LDKClosingTransaction; - - + uintptr_t datalen; +} LDKCVec_U5Z; /** - * The unsigned part of a channel_announcement + * Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which + * allows recovering the exact public key which created the signature given the message. */ -typedef struct MUST_USE_STRUCT LDKUnsignedChannelAnnouncement { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeUnsignedChannelAnnouncement *inner; +typedef struct LDKRecoverableSignature { /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. + * The bytes of the signature in "compact" form plus a "Recovery ID" which allows for + * recovery. */ - bool is_owned; -} LDKUnsignedChannelAnnouncement; + uint8_t serialized_form[68]; +} LDKRecoverableSignature; /** - * A trait to sign Lightning channel transactions as described in - * [BOLT 3](https://github.com/lightning/bolts/blob/master/03-transactions.md). - * - * Signing services could be implemented on a hardware wallet and should implement signing - * policies in order to be secure. Please refer to the [VLS Policy - * Controls](https://gitlab.com/lightning-signer/validating-lightning-signer/-/blob/main/docs/policy-controls.md) - * for an example of such policies. + * The contents of CResult_RecoverableSignatureNoneZ */ -typedef struct LDKBaseSign { +typedef union LDKCResult_RecoverableSignatureNoneZPtr { /** - * An opaque pointer which is passed to your function implementations as an argument. - * This has no meaning in the LDK, and can be NULL or any other value. + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. */ - void *this_arg; + struct LDKRecoverableSignature *result; + /** + * Note that this value is always NULL, as there are no contents in the Err variant + */ + void *err; +} LDKCResult_RecoverableSignatureNoneZPtr; + +/** + * A CResult_RecoverableSignatureNoneZ represents the result of a fallible operation, + * containing a crate::c_types::RecoverableSignature on success and a () on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult_RecoverableSignatureNoneZ { + /** + * The contents of this CResult_RecoverableSignatureNoneZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. + */ + union LDKCResult_RecoverableSignatureNoneZPtr contents; + /** + * Whether this CResult_RecoverableSignatureNoneZ represents a success state. + */ + bool result_ok; +} LDKCResult_RecoverableSignatureNoneZ; + + + +/** + * This class tracks the per-transaction information needed to build a closing transaction and will + * actually build it and sign. + * + * This class can be used inside a signer implementation to generate a signature given the relevant + * secret key. + */ +typedef struct MUST_USE_STRUCT LDKClosingTransaction { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeClosingTransaction *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKClosingTransaction; + + + +/** + * The unsigned part of a [`channel_announcement`] message. + * + * [`channel_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message + */ +typedef struct MUST_USE_STRUCT LDKUnsignedChannelAnnouncement { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeUnsignedChannelAnnouncement *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKUnsignedChannelAnnouncement; + +/** + * A trait to handle Lightning channel key material without concretizing the channel type or + * the signature mechanism. + */ +typedef struct LDKChannelSigner { + /** + * An opaque pointer which is passed to your function implementations as an argument. + * This has no meaning in the LDK, and can be NULL or any other value. + */ + void *this_arg; /** * Gets the per-commitment point for a specific commitment number * @@ -6995,13 +7441,47 @@ typedef struct LDKBaseSign { * Note that this takes a pointer to this object, not the this_ptr like other methods do * This function pointer may be NULL if pubkeys is filled in when this object is created and never needs updating. */ - void (*set_pubkeys)(const struct LDKBaseSign*NONNULL_PTR ); + void (*set_pubkeys)(const struct LDKChannelSigner*NONNULL_PTR ); /** * Returns an arbitrary identifier describing the set of keys which are provided back to you in * some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this - * [`BaseSign`] object uniquely and lookup or re-derive its keys. + * [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys. */ struct LDKThirtyTwoBytes (*channel_keys_id)(const void *this_arg); + /** + * Set the counterparty static channel data, including basepoints, + * `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint. + * + * This data is static, and will never change for a channel once set. For a given [`ChannelSigner`] + * instance, LDK will call this method exactly once - either immediately after construction + * (not including if done via [`SignerProvider::read_chan_signer`]) or when the funding + * information has been generated. + * + * channel_parameters.is_populated() MUST be true. + */ + void (*provide_channel_parameters)(void *this_arg, const struct LDKChannelTransactionParameters *NONNULL_PTR channel_parameters); + /** + * Frees any resources associated with this object given its this_arg pointer. + * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. + */ + void (*free)(void *this_arg); +} LDKChannelSigner; + +/** + * A trait to sign Lightning channel transactions as described in + * [BOLT 3](https://github.com/lightning/bolts/blob/master/03-transactions.md). + * + * Signing services could be implemented on a hardware wallet and should implement signing + * policies in order to be secure. Please refer to the [VLS Policy + * Controls](https://gitlab.com/lightning-signer/validating-lightning-signer/-/blob/main/docs/policy-controls.md) + * for an example of such policies. + */ +typedef struct LDKEcdsaChannelSigner { + /** + * An opaque pointer which is passed to your function implementations as an argument. + * This has no meaning in the LDK, and can be NULL or any other value. + */ + void *this_arg; /** * Create a signature for a counterparty's commitment transaction and associated HTLC transactions. * @@ -7114,32 +7594,27 @@ typedef struct LDKBaseSign { */ struct LDKCResult_SignatureNoneZ (*sign_holder_anchor_input)(const void *this_arg, struct LDKTransaction anchor_tx, uintptr_t input); /** - * Signs a channel announcement message with our funding key and our node secret key (aka - * node_id or network_key), proving it comes from one of the channel participants. + * Signs a channel announcement message with our funding key proving it comes from one of the + * channel participants. * - * The first returned signature should be from our node secret key, the second from our - * funding key. + * Channel announcements also require a signature from each node's network key. Our node + * signature is computed through [`NodeSigner::sign_gossip_message`]. * * Note that if this fails or is rejected, the channel will not be publicly announced and * our counterparty may (though likely will not) close the channel on us for violating the * protocol. */ - struct LDKCResult_C2Tuple_SignatureSignatureZNoneZ (*sign_channel_announcement)(const void *this_arg, const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg); + struct LDKCResult_SignatureNoneZ (*sign_channel_announcement_with_funding_key)(const void *this_arg, const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg); /** - * Set the counterparty static channel data, including basepoints, - * `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint. Since these - * are static channel data, they MUST NOT be allowed to change to different values once set, - * as LDK may call this method more than once. - * - * channel_parameters.is_populated() MUST be true. + * Implementation of ChannelSigner for this object. */ - void (*provide_channel_parameters)(void *this_arg, const struct LDKChannelTransactionParameters *NONNULL_PTR channel_parameters); + struct LDKChannelSigner ChannelSigner; /** * Frees any resources associated with this object given its this_arg pointer. * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. */ void (*free)(void *this_arg); -} LDKBaseSign; +} LDKEcdsaChannelSigner; /** * A writeable signer. @@ -7150,16 +7625,16 @@ typedef struct LDKBaseSign { * [`ChannelManager`]: crate::ln::channelmanager::ChannelManager * [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor */ -typedef struct LDKSign { +typedef struct LDKWriteableEcdsaChannelSigner { /** * An opaque pointer which is passed to your function implementations as an argument. * This has no meaning in the LDK, and can be NULL or any other value. */ void *this_arg; /** - * Implementation of BaseSign for this object. + * Implementation of EcdsaChannelSigner for this object. */ - struct LDKBaseSign BaseSign; + struct LDKEcdsaChannelSigner EcdsaChannelSigner; /** * Serialize the object into a byte array */ @@ -7169,107 +7644,40 @@ typedef struct LDKSign { * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. */ void (*free)(void *this_arg); -} LDKSign; +} LDKWriteableEcdsaChannelSigner; /** - * The contents of CResult_SignDecodeErrorZ + * The contents of CResult_WriteableEcdsaChannelSignerDecodeErrorZ */ -typedef union LDKCResult_SignDecodeErrorZPtr { +typedef union LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZPtr { /** * A pointer to the contents in the success state. * Reading from this pointer when `result_ok` is not set is undefined. */ - struct LDKSign *result; + struct LDKWriteableEcdsaChannelSigner *result; /** * A pointer to the contents in the error state. * Reading from this pointer when `result_ok` is set is undefined. */ struct LDKDecodeError *err; -} LDKCResult_SignDecodeErrorZPtr; +} LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZPtr; /** - * A CResult_SignDecodeErrorZ represents the result of a fallible operation, - * containing a crate::lightning::chain::keysinterface::Sign on success and a crate::lightning::ln::msgs::DecodeError on failure. + * A CResult_WriteableEcdsaChannelSignerDecodeErrorZ represents the result of a fallible operation, + * containing a crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner on success and a crate::lightning::ln::msgs::DecodeError on failure. * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ -typedef struct LDKCResult_SignDecodeErrorZ { +typedef struct LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ { /** - * The contents of this CResult_SignDecodeErrorZ, accessible via either + * The contents of this CResult_WriteableEcdsaChannelSignerDecodeErrorZ, accessible via either * `err` or `result` depending on the state of `result_ok`. */ - union LDKCResult_SignDecodeErrorZPtr contents; + union LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZPtr contents; /** - * Whether this CResult_SignDecodeErrorZ represents a success state. + * Whether this CResult_WriteableEcdsaChannelSignerDecodeErrorZ represents a success state. */ bool result_ok; -} LDKCResult_SignDecodeErrorZ; - -/** - * Integer in the range `0..32` - */ -typedef struct LDKU5 { - uint8_t _0; -} LDKU5; - -/** - * A dynamically-allocated array of crate::c_types::U5s of arbitrary size. - * This corresponds to std::vector in C++ - */ -typedef struct LDKCVec_U5Z { - /** - * The elements in the array. - * If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). - */ - struct LDKU5 *data; - /** - * The number of elements pointed to by `data`. - */ - uintptr_t datalen; -} LDKCVec_U5Z; - -/** - * Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which - * allows recovering the exact public key which created the signature given the message. - */ -typedef struct LDKRecoverableSignature { - /** - * The bytes of the signature in "compact" form plus a "Recovery ID" which allows for - * recovery. - */ - uint8_t serialized_form[68]; -} LDKRecoverableSignature; - -/** - * The contents of CResult_RecoverableSignatureNoneZ - */ -typedef union LDKCResult_RecoverableSignatureNoneZPtr { - /** - * A pointer to the contents in the success state. - * Reading from this pointer when `result_ok` is not set is undefined. - */ - struct LDKRecoverableSignature *result; - /** - * Note that this value is always NULL, as there are no contents in the Err variant - */ - void *err; -} LDKCResult_RecoverableSignatureNoneZPtr; - -/** - * A CResult_RecoverableSignatureNoneZ represents the result of a fallible operation, - * containing a crate::c_types::RecoverableSignature on success and a () on failure. - * `result_ok` indicates the overall state, and the contents are provided via `contents`. - */ -typedef struct LDKCResult_RecoverableSignatureNoneZ { - /** - * The contents of this CResult_RecoverableSignatureNoneZ, accessible via either - * `err` or `result` depending on the state of `result_ok`. - */ - union LDKCResult_RecoverableSignatureNoneZPtr contents; - /** - * Whether this CResult_RecoverableSignatureNoneZ represents a success state. - */ - bool result_ok; -} LDKCResult_RecoverableSignatureNoneZ; +} LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ; /** * A dynamically-allocated array of crate::c_types::derived::CVec_u8Zs of arbitrary size. @@ -7322,7 +7730,7 @@ typedef struct LDKCResult_CVec_CVec_u8ZZNoneZ { /** - * A simple implementation of [`Sign`] that just keeps the private keys in memory. + * A simple implementation of [`WriteableEcdsaChannelSigner`] that just keeps the private keys in memory. * * This implementation performs no policy checks and is insufficient by itself as * a secure external signer. @@ -7549,211 +7957,126 @@ typedef struct LDKCOption_u16Z { } LDKCOption_u16Z; /** - * Indicates an error on the client's part (usually some variant of attempting to use too-low or - * too-high values) + * The contents of CResult__u832APIErrorZ */ -typedef enum LDKAPIError_Tag { +typedef union LDKCResult__u832APIErrorZPtr { /** - * Indicates the API was wholly misused (see err for more). Cases where these can be returned - * are documented, but generally indicates some precondition of a function was violated. + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. */ - LDKAPIError_APIMisuseError, + struct LDKThirtyTwoBytes *result; /** - * Due to a high feerate, we were unable to complete the request. - * For example, this may be returned if the feerate implies we cannot open a channel at the - * requested value, but opening a larger channel would succeed. + * A pointer to the contents in the error state. + * Reading from this pointer when `result_ok` is set is undefined. */ - LDKAPIError_FeeRateTooHigh, + struct LDKAPIError *err; +} LDKCResult__u832APIErrorZPtr; + +/** + * A CResult__u832APIErrorZ represents the result of a fallible operation, + * containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::util::errors::APIError on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult__u832APIErrorZ { /** - * A malformed Route was provided (eg overflowed value, node id mismatch, overly-looped route, - * too-many-hops, etc). + * The contents of this CResult__u832APIErrorZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. */ - LDKAPIError_InvalidRoute, + union LDKCResult__u832APIErrorZPtr contents; /** - * We were unable to complete the request as the Channel required to do so is unable to - * complete the request (or was not found). This can take many forms, including disconnected - * peer, channel at capacity, channel shutting down, etc. + * Whether this CResult__u832APIErrorZ represents a success state. */ - LDKAPIError_ChannelUnavailable, + bool result_ok; +} LDKCResult__u832APIErrorZ; + +/** + * Used by [`ChannelManager::list_recent_payments`] to express the status of recent payments. + * These include payments that have yet to find a successful path, or have unresolved HTLCs. + */ +typedef enum LDKRecentPaymentDetails_Tag { /** - * An attempt to call [`chain::Watch::watch_channel`]/[`chain::Watch::update_channel`] - * returned a [`ChannelMonitorUpdateStatus::InProgress`] indicating the persistence of a - * monitor update is awaiting async resolution. Once it resolves the attempted action should - * complete automatically. - * - * [`chain::Watch::watch_channel`]: crate::chain::Watch::watch_channel - * [`chain::Watch::update_channel`]: crate::chain::Watch::update_channel - * [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress + * When a payment is still being sent and awaiting successful delivery. */ - LDKAPIError_MonitorUpdateInProgress, + LDKRecentPaymentDetails_Pending, /** - * [`KeysInterface::get_shutdown_scriptpubkey`] returned a shutdown scriptpubkey incompatible - * with the channel counterparty as negotiated in [`InitFeatures`]. - * - * Using a SegWit v0 script should resolve this issue. If you cannot, you won't be able to open - * a channel or cooperatively close one with this peer (and will have to force-close instead). - * - * [`KeysInterface::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::KeysInterface::get_shutdown_scriptpubkey - * [`InitFeatures`]: crate::ln::features::InitFeatures + * When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have + * been resolved. Upon receiving [`Event::PaymentSent`], we delay for a few minutes before the + * payment is removed from tracking. */ - LDKAPIError_IncompatibleShutdownScript, + LDKRecentPaymentDetails_Fulfilled, /** - * Must be last for serialization purposes + * After a payment's retries are exhausted per the provided [`Retry`], or it is explicitly + * abandoned via [`ChannelManager::abandon_payment`], it is marked as abandoned until all + * pending HTLCs for this payment resolve and an [`Event::PaymentFailed`] is generated. */ - LDKAPIError_Sentinel, -} LDKAPIError_Tag; - -typedef struct LDKAPIError_LDKAPIMisuseError_Body { + LDKRecentPaymentDetails_Abandoned, /** - * A human-readable error message + * Must be last for serialization purposes */ - struct LDKStr err; -} LDKAPIError_LDKAPIMisuseError_Body; + LDKRecentPaymentDetails_Sentinel, +} LDKRecentPaymentDetails_Tag; -typedef struct LDKAPIError_LDKFeeRateTooHigh_Body { +typedef struct LDKRecentPaymentDetails_LDKPending_Body { /** - * A human-readable error message + * Hash of the payment that is currently being sent but has yet to be fulfilled or + * abandoned. */ - struct LDKStr err; - /** - * The feerate which was too high. - */ - uint32_t feerate; -} LDKAPIError_LDKFeeRateTooHigh_Body; - -typedef struct LDKAPIError_LDKInvalidRoute_Body { + struct LDKThirtyTwoBytes payment_hash; /** - * A human-readable error message + * Total amount (in msat, excluding fees) across all paths for this payment, + * not just the amount currently inflight. */ - struct LDKStr err; -} LDKAPIError_LDKInvalidRoute_Body; + uint64_t total_msat; +} LDKRecentPaymentDetails_LDKPending_Body; -typedef struct LDKAPIError_LDKChannelUnavailable_Body { +typedef struct LDKRecentPaymentDetails_LDKFulfilled_Body { /** - * A human-readable error message + * Hash of the payment that was claimed. `None` for serializations of [`ChannelManager`] + * made before LDK version 0.0.104. + * + * Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None */ - struct LDKStr err; -} LDKAPIError_LDKChannelUnavailable_Body; + struct LDKThirtyTwoBytes payment_hash; +} LDKRecentPaymentDetails_LDKFulfilled_Body; -typedef struct LDKAPIError_LDKIncompatibleShutdownScript_Body { +typedef struct LDKRecentPaymentDetails_LDKAbandoned_Body { /** - * The incompatible shutdown script. + * Hash of the payment that we have given up trying to send. */ - struct LDKShutdownScript script; -} LDKAPIError_LDKIncompatibleShutdownScript_Body; + struct LDKThirtyTwoBytes payment_hash; +} LDKRecentPaymentDetails_LDKAbandoned_Body; -typedef struct MUST_USE_STRUCT LDKAPIError { - LDKAPIError_Tag tag; +typedef struct MUST_USE_STRUCT LDKRecentPaymentDetails { + LDKRecentPaymentDetails_Tag tag; union { - LDKAPIError_LDKAPIMisuseError_Body api_misuse_error; - LDKAPIError_LDKFeeRateTooHigh_Body fee_rate_too_high; - LDKAPIError_LDKInvalidRoute_Body invalid_route; - LDKAPIError_LDKChannelUnavailable_Body channel_unavailable; - LDKAPIError_LDKIncompatibleShutdownScript_Body incompatible_shutdown_script; + LDKRecentPaymentDetails_LDKPending_Body pending; + LDKRecentPaymentDetails_LDKFulfilled_Body fulfilled; + LDKRecentPaymentDetails_LDKAbandoned_Body abandoned; }; -} LDKAPIError; - -/** - * The contents of CResult_NoneAPIErrorZ - */ -typedef union LDKCResult_NoneAPIErrorZPtr { - /** - * Note that this value is always NULL, as there are no contents in the OK variant - */ - void *result; - /** - * A pointer to the contents in the error state. - * Reading from this pointer when `result_ok` is set is undefined. - */ - struct LDKAPIError *err; -} LDKCResult_NoneAPIErrorZPtr; +} LDKRecentPaymentDetails; /** - * A CResult_NoneAPIErrorZ represents the result of a fallible operation, - * containing a () on success and a crate::lightning::util::errors::APIError on failure. - * `result_ok` indicates the overall state, and the contents are provided via `contents`. - */ -typedef struct LDKCResult_NoneAPIErrorZ { - /** - * The contents of this CResult_NoneAPIErrorZ, accessible via either - * `err` or `result` depending on the state of `result_ok`. - */ - union LDKCResult_NoneAPIErrorZPtr contents; - /** - * Whether this CResult_NoneAPIErrorZ represents a success state. - */ - bool result_ok; -} LDKCResult_NoneAPIErrorZ; - -/** - * A dynamically-allocated array of crate::c_types::derived::CResult_NoneAPIErrorZs of arbitrary size. + * A dynamically-allocated array of crate::lightning::ln::channelmanager::RecentPaymentDetailss of arbitrary size. * This corresponds to std::vector in C++ */ -typedef struct LDKCVec_CResult_NoneAPIErrorZZ { +typedef struct LDKCVec_RecentPaymentDetailsZ { /** * The elements in the array. * If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). */ - struct LDKCResult_NoneAPIErrorZ *data; + struct LDKRecentPaymentDetails *data; /** * The number of elements pointed to by `data`. */ uintptr_t datalen; -} LDKCVec_CResult_NoneAPIErrorZZ; +} LDKCVec_RecentPaymentDetailsZ; /** - * A dynamically-allocated array of crate::lightning::util::errors::APIErrors of arbitrary size. - * This corresponds to std::vector in C++ - */ -typedef struct LDKCVec_APIErrorZ { - /** - * The elements in the array. - * If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). - */ - struct LDKAPIError *data; - /** - * The number of elements pointed to by `data`. - */ - uintptr_t datalen; -} LDKCVec_APIErrorZ; - -/** - * The contents of CResult__u832APIErrorZ - */ -typedef union LDKCResult__u832APIErrorZPtr { - /** - * A pointer to the contents in the success state. - * Reading from this pointer when `result_ok` is not set is undefined. - */ - struct LDKThirtyTwoBytes *result; - /** - * A pointer to the contents in the error state. - * Reading from this pointer when `result_ok` is set is undefined. - */ - struct LDKAPIError *err; -} LDKCResult__u832APIErrorZPtr; - -/** - * A CResult__u832APIErrorZ represents the result of a fallible operation, - * containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::util::errors::APIError on failure. - * `result_ok` indicates the overall state, and the contents are provided via `contents`. - */ -typedef struct LDKCResult__u832APIErrorZ { - /** - * The contents of this CResult__u832APIErrorZ, accessible via either - * `err` or `result` depending on the state of `result_ok`. - */ - union LDKCResult__u832APIErrorZPtr contents; - /** - * Whether this CResult__u832APIErrorZ represents a success state. - */ - bool result_ok; -} LDKCResult__u832APIErrorZ; - -/** - * If a payment fails to send, it can be in one of several states. This enum is returned as the - * Err() type describing which state the payment is in, see the description of individual enum - * states for more. + * If a payment fails to send with [`ChannelManager::send_payment`], it can be in one of several + * states. This enum is returned as the Err() type describing which state the payment is in, see + * the description of individual enum states for more. + * + * [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment */ typedef enum LDKPaymentSendFailure_Tag { /** @@ -7762,9 +8085,11 @@ typedef enum LDKPaymentSendFailure_Tag { * * You can freely resend the payment in full (with the parameter error fixed). * - * Because the payment failed outright, no payment tracking is done, you do not need to call - * [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work - * for this payment. + * Because the payment failed outright, no payment tracking is done and no + * [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated. + * + * [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed + * [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed */ LDKPaymentSendFailure_ParameterError, /** @@ -7773,12 +8098,14 @@ typedef enum LDKPaymentSendFailure_Tag { * * You can freely resend the payment in full (with the parameter error fixed). * + * Because the payment failed outright, no payment tracking is done and no + * [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated. + * * The results here are ordered the same as the paths in the route object which was passed to * send_payment. * - * Because the payment failed outright, no payment tracking is done, you do not need to call - * [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work - * for this payment. + * [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed + * [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed */ LDKPaymentSendFailure_PathParameterError, /** @@ -7786,32 +8113,33 @@ typedef enum LDKPaymentSendFailure_Tag { * You can freely resend the payment in full (though you probably want to do so over different * paths than the ones selected). * - * Because the payment failed outright, no payment tracking is done, you do not need to call - * [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work - * for this payment. + * Because the payment failed outright, no payment tracking is done and no + * [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated. + * + * [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed + * [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed */ LDKPaymentSendFailure_AllFailedResendSafe, /** * Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not - * yet completed (i.e. generated an [`Event::PaymentSent`]) or been abandoned (via - * [`ChannelManager::abandon_payment`]). + * yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]). * - * [`Event::PaymentSent`]: events::Event::PaymentSent + * [`PaymentId`]: crate::ln::channelmanager::PaymentId + * [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent + * [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed */ LDKPaymentSendFailure_DuplicatePayment, /** - * Some paths which were attempted failed to send, though possibly not all. At least some - * paths have irrevocably committed to the HTLC and retrying the payment in full would result - * in over-/re-payment. + * Some paths that were attempted failed to send, though some paths may have succeeded. At least + * some paths have irrevocably committed to the HTLC. * - * The results here are ordered the same as the paths in the route object which was passed to - * send_payment, and any `Err`s which are not [`APIError::MonitorUpdateInProgress`] can be - * safely retried via [`ChannelManager::retry_payment`]. + * The results here are ordered the same as the paths in the route object that was passed to + * send_payment. * - * Any entries which contain `Err(APIError::MonitorUpdateInprogress)` or `Ok(())` MUST NOT be - * retried as they will result in over-/re-payment. These HTLCs all either successfully sent - * (in the case of `Ok(())`) or will send once a [`MonitorEvent::Completed`] is provided for - * the next-hop channel with the latest update_id. + * Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a + * [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id. + * + * [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed */ LDKPaymentSendFailure_PartialFailure, /** @@ -7822,13 +8150,12 @@ typedef enum LDKPaymentSendFailure_Tag { typedef struct LDKPaymentSendFailure_LDKPartialFailure_Body { /** - * The errors themselves, in the same order as the route hops. + * The errors themselves, in the same order as the paths from the route. */ struct LDKCVec_CResult_NoneAPIErrorZZ results; /** * If some paths failed without irrevocably committing to the new HTLC(s), this will - * contain a [`RouteParameters`] object which can be used to calculate a new route that - * will pay all remaining unpaid balance. + * contain a [`RouteParameters`] object for the failing paths. * * Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None */ @@ -7872,7 +8199,7 @@ typedef union LDKCResult_NonePaymentSendFailureZPtr { /** * A CResult_NonePaymentSendFailureZ represents the result of a fallible operation, - * containing a () on success and a crate::lightning::ln::channelmanager::PaymentSendFailure on failure. + * containing a () on success and a crate::lightning::ln::outbound_payment::PaymentSendFailure on failure. * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ typedef struct LDKCResult_NonePaymentSendFailureZ { @@ -7887,6 +8214,38 @@ typedef struct LDKCResult_NonePaymentSendFailureZ { bool result_ok; } LDKCResult_NonePaymentSendFailureZ; +/** + * The contents of CResult_NoneRetryableSendFailureZ + */ +typedef union LDKCResult_NoneRetryableSendFailureZPtr { + /** + * Note that this value is always NULL, as there are no contents in the OK variant + */ + void *result; + /** + * A pointer to the contents in the error state. + * Reading from this pointer when `result_ok` is set is undefined. + */ + enum LDKRetryableSendFailure *err; +} LDKCResult_NoneRetryableSendFailureZPtr; + +/** + * A CResult_NoneRetryableSendFailureZ represents the result of a fallible operation, + * containing a () on success and a crate::lightning::ln::outbound_payment::RetryableSendFailure on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult_NoneRetryableSendFailureZ { + /** + * The contents of this CResult_NoneRetryableSendFailureZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. + */ + union LDKCResult_NoneRetryableSendFailureZPtr contents; + /** + * Whether this CResult_NoneRetryableSendFailureZ represents a success state. + */ + bool result_ok; +} LDKCResult_NoneRetryableSendFailureZ; + /** * The contents of CResult_PaymentHashPaymentSendFailureZ */ @@ -7905,7 +8264,7 @@ typedef union LDKCResult_PaymentHashPaymentSendFailureZPtr { /** * A CResult_PaymentHashPaymentSendFailureZ represents the result of a fallible operation, - * containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::ln::channelmanager::PaymentSendFailure on failure. + * containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::ln::outbound_payment::PaymentSendFailure on failure. * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ typedef struct LDKCResult_PaymentHashPaymentSendFailureZ { @@ -7920,6 +8279,39 @@ typedef struct LDKCResult_PaymentHashPaymentSendFailureZ { bool result_ok; } LDKCResult_PaymentHashPaymentSendFailureZ; +/** + * The contents of CResult_PaymentHashRetryableSendFailureZ + */ +typedef union LDKCResult_PaymentHashRetryableSendFailureZPtr { + /** + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. + */ + struct LDKThirtyTwoBytes *result; + /** + * A pointer to the contents in the error state. + * Reading from this pointer when `result_ok` is set is undefined. + */ + enum LDKRetryableSendFailure *err; +} LDKCResult_PaymentHashRetryableSendFailureZPtr; + +/** + * A CResult_PaymentHashRetryableSendFailureZ represents the result of a fallible operation, + * containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::ln::outbound_payment::RetryableSendFailure on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult_PaymentHashRetryableSendFailureZ { + /** + * The contents of this CResult_PaymentHashRetryableSendFailureZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. + */ + union LDKCResult_PaymentHashRetryableSendFailureZPtr contents; + /** + * Whether this CResult_PaymentHashRetryableSendFailureZ represents a success state. + */ + bool result_ok; +} LDKCResult_PaymentHashRetryableSendFailureZ; + /** * A tuple of 2 elements. See the individual fields for the types contained. */ @@ -7952,7 +8344,7 @@ typedef union LDKCResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZPtr { /** * A CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ represents the result of a fallible operation, - * containing a crate::c_types::derived::C2Tuple_PaymentHashPaymentIdZ on success and a crate::lightning::ln::channelmanager::PaymentSendFailure on failure. + * containing a crate::c_types::derived::C2Tuple_PaymentHashPaymentIdZ on success and a crate::lightning::ln::outbound_payment::PaymentSendFailure on failure. * `result_ok` indicates the overall state, and the contents are provided via `contents`. */ typedef struct LDKCResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { @@ -8447,7 +8839,7 @@ typedef struct LDKWatch { * * [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor */ - enum LDKChannelMonitorUpdateStatus (*update_channel)(const void *this_arg, struct LDKOutPoint funding_txo, struct LDKChannelMonitorUpdate update); + enum LDKChannelMonitorUpdateStatus (*update_channel)(const void *this_arg, struct LDKOutPoint funding_txo, const struct LDKChannelMonitorUpdate *NONNULL_PTR update); /** * Returns any monitor events since the last call. Subsequent calls must only return new * events. @@ -8487,6 +8879,27 @@ typedef struct LDKBroadcasterInterface { void (*free)(void *this_arg); } LDKBroadcasterInterface; +/** + * A trait that describes a source of entropy. + */ +typedef struct LDKEntropySource { + /** + * An opaque pointer which is passed to your function implementations as an argument. + * This has no meaning in the LDK, and can be NULL or any other value. + */ + void *this_arg; + /** + * Gets a unique, cryptographically-secure, random 32-byte value. This method must return a + * different value each time it is called. + */ + struct LDKThirtyTwoBytes (*get_secure_random_bytes)(const void *this_arg); + /** + * Frees any resources associated with this object given its this_arg pointer. + * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. + */ + void (*free)(void *this_arg); +} LDKEntropySource; + /** * A "slice" referencing some byte array. This is simply a length-tagged pointer which does not * own the memory pointed to by data. @@ -8502,65 +8915,172 @@ typedef struct LDKu8slice { uintptr_t datalen; } LDKu8slice; + + /** - * A trait to describe an object which can get user secrets and key material. + * The unsigned part of a [`channel_update`] message. + * + * [`channel_update`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message */ -typedef struct LDKKeysInterface { +typedef struct MUST_USE_STRUCT LDKUnsignedChannelUpdate { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeUnsignedChannelUpdate *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKUnsignedChannelUpdate; + + + +/** + * The unsigned part of a [`node_announcement`] message. + * + * [`node_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message + */ +typedef struct MUST_USE_STRUCT LDKUnsignedNodeAnnouncement { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeUnsignedNodeAnnouncement *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKUnsignedNodeAnnouncement; + +/** + * Represents the set of gossip messages that require a signature from a node's identity key. + */ +typedef enum LDKUnsignedGossipMessage_Tag { + /** + * An unsigned channel announcement. + */ + LDKUnsignedGossipMessage_ChannelAnnouncement, + /** + * An unsigned channel update. + */ + LDKUnsignedGossipMessage_ChannelUpdate, + /** + * An unsigned node announcement. + */ + LDKUnsignedGossipMessage_NodeAnnouncement, + /** + * Must be last for serialization purposes + */ + LDKUnsignedGossipMessage_Sentinel, +} LDKUnsignedGossipMessage_Tag; + +typedef struct MUST_USE_STRUCT LDKUnsignedGossipMessage { + LDKUnsignedGossipMessage_Tag tag; + union { + struct { + struct LDKUnsignedChannelAnnouncement channel_announcement; + }; + struct { + struct LDKUnsignedChannelUpdate channel_update; + }; + struct { + struct LDKUnsignedNodeAnnouncement node_announcement; + }; + }; +} LDKUnsignedGossipMessage; + +/** + * A trait that can handle cryptographic operations at the scope level of a node. + */ +typedef struct LDKNodeSigner { /** * An opaque pointer which is passed to your function implementations as an argument. * This has no meaning in the LDK, and can be NULL or any other value. */ void *this_arg; /** - * Get node secret key based on the provided [`Recipient`]. + * Get secret key material as bytes for use in encrypting and decrypting inbound payment data. * - * The `node_id`/`network_key` is the public key that corresponds to this secret key. + * If the implementor of this trait supports [phantom node payments], then every node that is + * intended to be included in the phantom invoice route hints must return the same value from + * this method. * - * This method must return the same value each time it is called with a given [`Recipient`] - * parameter. + * This method must return the same value each time it is called. * - * Errors if the [`Recipient`] variant is not supported by the implementation. + * [phantom node payments]: PhantomKeysManager */ - struct LDKCResult_SecretKeyNoneZ (*get_node_secret)(const void *this_arg, enum LDKRecipient recipient); + struct LDKThirtyTwoBytes (*get_inbound_payment_key_material)(const void *this_arg); /** - * Get node id based on the provided [`Recipient`]. This public key corresponds to the secret in - * [`get_node_secret`]. + * Get node id based on the provided [`Recipient`]. * * This method must return the same value each time it is called with a given [`Recipient`] * parameter. * * Errors if the [`Recipient`] variant is not supported by the implementation. - * - * [`get_node_secret`]: Self::get_node_secret */ struct LDKCResult_PublicKeyNoneZ (*get_node_id)(const void *this_arg, enum LDKRecipient recipient); /** - * Gets the ECDH shared secret of our [`node secret`] and `other_key`, multiplying by `tweak` if + * Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if * one is provided. Note that this tweak can be applied to `other_key` instead of our node * secret, though this is less efficient. * - * Errors if the [`Recipient`] variant is not supported by the implementation. + * Note that if this fails while attempting to forward an HTLC, LDK will panic. The error + * should be resolved to allow LDK to resume forwarding HTLCs. * - * [`node secret`]: Self::get_node_secret + * Errors if the [`Recipient`] variant is not supported by the implementation. */ struct LDKCResult_SharedSecretNoneZ (*ecdh)(const void *this_arg, enum LDKRecipient recipient, struct LDKPublicKey other_key, struct LDKCOption_ScalarZ tweak); /** - * Get a script pubkey which we send funds to when claiming on-chain contestable outputs. + * Sign an invoice. * - * This method should return a different value each time it is called, to avoid linking - * on-chain funds across channels as controlled to the same user. + * By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of + * this trait to parse the invoice and make sure they're signing what they expect, rather than + * blindly signing the hash. + * + * The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32. + * + * The secret key used to sign the invoice is dependent on the [`Recipient`]. + * + * Errors if the [`Recipient`] variant is not supported by the implementation. */ - struct LDKCVec_u8Z (*get_destination_script)(const void *this_arg); + struct LDKCResult_RecoverableSignatureNoneZ (*sign_invoice)(const void *this_arg, struct LDKu8slice hrp_bytes, struct LDKCVec_U5Z invoice_data, enum LDKRecipient recipient); /** - * Get a script pubkey which we will send funds to when closing a channel. + * Sign a gossip message. * - * This method should return a different value each time it is called, to avoid linking - * on-chain funds across channels as controlled to the same user. + * Note that if this fails, LDK may panic and the message will not be broadcast to the network + * or a possible channel counterparty. If LDK panics, the error should be resolved to allow the + * message to be broadcast, as otherwise it may prevent one from receiving funds over the + * corresponding channel. */ - struct LDKShutdownScript (*get_shutdown_scriptpubkey)(const void *this_arg); + struct LDKCResult_SignatureNoneZ (*sign_gossip_message)(const void *this_arg, struct LDKUnsignedGossipMessage msg); + /** + * Frees any resources associated with this object given its this_arg pointer. + * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. + */ + void (*free)(void *this_arg); +} LDKNodeSigner; + +/** + * A trait that can return signer instances for individual channels. + */ +typedef struct LDKSignerProvider { + /** + * An opaque pointer which is passed to your function implementations as an argument. + * This has no meaning in the LDK, and can be NULL or any other value. + */ + void *this_arg; /** - * Get a new set of [`Sign`] for per-channel secrets. These MUST be unique even if you - * restarted with some stale data! + * Generates a unique `channel_keys_id` that can be used to obtain a [`Self::Signer`] through + * [`SignerProvider::derive_channel_signer`]. The `user_channel_id` is provided to allow + * implementations of [`SignerProvider`] to maintain a mapping between itself and the generated + * `channel_keys_id`. * * This method must return a different value each time it is called. */ @@ -8569,23 +9089,15 @@ typedef struct LDKKeysInterface { * Derives the private key material backing a `Signer`. * * To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through - * [`KeysInterface::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be + * [`SignerProvider::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be * re-derived from its `channel_keys_id`, which can be obtained through its trait method - * [`BaseSign::channel_keys_id`]. - */ - struct LDKSign (*derive_channel_signer)(const void *this_arg, uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id); - /** - * Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting - * onion packets and for temporary channel IDs. There is no requirement that these be - * persisted anywhere, though they must be unique across restarts. - * - * This method must return a different value each time it is called. + * [`ChannelSigner::channel_keys_id`]. */ - struct LDKThirtyTwoBytes (*get_secure_random_bytes)(const void *this_arg); + struct LDKWriteableEcdsaChannelSigner (*derive_channel_signer)(const void *this_arg, uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id); /** - * Reads a [`Signer`] for this [`KeysInterface`] from the given input stream. + * Reads a [`Signer`] for this [`SignerProvider`] from the given input stream. * This is only called during deserialization of other objects which contain - * [`Sign`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s). + * [`WriteableEcdsaChannelSigner`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s). * The bytes are exactly those which `::write()` writes, and * contain no versioning scheme. You may wish to include your own version prefix and ensure * you've read all of the provided bytes to ensure no corruption occurred. @@ -8597,37 +9109,27 @@ typedef struct LDKKeysInterface { * [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor * [`ChannelManager`]: crate::ln::channelmanager::ChannelManager */ - struct LDKCResult_SignDecodeErrorZ (*read_chan_signer)(const void *this_arg, struct LDKu8slice reader); + struct LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ (*read_chan_signer)(const void *this_arg, struct LDKu8slice reader); /** - * Sign an invoice. - * By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of - * this trait to parse the invoice and make sure they're signing what they expect, rather than - * blindly signing the hash. - * The `hrp` is ASCII bytes, while the invoice data is base32-encoded. - * - * The secret key used to sign the invoice is dependent on the [`Recipient`]. + * Get a script pubkey which we send funds to when claiming on-chain contestable outputs. * - * Errors if the [`Recipient`] variant is not supported by the implementation. + * This method should return a different value each time it is called, to avoid linking + * on-chain funds across channels as controlled to the same user. */ - struct LDKCResult_RecoverableSignatureNoneZ (*sign_invoice)(const void *this_arg, struct LDKu8slice hrp_bytes, struct LDKCVec_U5Z invoice_data, enum LDKRecipient receipient); + struct LDKCVec_u8Z (*get_destination_script)(const void *this_arg); /** - * Get secret key material as bytes for use in encrypting and decrypting inbound payment data. - * - * If the implementor of this trait supports [phantom node payments], then every node that is - * intended to be included in the phantom invoice route hints must return the same value from - * this method. - * - * This method must return the same value each time it is called. + * Get a script pubkey which we will send funds to when closing a channel. * - * [phantom node payments]: PhantomKeysManager + * This method should return a different value each time it is called, to avoid linking + * on-chain funds across channels as controlled to the same user. */ - struct LDKThirtyTwoBytes (*get_inbound_payment_key_material)(const void *this_arg); + struct LDKShutdownScript (*get_shutdown_scriptpubkey)(const void *this_arg); /** * Frees any resources associated with this object given its this_arg pointer. * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. */ void (*free)(void *this_arg); -} LDKKeysInterface; +} LDKSignerProvider; /** * A trait which should be implemented to provide feerate information on a number of time @@ -8660,6 +9162,35 @@ typedef struct LDKFeeEstimator { void (*free)(void *this_arg); } LDKFeeEstimator; +/** + * A trait defining behavior for routing a payment. + */ +typedef struct LDKRouter { + /** + * An opaque pointer which is passed to your function implementations as an argument. + * This has no meaning in the LDK, and can be NULL or any other value. + */ + void *this_arg; + /** + * Finds a [`Route`] between `payer` and `payee` for a payment with the given values. + * + * Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None + */ + struct LDKCResult_RouteLightningErrorZ (*find_route)(const void *this_arg, struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, const struct LDKInFlightHtlcs *NONNULL_PTR inflight_htlcs); + /** + * Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes + * `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment. + * + * Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None + */ + struct LDKCResult_RouteLightningErrorZ (*find_route_with_id)(const void *this_arg, struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, const struct LDKInFlightHtlcs *NONNULL_PTR inflight_htlcs, struct LDKThirtyTwoBytes _payment_hash, struct LDKThirtyTwoBytes _payment_id); + /** + * Frees any resources associated with this object given its this_arg pointer. + * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. + */ + void (*free)(void *this_arg); +} LDKRouter; + /** @@ -8694,6 +9225,15 @@ typedef struct LDKFeeEstimator { * offline for a full minute. In order to track this, you must call * timer_tick_occurred roughly once per minute, though it doesn't have to be perfect. * + * To avoid trivial DoS issues, ChannelManager limits the number of inbound connections and + * inbound channels without confirmed funding transactions. This may result in nodes which we do + * not have a channel with being unable to connect to us or open new channels with us if we have + * many peers with unfunded channels. + * + * Because it is an indication of trust, inbound channels which we've accepted as 0conf are + * exempted from the count of unfunded channels. Similarly, outbound channels and connections are + * never limited. Please ensure you limit the count of such channels yourself. + * * Rather than using a plain ChannelManager, it is preferable to use either a SimpleArcChannelManager * a SimpleRefChannelManager, for conciseness. See their documentation for more details, but * essentially you should default to using a SimpleRefChannelManager, and use a @@ -8816,6 +9356,66 @@ typedef struct LDKCResult_ChannelConfigDecodeErrorZ { bool result_ok; } LDKCResult_ChannelConfigDecodeErrorZ; +/** + * An enum which can either contain a crate::lightning::util::errors::APIError or not + */ +typedef enum LDKCOption_APIErrorZ_Tag { + /** + * When we're in this state, this COption_APIErrorZ contains a crate::lightning::util::errors::APIError + */ + LDKCOption_APIErrorZ_Some, + /** + * When we're in this state, this COption_APIErrorZ contains nothing + */ + LDKCOption_APIErrorZ_None, + /** + * Must be last for serialization purposes + */ + LDKCOption_APIErrorZ_Sentinel, +} LDKCOption_APIErrorZ_Tag; + +typedef struct LDKCOption_APIErrorZ { + LDKCOption_APIErrorZ_Tag tag; + union { + struct { + struct LDKAPIError some; + }; + }; +} LDKCOption_APIErrorZ; + +/** + * The contents of CResult_COption_APIErrorZDecodeErrorZ + */ +typedef union LDKCResult_COption_APIErrorZDecodeErrorZPtr { + /** + * A pointer to the contents in the success state. + * Reading from this pointer when `result_ok` is not set is undefined. + */ + struct LDKCOption_APIErrorZ *result; + /** + * A pointer to the contents in the error state. + * Reading from this pointer when `result_ok` is set is undefined. + */ + struct LDKDecodeError *err; +} LDKCResult_COption_APIErrorZDecodeErrorZPtr; + +/** + * A CResult_COption_APIErrorZDecodeErrorZ represents the result of a fallible operation, + * containing a crate::c_types::derived::COption_APIErrorZ on success and a crate::lightning::ln::msgs::DecodeError on failure. + * `result_ok` indicates the overall state, and the contents are provided via `contents`. + */ +typedef struct LDKCResult_COption_APIErrorZDecodeErrorZ { + /** + * The contents of this CResult_COption_APIErrorZDecodeErrorZ, accessible via either + * `err` or `result` depending on the state of `result_ok`. + */ + union LDKCResult_COption_APIErrorZDecodeErrorZPtr contents; + /** + * Whether this CResult_COption_APIErrorZDecodeErrorZ represents a success state. + */ + bool result_ok; +} LDKCResult_COption_APIErrorZDecodeErrorZ; + /** * The contents of CResult_OutPointDecodeErrorZ */ @@ -8947,10 +9547,6 @@ typedef enum LDKPaymentError_Tag { * An error resulting from the provided [`Invoice`] or payment hash. */ LDKPaymentError_Invoice, - /** - * An error occurring when finding a route. - */ - LDKPaymentError_Routing, /** * An error occurring when sending a payment. */ @@ -8968,10 +9564,7 @@ typedef struct MUST_USE_STRUCT LDKPaymentError { struct LDKStr invoice; }; struct { - struct LDKLightningError routing; - }; - struct { - struct LDKPaymentSendFailure sending; + enum LDKRetryableSendFailure sending; }; }; } LDKPaymentError; @@ -9725,6 +10318,36 @@ typedef struct LDKCOption_NetAddressZ { }; } LDKCOption_NetAddressZ; +/** + * A tuple of 2 elements. See the individual fields for the types contained. + */ +typedef struct LDKC2Tuple_PublicKeyCOption_NetAddressZZ { + /** + * The element at position 0 + */ + struct LDKPublicKey a; + /** + * The element at position 1 + */ + struct LDKCOption_NetAddressZ b; +} LDKC2Tuple_PublicKeyCOption_NetAddressZZ; + +/** + * A dynamically-allocated array of crate::c_types::derived::C2Tuple_PublicKeyCOption_NetAddressZZs of arbitrary size. + * This corresponds to std::vector in C++ + */ +typedef struct LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ { + /** + * The elements in the array. + * If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). + */ + struct LDKC2Tuple_PublicKeyCOption_NetAddressZZ *data; + /** + * The number of elements pointed to by `data`. + */ + uintptr_t datalen; +} LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ; + /** @@ -9878,15 +10501,15 @@ typedef enum LDKSendError_Tag { */ LDKSendError_BufferFull, /** - * Failed to retrieve our node id from the provided [`KeysInterface`]. + * Failed to retrieve our node id from the provided [`NodeSigner`]. * - * [`KeysInterface`]: crate::chain::keysinterface::KeysInterface + * [`NodeSigner`]: crate::chain::keysinterface::NodeSigner */ LDKSendError_GetNodeIdFailed, /** * We attempted to send to a blinded path where we are the introduction node, and failed to * advance the blinded path to make the second hop the new introduction node. Either - * [`KeysInterface::ecdh`] failed, we failed to tweak the current blinding point to get the + * [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the * new blinding point, or we were attempting to send to ourselves. */ LDKSendError_BlindedPathAdvanceFailed, @@ -10649,7 +11272,9 @@ typedef struct LDKCResult_NetAddressDecodeErrorZ { /** - * An update_add_htlc message to be sent or received from a peer + * An [`update_add_htlc`] message to be sent to or received from a peer. + * + * [`update_add_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#adding-an-htlc-update_add_htlc */ typedef struct MUST_USE_STRUCT LDKUpdateAddHTLC { /** @@ -10685,7 +11310,9 @@ typedef struct LDKCVec_UpdateAddHTLCZ { /** - * An update_fulfill_htlc message to be sent or received from a peer + * An [`update_fulfill_htlc`] message to be sent to or received from a peer. + * + * [`update_fulfill_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc */ typedef struct MUST_USE_STRUCT LDKUpdateFulfillHTLC { /** @@ -10721,7 +11348,9 @@ typedef struct LDKCVec_UpdateFulfillHTLCZ { /** - * An update_fail_htlc message to be sent or received from a peer + * An [`update_fail_htlc`] message to be sent to or received from a peer. + * + * [`update_fail_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc */ typedef struct MUST_USE_STRUCT LDKUpdateFailHTLC { /** @@ -10757,7 +11386,9 @@ typedef struct LDKCVec_UpdateFailHTLCZ { /** - * An update_fail_malformed_htlc message to be sent or received from a peer + * An [`update_fail_malformed_htlc`] message to be sent to or received from a peer. + * + * [`update_fail_malformed_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc */ typedef struct MUST_USE_STRUCT LDKUpdateFailMalformedHTLC { /** @@ -10926,6 +11557,7 @@ typedef struct LDKCResult_ClosingSignedDecodeErrorZ { /** * The minimum and maximum fees which the sender is willing to place on the closing transaction. + * * This is provided in [`ClosingSigned`] by both sides to indicate the fee range they are willing * to use. */ @@ -10980,7 +11612,9 @@ typedef struct LDKCResult_ClosingSignedFeeRangeDecodeErrorZ { /** - * A commitment_signed message to be sent or received from a peer + * A [`commitment_signed`] message to be sent to or received from a peer. + * + * [`commitment_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#committing-updates-so-far-commitment_signed */ typedef struct MUST_USE_STRUCT LDKCommitmentSigned { /** @@ -11132,7 +11766,9 @@ typedef struct LDKCResult_ChannelReadyDecodeErrorZ { /** - * An init message to be sent or received from a peer + * An [`init`] message to be sent to or received from a peer. + * + * [`init`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-init-message */ typedef struct MUST_USE_STRUCT LDKInit { /** @@ -11350,7 +11986,9 @@ typedef struct LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ { /** - * An update_fee message to be sent or received from a peer + * An [`update_fee`] message to be sent to or received from a peer + * + * [`update_fee`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#updating-fees-update_fee */ typedef struct MUST_USE_STRUCT LDKUpdateFee { /** @@ -11469,7 +12107,8 @@ typedef struct LDKCResult_UpdateAddHTLCDecodeErrorZ { /** - * An onion message to be sent or received from a peer + * An onion message to be sent to or received from a peer. + * */ typedef struct MUST_USE_STRUCT LDKOnionMessage { /** @@ -11522,7 +12161,9 @@ typedef struct LDKCResult_OnionMessageDecodeErrorZ { /** - * A ping message to be sent or received from a peer + * A [`ping`] message to be sent to or received from a peer. + * + * [`ping`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-ping-and-pong-messages */ typedef struct MUST_USE_STRUCT LDKPing { /** @@ -11575,7 +12216,9 @@ typedef struct LDKCResult_PingDecodeErrorZ { /** - * A pong message to be sent or received from a peer + * A [`pong`] message to be sent to or received from a peer. + * + * [`pong`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-ping-and-pong-messages */ typedef struct MUST_USE_STRUCT LDKPong { /** @@ -11691,26 +12334,6 @@ typedef struct LDKCResult_ChannelAnnouncementDecodeErrorZ { bool result_ok; } LDKCResult_ChannelAnnouncementDecodeErrorZ; - - -/** - * The unsigned part of a channel_update - */ -typedef struct MUST_USE_STRUCT LDKUnsignedChannelUpdate { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeUnsignedChannelUpdate *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKUnsignedChannelUpdate; - /** * The contents of CResult_UnsignedChannelUpdateDecodeErrorZ */ @@ -11843,26 +12466,6 @@ typedef struct LDKCResult_WarningMessageDecodeErrorZ { bool result_ok; } LDKCResult_WarningMessageDecodeErrorZ; - - -/** - * The unsigned part of a node_announcement - */ -typedef struct MUST_USE_STRUCT LDKUnsignedNodeAnnouncement { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeUnsignedNodeAnnouncement *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKUnsignedNodeAnnouncement; - /** * The contents of CResult_UnsignedNodeAnnouncementDecodeErrorZ */ @@ -11896,26 +12499,6 @@ typedef struct LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ { bool result_ok; } LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ; - - -/** - * A node_announcement message to be sent or received from a peer - */ -typedef struct MUST_USE_STRUCT LDKNodeAnnouncement { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeNodeAnnouncement *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKNodeAnnouncement; - /** * The contents of CResult_NodeAnnouncementDecodeErrorZ */ @@ -11985,10 +12568,12 @@ typedef struct LDKCResult_QueryShortChannelIdsDecodeErrorZ { /** - * A reply_short_channel_ids_end message is sent as a reply to a - * query_short_channel_ids message. The query recipient makes a best + * A [`reply_short_channel_ids_end`] message is sent as a reply to a + * message. The query recipient makes a best * effort to respond based on their local network view which may not be * a perfect view of the network. + * + * [`reply_short_channel_ids_end`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_short_channel_idsreply_short_channel_ids_end-messages */ typedef struct MUST_USE_STRUCT LDKReplyShortChannelIdsEnd { /** @@ -12586,7 +13171,7 @@ typedef struct LDKEventsProvider { /** - * Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's + * Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's * variable-length integers except that it is serialized in big-endian instead of little-endian. * * Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be @@ -12734,7 +13319,7 @@ typedef struct MUST_USE_STRUCT LDKChannelHandshakeConfig { * * These limits are only applied to our counterparty's limits, not our own. * - * Use 0/::max_value() as appropriate to skip checking. + * Use 0/`::max_value()` as appropriate to skip checking. * * Provides sane defaults for most configurations. * @@ -12922,6 +13507,9 @@ typedef struct LDKConfirm { * Returns transactions that must be monitored for reorganization out of the chain along * with the hash of the block as part of which it had been previously confirmed. * + * Note that the returned `Option` might be `None` for channels created with LDK + * 0.0.112 and prior, in which case you need to manually track previous confirmations. + * * Will include any transactions passed to [`transactions_confirmed`] that have insufficient * confirmations to be safe from a chain reorganization. Will not include any transactions * passed to [`transaction_unconfirmed`], unless later reconfirmed. @@ -13029,7 +13617,7 @@ typedef struct LDKPersist { * * Note that update (or a relevant inner pointer) may be NULL or all-0s to represent None */ - enum LDKChannelMonitorUpdateStatus (*update_persisted_channel)(const void *this_arg, struct LDKOutPoint channel_id, const struct LDKChannelMonitorUpdate *NONNULL_PTR update, const struct LDKChannelMonitor *NONNULL_PTR data, struct LDKMonitorUpdateId update_id); + enum LDKChannelMonitorUpdateStatus (*update_persisted_channel)(const void *this_arg, struct LDKOutPoint channel_id, struct LDKChannelMonitorUpdate update, const struct LDKChannelMonitor *NONNULL_PTR data, struct LDKMonitorUpdateId update_id); /** * Frees any resources associated with this object given its this_arg pointer. * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. @@ -13065,11 +13653,21 @@ typedef struct MUST_USE_STRUCT LDKChainMonitor { bool is_owned; } LDKChainMonitor; +/** + * Represents a valid secp256k1 secret key serialized as a 32 byte array. + */ +typedef struct LDKSecretKey { + /** + * The bytes of the secret key + */ + uint8_t bytes[32]; +} LDKSecretKey; + /** - * Simple [`KeysInterface`] implementation that takes a 32-byte seed for use as a BIP 32 extended - * key and derives keys from that. + * Simple implementation of [`EntropySource`], [`NodeSigner`], and [`SignerProvider`] that takes a + * 32-byte seed for use as a BIP 32 extended key and derives keys from that. * * Your `node_id` is seed/0'. * Unilateral closes may use seed/1'. @@ -13146,20 +13744,57 @@ typedef struct MUST_USE_STRUCT LDKChainParameters { * Nearly everywhere, inner must be non-null, however in places where * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKnativeChainParameters *inner; + LDKnativeChainParameters *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKChainParameters; + +/** + * Strategies available to retry payment path failures. + */ +typedef enum LDKRetry_Tag { + /** + * Max number of attempts to retry payment. + * + * Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a + * retry, and may retry multiple failed HTLCs at once if they failed around the same time and + * were retried along a route from a single call to [`Router::find_route`]. + */ + LDKRetry_Attempts, + /** + * Time elapsed before abandoning retries for a payment. At least one attempt at payment is made; + * see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time. + * + * [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time + */ + LDKRetry_Timeout, /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. + * Must be last for serialization purposes */ - bool is_owned; -} LDKChainParameters; + LDKRetry_Sentinel, +} LDKRetry_Tag; + +typedef struct MUST_USE_STRUCT LDKRetry { + LDKRetry_Tag tag; + union { + struct { + uintptr_t attempts; + }; + struct { + uint64_t timeout; + }; + }; +} LDKRetry; /** * A trait to describe an object which can receive channel messages. * - * Messages MAY be called in parallel when they originate from different their_node_ids, however - * they MUST NOT be called in parallel when the two calls have the same their_node_id. + * Messages MAY be called in parallel when they originate from different `their_node_ids`, however + * they MUST NOT be called in parallel when the two calls have the same `their_node_id`. */ typedef struct LDKChannelMessageHandler { /** @@ -13168,93 +13803,87 @@ typedef struct LDKChannelMessageHandler { */ void *this_arg; /** - * Handle an incoming open_channel message from the given peer. + * Handle an incoming `open_channel` message from the given peer. */ - void (*handle_open_channel)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKOpenChannel *NONNULL_PTR msg); + void (*handle_open_channel)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKOpenChannel *NONNULL_PTR msg); /** - * Handle an incoming accept_channel message from the given peer. + * Handle an incoming `accept_channel` message from the given peer. */ - void (*handle_accept_channel)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKAcceptChannel *NONNULL_PTR msg); + void (*handle_accept_channel)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKAcceptChannel *NONNULL_PTR msg); /** - * Handle an incoming funding_created message from the given peer. + * Handle an incoming `funding_created` message from the given peer. */ void (*handle_funding_created)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKFundingCreated *NONNULL_PTR msg); /** - * Handle an incoming funding_signed message from the given peer. + * Handle an incoming `funding_signed` message from the given peer. */ void (*handle_funding_signed)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKFundingSigned *NONNULL_PTR msg); /** - * Handle an incoming channel_ready message from the given peer. + * Handle an incoming `channel_ready` message from the given peer. */ void (*handle_channel_ready)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKChannelReady *NONNULL_PTR msg); /** - * Handle an incoming shutdown message from the given peer. + * Handle an incoming `shutdown` message from the given peer. */ - void (*handle_shutdown)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInitFeatures *NONNULL_PTR their_features, const struct LDKShutdown *NONNULL_PTR msg); + void (*handle_shutdown)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKShutdown *NONNULL_PTR msg); /** - * Handle an incoming closing_signed message from the given peer. + * Handle an incoming `closing_signed` message from the given peer. */ void (*handle_closing_signed)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKClosingSigned *NONNULL_PTR msg); /** - * Handle an incoming update_add_htlc message from the given peer. + * Handle an incoming `update_add_htlc` message from the given peer. */ void (*handle_update_add_htlc)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateAddHTLC *NONNULL_PTR msg); /** - * Handle an incoming update_fulfill_htlc message from the given peer. + * Handle an incoming `update_fulfill_htlc` message from the given peer. */ void (*handle_update_fulfill_htlc)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateFulfillHTLC *NONNULL_PTR msg); /** - * Handle an incoming update_fail_htlc message from the given peer. + * Handle an incoming `update_fail_htlc` message from the given peer. */ void (*handle_update_fail_htlc)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateFailHTLC *NONNULL_PTR msg); /** - * Handle an incoming update_fail_malformed_htlc message from the given peer. + * Handle an incoming `update_fail_malformed_htlc` message from the given peer. */ void (*handle_update_fail_malformed_htlc)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR msg); /** - * Handle an incoming commitment_signed message from the given peer. + * Handle an incoming `commitment_signed` message from the given peer. */ void (*handle_commitment_signed)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKCommitmentSigned *NONNULL_PTR msg); /** - * Handle an incoming revoke_and_ack message from the given peer. + * Handle an incoming `revoke_and_ack` message from the given peer. */ void (*handle_revoke_and_ack)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKRevokeAndACK *NONNULL_PTR msg); /** - * Handle an incoming update_fee message from the given peer. + * Handle an incoming `update_fee` message from the given peer. */ void (*handle_update_fee)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKUpdateFee *NONNULL_PTR msg); /** - * Handle an incoming announcement_signatures message from the given peer. + * Handle an incoming `announcement_signatures` message from the given peer. */ void (*handle_announcement_signatures)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKAnnouncementSignatures *NONNULL_PTR msg); /** - * Indicates a connection to the peer failed/an existing connection was lost. If no connection - * is believed to be possible in the future (eg they're sending us messages we don't - * understand or indicate they require unknown feature bits), no_connection_possible is set - * and any outstanding channels should be failed. - * - * Note that in some rare cases this may be called without a corresponding - * [`Self::peer_connected`]. + * Indicates a connection to the peer failed/an existing connection was lost. */ - void (*peer_disconnected)(const void *this_arg, struct LDKPublicKey their_node_id, bool no_connection_possible); + void (*peer_disconnected)(const void *this_arg, struct LDKPublicKey their_node_id); /** - * Handle a peer reconnecting, possibly generating channel_reestablish message(s). + * Handle a peer reconnecting, possibly generating `channel_reestablish` message(s). * * May return an `Err(())` if the features the peer supports are not sufficient to communicate * with us. Implementors should be somewhat conservative about doing so, however, as other * message handlers may still wish to communicate with this peer. */ - struct LDKCResult_NoneNoneZ (*peer_connected)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR msg); + struct LDKCResult_NoneNoneZ (*peer_connected)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR msg, bool inbound); /** - * Handle an incoming channel_reestablish message from the given peer. + * Handle an incoming `channel_reestablish` message from the given peer. */ void (*handle_channel_reestablish)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKChannelReestablish *NONNULL_PTR msg); /** - * Handle an incoming channel update from the given peer. + * Handle an incoming `channel_update` message from the given peer. */ void (*handle_channel_update)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKChannelUpdate *NONNULL_PTR msg); /** - * Handle an incoming error message from the given peer. + * Handle an incoming `error` message from the given peer. */ void (*handle_error)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKErrorMessage *NONNULL_PTR msg); /** @@ -13337,9 +13966,9 @@ typedef struct MUST_USE_STRUCT LDKChannelManagerReadArgs { /** * A set of keys that were HKDF-expanded from an initial call to - * [`KeysInterface::get_inbound_payment_key_material`]. + * [`NodeSigner::get_inbound_payment_key_material`]. * - * [`KeysInterface::get_inbound_payment_key_material`]: crate::chain::keysinterface::KeysInterface::get_inbound_payment_key_material + * [`NodeSigner::get_inbound_payment_key_material`]: crate::chain::keysinterface::NodeSigner::get_inbound_payment_key_material */ typedef struct MUST_USE_STRUCT LDKExpandedKey { /** @@ -13360,8 +13989,9 @@ typedef struct MUST_USE_STRUCT LDKExpandedKey { /** * Proof that the sender knows the per-commitment secret of the previous commitment transaction. + * * This is used to convince the recipient that the channel is at a certain commitment - * number even if they lost that data due to a local failure. Of course, the peer may lie + * number even if they lost that data due to a local failure. Of course, the peer may lie * and even later commitments may have been revoked. */ typedef struct MUST_USE_STRUCT LDKDataLossProtect { @@ -13394,8 +14024,8 @@ typedef struct LDKThreeBytes { * * # Implementor DoS Warnings * - * For `gossip_queries` messages there are potential DoS vectors when handling - * inbound queries. Implementors using an on-disk network graph should be aware of + * For messages enabled with the `gossip_queries` feature there are potential DoS vectors when + * handling inbound queries. Implementors using an on-disk network graph should be aware of * repeated disk I/O for queries accessing different parts of the network graph. */ typedef struct LDKRoutingMessageHandler { @@ -13405,36 +14035,36 @@ typedef struct LDKRoutingMessageHandler { */ void *this_arg; /** - * Handle an incoming node_announcement message, returning true if it should be forwarded on, - * false or returning an Err otherwise. + * Handle an incoming `node_announcement` message, returning `true` if it should be forwarded on, + * `false` or returning an `Err` otherwise. */ struct LDKCResult_boolLightningErrorZ (*handle_node_announcement)(const void *this_arg, const struct LDKNodeAnnouncement *NONNULL_PTR msg); /** - * Handle a channel_announcement message, returning true if it should be forwarded on, false - * or returning an Err otherwise. + * Handle a `channel_announcement` message, returning `true` if it should be forwarded on, `false` + * or returning an `Err` otherwise. */ struct LDKCResult_boolLightningErrorZ (*handle_channel_announcement)(const void *this_arg, const struct LDKChannelAnnouncement *NONNULL_PTR msg); /** - * Handle an incoming channel_update message, returning true if it should be forwarded on, - * false or returning an Err otherwise. + * Handle an incoming `channel_update` message, returning true if it should be forwarded on, + * `false` or returning an `Err` otherwise. */ struct LDKCResult_boolLightningErrorZ (*handle_channel_update)(const void *this_arg, const struct LDKChannelUpdate *NONNULL_PTR msg); /** * Gets channel announcements and updates required to dump our routing table to a remote node, - * starting at the short_channel_id indicated by starting_point and including announcements + * starting at the `short_channel_id` indicated by `starting_point` and including announcements * for a single channel. */ struct LDKCOption_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ (*get_next_channel_announcement)(const void *this_arg, uint64_t starting_point); /** * Gets a node announcement required to dump our routing table to a remote node, starting at * the node *after* the provided pubkey and including up to one announcement immediately - * higher (as defined by ::cmp) than starting_point. - * If None is provided for starting_point, we start at the first node. + * higher (as defined by `::cmp`) than `starting_point`. + * If `None` is provided for `starting_point`, we start at the first node. * * Note that starting_point (or a relevant inner pointer) may be NULL or all-0s to represent None * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None */ - struct LDKNodeAnnouncement (*get_next_node_announcement)(const void *this_arg, struct LDKPublicKey starting_point); + struct LDKNodeAnnouncement (*get_next_node_announcement)(const void *this_arg, struct LDKNodeId starting_point); /** * Called when a connection is established with a peer. This can be used to * perform routing table synchronization using a strategy defined by the @@ -13444,7 +14074,7 @@ typedef struct LDKRoutingMessageHandler { * with us. Implementors should be somewhat conservative about doing so, however, as other * message handlers may still wish to communicate with this peer. */ - struct LDKCResult_NoneNoneZ (*peer_connected)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init); + struct LDKCResult_NoneNoneZ (*peer_connected)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init, bool inbound); /** * Handles the reply of a query we initiated to learn about channels * for a given range of blocks. We can expect to receive one or more @@ -13459,15 +14089,22 @@ typedef struct LDKRoutingMessageHandler { */ struct LDKCResult_NoneLightningErrorZ (*handle_reply_short_channel_ids_end)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKReplyShortChannelIdsEnd msg); /** - * Handles when a peer asks us to send a list of short_channel_ids + * Handles when a peer asks us to send a list of `short_channel_id`s * for the requested range of blocks. */ struct LDKCResult_NoneLightningErrorZ (*handle_query_channel_range)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKQueryChannelRange msg); /** * Handles when a peer asks us to send routing gossip messages for a - * list of short_channel_ids. + * list of `short_channel_id`s. */ struct LDKCResult_NoneLightningErrorZ (*handle_query_short_channel_ids)(const void *this_arg, struct LDKPublicKey their_node_id, struct LDKQueryShortChannelIds msg); + /** + * Indicates that there are a large number of [`ChannelAnnouncement`] (or other) messages + * pending some async action. While there is no guarantee of the rate of future messages, the + * caller should seek to reduce the rate of new gossip messages handled, especially + * [`ChannelAnnouncement`]s. + */ + bool (*processing_queue_high)(const void *this_arg); /** * Gets the node feature flags which this handler itself supports. All available handlers are * queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`] @@ -13503,7 +14140,7 @@ typedef struct LDKOnionMessageHandler { */ void *this_arg; /** - * Handle an incoming onion_message message from the given peer. + * Handle an incoming `onion_message` message from the given peer. */ void (*handle_onion_message)(const void *this_arg, struct LDKPublicKey peer_node_id, const struct LDKOnionMessage *NONNULL_PTR msg); /** @@ -13514,15 +14151,12 @@ typedef struct LDKOnionMessageHandler { * with us. Implementors should be somewhat conservative about doing so, however, as other * message handlers may still wish to communicate with this peer. */ - struct LDKCResult_NoneNoneZ (*peer_connected)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init); + struct LDKCResult_NoneNoneZ (*peer_connected)(const void *this_arg, struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init, bool inbound); /** * Indicates a connection to the peer failed/an existing connection was lost. Allows handlers to * drop and refuse to forward onion messages to this peer. - * - * Note that in some rare cases this may be called without a corresponding - * [`Self::peer_connected`]. */ - void (*peer_disconnected)(const void *this_arg, struct LDKPublicKey their_node_id, bool no_connection_possible); + void (*peer_disconnected)(const void *this_arg, struct LDKPublicKey their_node_id); /** * Gets the node feature flags which this handler itself supports. All available handlers are * queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`] @@ -13573,7 +14207,14 @@ typedef struct LDKCustomMessageReader { } LDKCustomMessageReader; /** - * Handler for BOLT1-compliant messages. + * A handler provided to [`PeerManager`] for reading and handling custom messages. + * + * [BOLT 1] specifies a custom message type range for use with experimental or application-specific + * messages. `CustomMessageHandler` allows for user-defined handling of such types. See the + * [`lightning_custom_message`] crate for tools useful in composing more than one custom handler. + * + * [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md + * [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message */ typedef struct LDKCustomMessageHandler { /** @@ -13582,15 +14223,15 @@ typedef struct LDKCustomMessageHandler { */ void *this_arg; /** - * Called with the message type that was received and the buffer to be read. - * Can return a `MessageHandlingError` if the message could not be handled. + * Handles the given message sent from `sender_node_id`, possibly producing messages for + * [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`] + * to send. */ struct LDKCResult_NoneLightningErrorZ (*handle_custom_message)(const void *this_arg, struct LDKType msg, struct LDKPublicKey sender_node_id); /** - * Gets the list of pending messages which were generated by the custom message - * handler, clearing the list in the process. The first tuple element must - * correspond to the intended recipients node ids. If no connection to one of the - * specified node does not exist, the message is simply not sent to it. + * Returns the list of pending messages that were generated by the handler, clearing the list + * in the process. Each message is paired with the node id of the intended recipient. If no + * connection to the node exists, then the message is simply not sent. */ struct LDKCVec_C2Tuple_PublicKeyTypeZZ (*get_and_clear_pending_msg)(const void *this_arg); /** @@ -13831,32 +14472,72 @@ typedef struct MUST_USE_STRUCT LDKDirectedChannelTransactionParameters { bool is_owned; } LDKDirectedChannelTransactionParameters; + + /** - * Integer in the range `0..=16` + * Features used within an `offer`. */ -typedef struct LDKWitnessVersion { - uint8_t _0; -} LDKWitnessVersion; +typedef struct MUST_USE_STRUCT LDKOfferFeatures { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeOfferFeatures *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKOfferFeatures; /** - * A read-only view of [`NetworkGraph`]. + * Features used within an `invoice_request`. */ -typedef struct MUST_USE_STRUCT LDKReadOnlyNetworkGraph { +typedef struct MUST_USE_STRUCT LDKInvoiceRequestFeatures { /** * A pointer to the opaque Rust object. * Nearly everywhere, inner must be non-null, however in places where * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKnativeReadOnlyNetworkGraph *inner; + LDKnativeInvoiceRequestFeatures *inner; /** * Indicates that this is the only struct which contains the same pointer. * Rust functions which take ownership of an object provided via an argument require * this to be true and invalidate the object pointed to by inner. */ bool is_owned; -} LDKReadOnlyNetworkGraph; +} LDKInvoiceRequestFeatures; + + + +/** + * Features used within an `invoice`. + */ +typedef struct MUST_USE_STRUCT LDKBolt12InvoiceFeatures { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeBolt12InvoiceFeatures *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKBolt12InvoiceFeatures; + +/** + * Integer in the range `0..=16` + */ +typedef struct LDKWitnessVersion { + uint8_t _0; +} LDKWitnessVersion; @@ -13884,6 +14565,26 @@ typedef struct MUST_USE_STRUCT LDKP2PGossipSync { +/** + * A read-only view of [`NetworkGraph`]. + */ +typedef struct MUST_USE_STRUCT LDKReadOnlyNetworkGraph { + /** + * A pointer to the opaque Rust object. + * Nearly everywhere, inner must be non-null, however in places where + * the Rust equivalent takes an Option, it may be set to null to indicate None. + */ + LDKnativeReadOnlyNetworkGraph *inner; + /** + * Indicates that this is the only struct which contains the same pointer. + * Rust functions which take ownership of an object provided via an argument require + * this to be true and invalidate the object pointed to by inner. + */ + bool is_owned; +} LDKReadOnlyNetworkGraph; + + + /** * A wrapper around [`ChannelInfo`] representing information about the channel as directed from a * source node to a target node. @@ -13994,51 +14695,6 @@ typedef struct MUST_USE_STRUCT LDKDefaultRouter { bool is_owned; } LDKDefaultRouter; -/** - * A trait defining behavior for routing a payment. - */ -typedef struct LDKRouter { - /** - * An opaque pointer which is passed to your function implementations as an argument. - * This has no meaning in the LDK, and can be NULL or any other value. - */ - void *this_arg; - /** - * Finds a [`Route`] between `payer` and `payee` for a payment with the given values. - * - * Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None - */ - struct LDKCResult_RouteLightningErrorZ (*find_route)(const void *this_arg, struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, struct LDKInFlightHtlcs inflight_htlcs); - /** - * Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes - * `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment. - * - * Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None - */ - struct LDKCResult_RouteLightningErrorZ (*find_route_with_id)(const void *this_arg, struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, struct LDKInFlightHtlcs inflight_htlcs, struct LDKThirtyTwoBytes _payment_hash, struct LDKThirtyTwoBytes _payment_id); - /** - * Lets the router know that payment through a specific path has failed. - */ - void (*notify_payment_path_failed)(const void *this_arg, struct LDKCVec_RouteHopZ path, uint64_t short_channel_id); - /** - * Lets the router know that payment through a specific path was successful. - */ - void (*notify_payment_path_successful)(const void *this_arg, struct LDKCVec_RouteHopZ path); - /** - * Lets the router know that a payment probe was successful. - */ - void (*notify_payment_probe_successful)(const void *this_arg, struct LDKCVec_RouteHopZ path); - /** - * Lets the router know that a payment probe failed. - */ - void (*notify_payment_probe_failed)(const void *this_arg, struct LDKCVec_RouteHopZ path, uint64_t short_channel_id); - /** - * Frees any resources associated with this object given its this_arg pointer. - * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. - */ - void (*free)(void *this_arg); -} LDKRouter; - /** @@ -14143,16 +14799,16 @@ typedef struct MUST_USE_STRUCT LDKProbabilisticScoringParameters { * # extern crate bitcoin; * # use bitcoin::hashes::_export::_core::time::Duration; * # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey}; - * # use lightning::chain::keysinterface::{InMemorySigner, KeysManager, KeysInterface}; - * # use lightning::ln::msgs::DecodeError; + * # use lightning::chain::keysinterface::KeysManager; * # use lightning::ln::peer_handler::IgnoringMessageHandler; * # use lightning::onion_message::blinded_path::BlindedPath; - * # use lightning::onion_message::messenger::{CustomOnionMessageContents, Destination, OnionMessageContents, OnionMessenger}; + * # use lightning::onion_message::messenger::{Destination, OnionMessenger}; + * # use lightning::onion_message::packet::{CustomOnionMessageContents, OnionMessageContents}; * # use lightning::util::logger::{Logger, Record}; * # use lightning::util::ser::{Writeable, Writer}; * # use lightning::io; * # use std::sync::Arc; - * # struct FakeLogger {}; + * # struct FakeLogger; * # impl Logger for FakeLogger { * # fn log(&self, record: &Record) { unimplemented!() } * # } @@ -14168,7 +14824,7 @@ typedef struct MUST_USE_STRUCT LDKProbabilisticScoringParameters { * # let your_custom_message_handler = IgnoringMessageHandler {}; * // Create the onion messenger. This must use the same `keys_manager` as is passed to your * // ChannelManager. - * let onion_messenger = OnionMessenger::new(&keys_manager, logger, your_custom_message_handler); + * let onion_messenger = OnionMessenger::new(&keys_manager, &keys_manager, logger, &your_custom_message_handler); * * # struct YourCustomMessage {} * impl Writeable for YourCustomMessage { @@ -14478,22 +15134,22 @@ typedef struct MUST_USE_STRUCT LDKExpiryTime { /** - * `min_final_cltv_expiry` to use for the last HTLC in the route + * `min_final_cltv_expiry_delta` to use for the last HTLC in the route */ -typedef struct MUST_USE_STRUCT LDKMinFinalCltvExpiry { +typedef struct MUST_USE_STRUCT LDKMinFinalCltvExpiryDelta { /** * A pointer to the opaque Rust object. * Nearly everywhere, inner must be non-null, however in places where * the Rust equivalent takes an Option, it may be set to null to indicate None. */ - LDKnativeMinFinalCltvExpiry *inner; + LDKnativeMinFinalCltvExpiryDelta *inner; /** * Indicates that this is the only struct which contains the same pointer. * Rust functions which take ownership of an object provided via an argument require * this to be true and invalidate the object pointed to by inner. */ bool is_owned; -} LDKMinFinalCltvExpiry; +} LDKMinFinalCltvExpiryDelta; /** * A 20-byte byte array. @@ -14536,124 +15192,6 @@ typedef struct MUST_USE_STRUCT LDKFallback { }; } LDKFallback; -/** - * A trait defining behavior of an [`Invoice`] payer. - * - * While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls - * with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts. - * - * [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`]. - * - * In order to trivially ensure idempotency for payments, the default `Payer` implementation - * reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to - * provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map - * the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key. - * - * [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager - */ -typedef struct LDKPayer { - /** - * An opaque pointer which is passed to your function implementations as an argument. - * This has no meaning in the LDK, and can be NULL or any other value. - */ - void *this_arg; - /** - * Returns the payer's node id. - */ - struct LDKPublicKey (*node_id)(const void *this_arg); - /** - * Returns the payer's channels. - */ - struct LDKCVec_ChannelDetailsZ (*first_hops)(const void *this_arg); - /** - * Sends a payment over the Lightning Network using the given [`Route`]. - * - * Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None - */ - struct LDKCResult_NonePaymentSendFailureZ (*send_payment)(const void *this_arg, const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_hash, struct LDKThirtyTwoBytes payment_secret, struct LDKThirtyTwoBytes payment_id); - /** - * Sends a spontaneous payment over the Lightning Network using the given [`Route`]. - */ - struct LDKCResult_NonePaymentSendFailureZ (*send_spontaneous_payment)(const void *this_arg, const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_preimage, struct LDKThirtyTwoBytes payment_id); - /** - * Retries a failed payment path for the [`PaymentId`] using the given [`Route`]. - */ - struct LDKCResult_NonePaymentSendFailureZ (*retry_payment)(const void *this_arg, const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_id); - /** - * Signals that no further retries for the given payment will occur. - */ - void (*abandon_payment)(const void *this_arg, struct LDKThirtyTwoBytes payment_id); - /** - * Construct an [`InFlightHtlcs`] containing information about currently used up liquidity - * across payments. - */ - struct LDKInFlightHtlcs (*inflight_htlcs)(const void *this_arg); - /** - * Frees any resources associated with this object given its this_arg pointer. - * Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. - */ - void (*free)(void *this_arg); -} LDKPayer; - - - -/** - * A utility for paying [`Invoice`]s and sending spontaneous payments. - * - * See [module-level documentation] for details. - * - * [module-level documentation]: crate::payment - */ -typedef struct MUST_USE_STRUCT LDKInvoicePayer { - /** - * A pointer to the opaque Rust object. - * Nearly everywhere, inner must be non-null, however in places where - * the Rust equivalent takes an Option, it may be set to null to indicate None. - */ - LDKnativeInvoicePayer *inner; - /** - * Indicates that this is the only struct which contains the same pointer. - * Rust functions which take ownership of an object provided via an argument require - * this to be true and invalidate the object pointed to by inner. - */ - bool is_owned; -} LDKInvoicePayer; - -/** - * Strategies available to retry payment path failures for an [`Invoice`]. - * - */ -typedef enum LDKRetry_Tag { - /** - * Max number of attempts to retry payment. - * - * Note that this is the number of *path* failures, not full payment retries. For multi-path - * payments, if this is less than the total number of paths, we will never even retry all of the - * payment's paths. - */ - LDKRetry_Attempts, - /** - * Time elapsed before abandoning retries for a payment. - */ - LDKRetry_Timeout, - /** - * Must be last for serialization purposes - */ - LDKRetry_Sentinel, -} LDKRetry_Tag; - -typedef struct MUST_USE_STRUCT LDKRetry { - LDKRetry_Tag tag; - union { - struct { - uintptr_t attempts; - }; - struct { - uint64_t timeout; - }; - }; -} LDKRetry; - extern const uintptr_t MAX_BUF_SIZE; extern const uint64_t MIN_RELAY_FEE_SAT_PER_1000_WEIGHT; @@ -14668,7 +15206,7 @@ extern const uint16_t BREAKDOWN_TIMEOUT; extern const uint16_t MIN_CLTV_EXPIRY_DELTA; -extern const uint32_t MIN_FINAL_CLTV_EXPIRY; +extern const uint16_t MIN_FINAL_CLTV_EXPIRY_DELTA; extern const uint16_t MAX_HTLCS; @@ -14690,7 +15228,7 @@ extern const uint64_t MAX_TIMESTAMP; extern const uint64_t DEFAULT_EXPIRY_TIME; -extern const uint64_t DEFAULT_MIN_FINAL_CLTV_EXPIRY; +extern const uint64_t DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA; extern const uint8_t TAG_PAYMENT_HASH; @@ -14702,7 +15240,7 @@ extern const uint8_t TAG_DESCRIPTION_HASH; extern const uint8_t TAG_EXPIRY_TIME; -extern const uint8_t TAG_MIN_FINAL_CLTV_EXPIRY; +extern const uint8_t TAG_MIN_FINAL_CLTV_EXPIRY_DELTA; extern const uint8_t TAG_FALLBACK; @@ -14754,30 +15292,66 @@ void Witness_free(struct LDKWitness _res); /** * Convenience function for constructing a new TxOut */ -struct LDKTxOut TxOut_new(struct LDKCVec_u8Z script_pubkey, uint64_t value); +struct LDKTxOut TxOut_new(struct LDKCVec_u8Z script_pubkey, uint64_t value); + +/** + * Frees the data pointed to by script_pubkey. + */ +void TxOut_free(struct LDKTxOut _res); + +/** + * Creates a new TxOut which has the same data as `orig` but with a new script buffer. + */ +struct LDKTxOut TxOut_clone(const struct LDKTxOut *NONNULL_PTR orig); + +/** + * Frees the data buffer, if chars_is_owned is set and len > 0. + */ +void Str_free(struct LDKStr _res); + +#if defined(LDK_DEBUG_BUILD) +/** + * This function exists for memory safety testing purposes. It should never be used in production + * code + */ +const void *__unmangle_inner_ptr(const void *ptr); +#endif + +/** + * Creates a new CResult_NoneAPIErrorZ in the success state. + */ +struct LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_ok(void); + +/** + * Creates a new CResult_NoneAPIErrorZ in the error state. + */ +struct LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_err(struct LDKAPIError e); + +/** + * Checks if the given object is currently in the success state + */ +bool CResult_NoneAPIErrorZ_is_ok(const struct LDKCResult_NoneAPIErrorZ *NONNULL_PTR o); /** - * Frees the data pointed to by script_pubkey. + * Frees any resources used by the CResult_NoneAPIErrorZ. */ -void TxOut_free(struct LDKTxOut _res); +void CResult_NoneAPIErrorZ_free(struct LDKCResult_NoneAPIErrorZ _res); /** - * Creates a new TxOut which has the same data as `orig` but with a new script buffer. + * Creates a new CResult_NoneAPIErrorZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKTxOut TxOut_clone(const struct LDKTxOut *NONNULL_PTR orig); +struct LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_clone(const struct LDKCResult_NoneAPIErrorZ *NONNULL_PTR orig); /** - * Frees the data buffer, if chars_is_owned is set and len > 0. + * Frees the buffer pointed to by `data` if `datalen` is non-0. */ -void Str_free(struct LDKStr _res); +void CVec_CResult_NoneAPIErrorZZ_free(struct LDKCVec_CResult_NoneAPIErrorZZ _res); -#if defined(LDK_DEBUG_BUILD) /** - * This function exists for memory safety testing purposes. It should never be used in production - * code + * Frees the buffer pointed to by `data` if `datalen` is non-0. */ -const void *__unmangle_inner_ptr(const void *ptr); -#endif +void CVec_APIErrorZ_free(struct LDKCVec_APIErrorZ _res); /** * Constructs a new COption_HTLCClaimZ containing a crate::lightning::ln::chan_utils::HTLCClaim @@ -15622,6 +16196,74 @@ void CResult_PaymentPurposeDecodeErrorZ_free(struct LDKCResult_PaymentPurposeDec */ struct LDKCResult_PaymentPurposeDecodeErrorZ CResult_PaymentPurposeDecodeErrorZ_clone(const struct LDKCResult_PaymentPurposeDecodeErrorZ *NONNULL_PTR orig); +/** + * Constructs a new COption_NetworkUpdateZ containing a crate::lightning::routing::gossip::NetworkUpdate + */ +struct LDKCOption_NetworkUpdateZ COption_NetworkUpdateZ_some(struct LDKNetworkUpdate o); + +/** + * Constructs a new COption_NetworkUpdateZ containing nothing + */ +struct LDKCOption_NetworkUpdateZ COption_NetworkUpdateZ_none(void); + +/** + * Frees any resources associated with the crate::lightning::routing::gossip::NetworkUpdate, if we are in the Some state + */ +void COption_NetworkUpdateZ_free(struct LDKCOption_NetworkUpdateZ _res); + +/** + * Creates a new COption_NetworkUpdateZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCOption_NetworkUpdateZ COption_NetworkUpdateZ_clone(const struct LDKCOption_NetworkUpdateZ *NONNULL_PTR orig); + +/** + * Constructs a new COption_PathFailureZ containing a crate::lightning::util::events::PathFailure + */ +struct LDKCOption_PathFailureZ COption_PathFailureZ_some(struct LDKPathFailure o); + +/** + * Constructs a new COption_PathFailureZ containing nothing + */ +struct LDKCOption_PathFailureZ COption_PathFailureZ_none(void); + +/** + * Frees any resources associated with the crate::lightning::util::events::PathFailure, if we are in the Some state + */ +void COption_PathFailureZ_free(struct LDKCOption_PathFailureZ _res); + +/** + * Creates a new COption_PathFailureZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCOption_PathFailureZ COption_PathFailureZ_clone(const struct LDKCOption_PathFailureZ *NONNULL_PTR orig); + +/** + * Creates a new CResult_COption_PathFailureZDecodeErrorZ in the success state. + */ +struct LDKCResult_COption_PathFailureZDecodeErrorZ CResult_COption_PathFailureZDecodeErrorZ_ok(struct LDKCOption_PathFailureZ o); + +/** + * Creates a new CResult_COption_PathFailureZDecodeErrorZ in the error state. + */ +struct LDKCResult_COption_PathFailureZDecodeErrorZ CResult_COption_PathFailureZDecodeErrorZ_err(struct LDKDecodeError e); + +/** + * Checks if the given object is currently in the success state + */ +bool CResult_COption_PathFailureZDecodeErrorZ_is_ok(const struct LDKCResult_COption_PathFailureZDecodeErrorZ *NONNULL_PTR o); + +/** + * Frees any resources used by the CResult_COption_PathFailureZDecodeErrorZ. + */ +void CResult_COption_PathFailureZDecodeErrorZ_free(struct LDKCResult_COption_PathFailureZDecodeErrorZ _res); + +/** + * Creates a new CResult_COption_PathFailureZDecodeErrorZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCResult_COption_PathFailureZDecodeErrorZ CResult_COption_PathFailureZDecodeErrorZ_clone(const struct LDKCResult_COption_PathFailureZDecodeErrorZ *NONNULL_PTR orig); + /** * Constructs a new COption_ClosureReasonZ containing a crate::lightning::util::events::ClosureReason */ @@ -15737,27 +16379,6 @@ void COption_u128Z_free(struct LDKCOption_u128Z _res); */ struct LDKCOption_u128Z COption_u128Z_clone(const struct LDKCOption_u128Z *NONNULL_PTR orig); -/** - * Constructs a new COption_NetworkUpdateZ containing a crate::lightning::routing::gossip::NetworkUpdate - */ -struct LDKCOption_NetworkUpdateZ COption_NetworkUpdateZ_some(struct LDKNetworkUpdate o); - -/** - * Constructs a new COption_NetworkUpdateZ containing nothing - */ -struct LDKCOption_NetworkUpdateZ COption_NetworkUpdateZ_none(void); - -/** - * Frees any resources associated with the crate::lightning::routing::gossip::NetworkUpdate, if we are in the Some state - */ -void COption_NetworkUpdateZ_free(struct LDKCOption_NetworkUpdateZ _res); - -/** - * Creates a new COption_NetworkUpdateZ which has the same data as `orig` - * but with all dynamically-allocated buffers duplicated in new buffers. - */ -struct LDKCOption_NetworkUpdateZ COption_NetworkUpdateZ_clone(const struct LDKCOption_NetworkUpdateZ *NONNULL_PTR orig); - /** * Frees the buffer pointed to by `data` if `datalen` is non-0. */ @@ -15815,32 +16436,6 @@ struct LDKCResult_COption_EventZDecodeErrorZ CResult_COption_EventZDecodeErrorZ_ */ void CVec_MessageSendEventZ_free(struct LDKCVec_MessageSendEventZ _res); -/** - * Creates a new CResult_TxOutAccessErrorZ in the success state. - */ -struct LDKCResult_TxOutAccessErrorZ CResult_TxOutAccessErrorZ_ok(struct LDKTxOut o); - -/** - * Creates a new CResult_TxOutAccessErrorZ in the error state. - */ -struct LDKCResult_TxOutAccessErrorZ CResult_TxOutAccessErrorZ_err(enum LDKAccessError e); - -/** - * Checks if the given object is currently in the success state - */ -bool CResult_TxOutAccessErrorZ_is_ok(const struct LDKCResult_TxOutAccessErrorZ *NONNULL_PTR o); - -/** - * Frees any resources used by the CResult_TxOutAccessErrorZ. - */ -void CResult_TxOutAccessErrorZ_free(struct LDKCResult_TxOutAccessErrorZ _res); - -/** - * Creates a new CResult_TxOutAccessErrorZ which has the same data as `orig` - * but with all dynamically-allocated buffers duplicated in new buffers. - */ -struct LDKCResult_TxOutAccessErrorZ CResult_TxOutAccessErrorZ_clone(const struct LDKCResult_TxOutAccessErrorZ *NONNULL_PTR orig); - /** * Creates a new tuple which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. @@ -15972,6 +16567,59 @@ void COption_C2Tuple_u64u64ZZ_free(struct LDKCOption_C2Tuple_u64u64ZZ _res); */ struct LDKCOption_C2Tuple_u64u64ZZ COption_C2Tuple_u64u64ZZ_clone(const struct LDKCOption_C2Tuple_u64u64ZZ *NONNULL_PTR orig); +/** + * Creates a new tuple which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKC2Tuple_Z C2Tuple_Z_clone(const struct LDKC2Tuple_Z *NONNULL_PTR orig); + +/** + * Creates a new C2Tuple_Z from the contained elements. + */ +struct LDKC2Tuple_Z C2Tuple_Z_new(struct LDKEightU16s a, struct LDKEightU16s b); + +/** + * Frees any resources used by the C2Tuple_Z. + */ +void C2Tuple_Z_free(struct LDKC2Tuple_Z _res); + +/** + * Creates a new tuple which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKC2Tuple__u168_u168Z C2Tuple__u168_u168Z_clone(const struct LDKC2Tuple__u168_u168Z *NONNULL_PTR orig); + +/** + * Creates a new C2Tuple__u168_u168Z from the contained elements. + */ +struct LDKC2Tuple__u168_u168Z C2Tuple__u168_u168Z_new(struct LDKEightU16s a, struct LDKEightU16s b); + +/** + * Frees any resources used by the C2Tuple__u168_u168Z. + */ +void C2Tuple__u168_u168Z_free(struct LDKC2Tuple__u168_u168Z _res); + +/** + * Constructs a new COption_C2Tuple_EightU16sEightU16sZZ containing a crate::c_types::derived::C2Tuple__u168_u168Z + */ +struct LDKCOption_C2Tuple_EightU16sEightU16sZZ COption_C2Tuple_EightU16sEightU16sZZ_some(struct LDKC2Tuple__u168_u168Z o); + +/** + * Constructs a new COption_C2Tuple_EightU16sEightU16sZZ containing nothing + */ +struct LDKCOption_C2Tuple_EightU16sEightU16sZZ COption_C2Tuple_EightU16sEightU16sZZ_none(void); + +/** + * Frees any resources associated with the crate::c_types::derived::C2Tuple__u168_u168Z, if we are in the Some state + */ +void COption_C2Tuple_EightU16sEightU16sZZ_free(struct LDKCOption_C2Tuple_EightU16sEightU16sZZ _res); + +/** + * Creates a new COption_C2Tuple_EightU16sEightU16sZZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCOption_C2Tuple_EightU16sEightU16sZZ COption_C2Tuple_EightU16sEightU16sZZ_clone(const struct LDKCOption_C2Tuple_EightU16sEightU16sZZ *NONNULL_PTR orig); + /** * Frees the buffer pointed to by `data` if `datalen` is non-0. */ @@ -16102,82 +16750,56 @@ void CResult_InvoiceFeaturesDecodeErrorZ_free(struct LDKCResult_InvoiceFeaturesD struct LDKCResult_InvoiceFeaturesDecodeErrorZ CResult_InvoiceFeaturesDecodeErrorZ_clone(const struct LDKCResult_InvoiceFeaturesDecodeErrorZ *NONNULL_PTR orig); /** - * Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ in the success state. - */ -struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ CResult_ChannelTypeFeaturesDecodeErrorZ_ok(struct LDKChannelTypeFeatures o); - -/** - * Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ in the error state. - */ -struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ CResult_ChannelTypeFeaturesDecodeErrorZ_err(struct LDKDecodeError e); - -/** - * Checks if the given object is currently in the success state - */ -bool CResult_ChannelTypeFeaturesDecodeErrorZ_is_ok(const struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ *NONNULL_PTR o); - -/** - * Frees any resources used by the CResult_ChannelTypeFeaturesDecodeErrorZ. - */ -void CResult_ChannelTypeFeaturesDecodeErrorZ_free(struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ _res); - -/** - * Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ which has the same data as `orig` - * but with all dynamically-allocated buffers duplicated in new buffers. - */ -struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ CResult_ChannelTypeFeaturesDecodeErrorZ_clone(const struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ *NONNULL_PTR orig); - -/** - * Creates a new CResult_OfferFeaturesDecodeErrorZ in the success state. + * Creates a new CResult_BlindedHopFeaturesDecodeErrorZ in the success state. */ -struct LDKCResult_OfferFeaturesDecodeErrorZ CResult_OfferFeaturesDecodeErrorZ_ok(struct LDKOfferFeatures o); +struct LDKCResult_BlindedHopFeaturesDecodeErrorZ CResult_BlindedHopFeaturesDecodeErrorZ_ok(struct LDKBlindedHopFeatures o); /** - * Creates a new CResult_OfferFeaturesDecodeErrorZ in the error state. + * Creates a new CResult_BlindedHopFeaturesDecodeErrorZ in the error state. */ -struct LDKCResult_OfferFeaturesDecodeErrorZ CResult_OfferFeaturesDecodeErrorZ_err(struct LDKDecodeError e); +struct LDKCResult_BlindedHopFeaturesDecodeErrorZ CResult_BlindedHopFeaturesDecodeErrorZ_err(struct LDKDecodeError e); /** * Checks if the given object is currently in the success state */ -bool CResult_OfferFeaturesDecodeErrorZ_is_ok(const struct LDKCResult_OfferFeaturesDecodeErrorZ *NONNULL_PTR o); +bool CResult_BlindedHopFeaturesDecodeErrorZ_is_ok(const struct LDKCResult_BlindedHopFeaturesDecodeErrorZ *NONNULL_PTR o); /** - * Frees any resources used by the CResult_OfferFeaturesDecodeErrorZ. + * Frees any resources used by the CResult_BlindedHopFeaturesDecodeErrorZ. */ -void CResult_OfferFeaturesDecodeErrorZ_free(struct LDKCResult_OfferFeaturesDecodeErrorZ _res); +void CResult_BlindedHopFeaturesDecodeErrorZ_free(struct LDKCResult_BlindedHopFeaturesDecodeErrorZ _res); /** - * Creates a new CResult_OfferFeaturesDecodeErrorZ which has the same data as `orig` + * Creates a new CResult_BlindedHopFeaturesDecodeErrorZ which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKCResult_OfferFeaturesDecodeErrorZ CResult_OfferFeaturesDecodeErrorZ_clone(const struct LDKCResult_OfferFeaturesDecodeErrorZ *NONNULL_PTR orig); +struct LDKCResult_BlindedHopFeaturesDecodeErrorZ CResult_BlindedHopFeaturesDecodeErrorZ_clone(const struct LDKCResult_BlindedHopFeaturesDecodeErrorZ *NONNULL_PTR orig); /** - * Creates a new CResult_InvoiceRequestFeaturesDecodeErrorZ in the success state. + * Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ in the success state. */ -struct LDKCResult_InvoiceRequestFeaturesDecodeErrorZ CResult_InvoiceRequestFeaturesDecodeErrorZ_ok(struct LDKInvoiceRequestFeatures o); +struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ CResult_ChannelTypeFeaturesDecodeErrorZ_ok(struct LDKChannelTypeFeatures o); /** - * Creates a new CResult_InvoiceRequestFeaturesDecodeErrorZ in the error state. + * Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ in the error state. */ -struct LDKCResult_InvoiceRequestFeaturesDecodeErrorZ CResult_InvoiceRequestFeaturesDecodeErrorZ_err(struct LDKDecodeError e); +struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ CResult_ChannelTypeFeaturesDecodeErrorZ_err(struct LDKDecodeError e); /** * Checks if the given object is currently in the success state */ -bool CResult_InvoiceRequestFeaturesDecodeErrorZ_is_ok(const struct LDKCResult_InvoiceRequestFeaturesDecodeErrorZ *NONNULL_PTR o); +bool CResult_ChannelTypeFeaturesDecodeErrorZ_is_ok(const struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ *NONNULL_PTR o); /** - * Frees any resources used by the CResult_InvoiceRequestFeaturesDecodeErrorZ. + * Frees any resources used by the CResult_ChannelTypeFeaturesDecodeErrorZ. */ -void CResult_InvoiceRequestFeaturesDecodeErrorZ_free(struct LDKCResult_InvoiceRequestFeaturesDecodeErrorZ _res); +void CResult_ChannelTypeFeaturesDecodeErrorZ_free(struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ _res); /** - * Creates a new CResult_InvoiceRequestFeaturesDecodeErrorZ which has the same data as `orig` + * Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKCResult_InvoiceRequestFeaturesDecodeErrorZ CResult_InvoiceRequestFeaturesDecodeErrorZ_clone(const struct LDKCResult_InvoiceRequestFeaturesDecodeErrorZ *NONNULL_PTR orig); +struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ CResult_ChannelTypeFeaturesDecodeErrorZ_clone(const struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ *NONNULL_PTR orig); /** * Creates a new CResult_NodeIdDecodeErrorZ in the success state. @@ -16232,19 +16854,19 @@ void CResult_COption_NetworkUpdateZDecodeErrorZ_free(struct LDKCResult_COption_N struct LDKCResult_COption_NetworkUpdateZDecodeErrorZ CResult_COption_NetworkUpdateZDecodeErrorZ_clone(const struct LDKCResult_COption_NetworkUpdateZDecodeErrorZ *NONNULL_PTR orig); /** - * Constructs a new COption_AccessZ containing a crate::lightning::chain::Access + * Constructs a new COption_UtxoLookupZ containing a crate::lightning::routing::utxo::UtxoLookup */ -struct LDKCOption_AccessZ COption_AccessZ_some(struct LDKAccess o); +struct LDKCOption_UtxoLookupZ COption_UtxoLookupZ_some(struct LDKUtxoLookup o); /** - * Constructs a new COption_AccessZ containing nothing + * Constructs a new COption_UtxoLookupZ containing nothing */ -struct LDKCOption_AccessZ COption_AccessZ_none(void); +struct LDKCOption_UtxoLookupZ COption_UtxoLookupZ_none(void); /** - * Frees any resources associated with the crate::lightning::chain::Access, if we are in the Some state + * Frees any resources associated with the crate::lightning::routing::utxo::UtxoLookup, if we are in the Some state */ -void COption_AccessZ_free(struct LDKCOption_AccessZ _res); +void COption_UtxoLookupZ_free(struct LDKCOption_UtxoLookupZ _res); /** * Creates a new CResult_boolLightningErrorZ in the success state. @@ -16592,169 +17214,101 @@ struct LDKCResult_StaticPaymentOutputDescriptorDecodeErrorZ CResult_StaticPaymen /** * Creates a new CResult_SpendableOutputDescriptorDecodeErrorZ in the success state. */ -struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ CResult_SpendableOutputDescriptorDecodeErrorZ_ok(struct LDKSpendableOutputDescriptor o); - -/** - * Creates a new CResult_SpendableOutputDescriptorDecodeErrorZ in the error state. - */ -struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ CResult_SpendableOutputDescriptorDecodeErrorZ_err(struct LDKDecodeError e); - -/** - * Checks if the given object is currently in the success state - */ -bool CResult_SpendableOutputDescriptorDecodeErrorZ_is_ok(const struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ *NONNULL_PTR o); - -/** - * Frees any resources used by the CResult_SpendableOutputDescriptorDecodeErrorZ. - */ -void CResult_SpendableOutputDescriptorDecodeErrorZ_free(struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ _res); - -/** - * Creates a new CResult_SpendableOutputDescriptorDecodeErrorZ which has the same data as `orig` - * but with all dynamically-allocated buffers duplicated in new buffers. - */ -struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ CResult_SpendableOutputDescriptorDecodeErrorZ_clone(const struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ *NONNULL_PTR orig); - -/** - * Frees the buffer pointed to by `data` if `datalen` is non-0. - */ -void CVec_PaymentPreimageZ_free(struct LDKCVec_PaymentPreimageZ _res); - -/** - * Creates a new tuple which has the same data as `orig` - * but with all dynamically-allocated buffers duplicated in new buffers. - */ -struct LDKC2Tuple_SignatureCVec_SignatureZZ C2Tuple_SignatureCVec_SignatureZZ_clone(const struct LDKC2Tuple_SignatureCVec_SignatureZZ *NONNULL_PTR orig); - -/** - * Creates a new C2Tuple_SignatureCVec_SignatureZZ from the contained elements. - */ -struct LDKC2Tuple_SignatureCVec_SignatureZZ C2Tuple_SignatureCVec_SignatureZZ_new(struct LDKSignature a, struct LDKCVec_SignatureZ b); - -/** - * Frees any resources used by the C2Tuple_SignatureCVec_SignatureZZ. - */ -void C2Tuple_SignatureCVec_SignatureZZ_free(struct LDKC2Tuple_SignatureCVec_SignatureZZ _res); - -/** - * Creates a new CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ in the success state. - */ -struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_ok(struct LDKC2Tuple_SignatureCVec_SignatureZZ o); - -/** - * Creates a new CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ in the error state. - */ -struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_err(void); - -/** - * Checks if the given object is currently in the success state - */ -bool CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_is_ok(const struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ *NONNULL_PTR o); - -/** - * Frees any resources used by the CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ. - */ -void CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_free(struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ _res); - -/** - * Creates a new CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ which has the same data as `orig` - * but with all dynamically-allocated buffers duplicated in new buffers. - */ -struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_clone(const struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ *NONNULL_PTR orig); - -/** - * Creates a new CResult_SignatureNoneZ in the success state. - */ -struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_ok(struct LDKSignature o); +struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ CResult_SpendableOutputDescriptorDecodeErrorZ_ok(struct LDKSpendableOutputDescriptor o); /** - * Creates a new CResult_SignatureNoneZ in the error state. + * Creates a new CResult_SpendableOutputDescriptorDecodeErrorZ in the error state. */ -struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_err(void); +struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ CResult_SpendableOutputDescriptorDecodeErrorZ_err(struct LDKDecodeError e); /** * Checks if the given object is currently in the success state */ -bool CResult_SignatureNoneZ_is_ok(const struct LDKCResult_SignatureNoneZ *NONNULL_PTR o); +bool CResult_SpendableOutputDescriptorDecodeErrorZ_is_ok(const struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ *NONNULL_PTR o); /** - * Frees any resources used by the CResult_SignatureNoneZ. + * Frees any resources used by the CResult_SpendableOutputDescriptorDecodeErrorZ. */ -void CResult_SignatureNoneZ_free(struct LDKCResult_SignatureNoneZ _res); +void CResult_SpendableOutputDescriptorDecodeErrorZ_free(struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ _res); /** - * Creates a new CResult_SignatureNoneZ which has the same data as `orig` + * Creates a new CResult_SpendableOutputDescriptorDecodeErrorZ which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_clone(const struct LDKCResult_SignatureNoneZ *NONNULL_PTR orig); +struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ CResult_SpendableOutputDescriptorDecodeErrorZ_clone(const struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ *NONNULL_PTR orig); + +/** + * Frees the buffer pointed to by `data` if `datalen` is non-0. + */ +void CVec_PaymentPreimageZ_free(struct LDKCVec_PaymentPreimageZ _res); /** * Creates a new tuple which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKC2Tuple_SignatureSignatureZ C2Tuple_SignatureSignatureZ_clone(const struct LDKC2Tuple_SignatureSignatureZ *NONNULL_PTR orig); +struct LDKC2Tuple_SignatureCVec_SignatureZZ C2Tuple_SignatureCVec_SignatureZZ_clone(const struct LDKC2Tuple_SignatureCVec_SignatureZZ *NONNULL_PTR orig); /** - * Creates a new C2Tuple_SignatureSignatureZ from the contained elements. + * Creates a new C2Tuple_SignatureCVec_SignatureZZ from the contained elements. */ -struct LDKC2Tuple_SignatureSignatureZ C2Tuple_SignatureSignatureZ_new(struct LDKSignature a, struct LDKSignature b); +struct LDKC2Tuple_SignatureCVec_SignatureZZ C2Tuple_SignatureCVec_SignatureZZ_new(struct LDKSignature a, struct LDKCVec_SignatureZ b); /** - * Frees any resources used by the C2Tuple_SignatureSignatureZ. + * Frees any resources used by the C2Tuple_SignatureCVec_SignatureZZ. */ -void C2Tuple_SignatureSignatureZ_free(struct LDKC2Tuple_SignatureSignatureZ _res); +void C2Tuple_SignatureCVec_SignatureZZ_free(struct LDKC2Tuple_SignatureCVec_SignatureZZ _res); /** - * Creates a new CResult_C2Tuple_SignatureSignatureZNoneZ in the success state. + * Creates a new CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ in the success state. */ -struct LDKCResult_C2Tuple_SignatureSignatureZNoneZ CResult_C2Tuple_SignatureSignatureZNoneZ_ok(struct LDKC2Tuple_SignatureSignatureZ o); +struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_ok(struct LDKC2Tuple_SignatureCVec_SignatureZZ o); /** - * Creates a new CResult_C2Tuple_SignatureSignatureZNoneZ in the error state. + * Creates a new CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ in the error state. */ -struct LDKCResult_C2Tuple_SignatureSignatureZNoneZ CResult_C2Tuple_SignatureSignatureZNoneZ_err(void); +struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_err(void); /** * Checks if the given object is currently in the success state */ -bool CResult_C2Tuple_SignatureSignatureZNoneZ_is_ok(const struct LDKCResult_C2Tuple_SignatureSignatureZNoneZ *NONNULL_PTR o); +bool CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_is_ok(const struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ *NONNULL_PTR o); /** - * Frees any resources used by the CResult_C2Tuple_SignatureSignatureZNoneZ. + * Frees any resources used by the CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ. */ -void CResult_C2Tuple_SignatureSignatureZNoneZ_free(struct LDKCResult_C2Tuple_SignatureSignatureZNoneZ _res); +void CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_free(struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ _res); /** - * Creates a new CResult_C2Tuple_SignatureSignatureZNoneZ which has the same data as `orig` + * Creates a new CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKCResult_C2Tuple_SignatureSignatureZNoneZ CResult_C2Tuple_SignatureSignatureZNoneZ_clone(const struct LDKCResult_C2Tuple_SignatureSignatureZNoneZ *NONNULL_PTR orig); +struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ_clone(const struct LDKCResult_C2Tuple_SignatureCVec_SignatureZZNoneZ *NONNULL_PTR orig); /** - * Creates a new CResult_SecretKeyNoneZ in the success state. + * Creates a new CResult_SignatureNoneZ in the success state. */ -struct LDKCResult_SecretKeyNoneZ CResult_SecretKeyNoneZ_ok(struct LDKSecretKey o); +struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_ok(struct LDKSignature o); /** - * Creates a new CResult_SecretKeyNoneZ in the error state. + * Creates a new CResult_SignatureNoneZ in the error state. */ -struct LDKCResult_SecretKeyNoneZ CResult_SecretKeyNoneZ_err(void); +struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_err(void); /** * Checks if the given object is currently in the success state */ -bool CResult_SecretKeyNoneZ_is_ok(const struct LDKCResult_SecretKeyNoneZ *NONNULL_PTR o); +bool CResult_SignatureNoneZ_is_ok(const struct LDKCResult_SignatureNoneZ *NONNULL_PTR o); /** - * Frees any resources used by the CResult_SecretKeyNoneZ. + * Frees any resources used by the CResult_SignatureNoneZ. */ -void CResult_SecretKeyNoneZ_free(struct LDKCResult_SecretKeyNoneZ _res); +void CResult_SignatureNoneZ_free(struct LDKCResult_SignatureNoneZ _res); /** - * Creates a new CResult_SecretKeyNoneZ which has the same data as `orig` + * Creates a new CResult_SignatureNoneZ which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKCResult_SecretKeyNoneZ CResult_SecretKeyNoneZ_clone(const struct LDKCResult_SecretKeyNoneZ *NONNULL_PTR orig); +struct LDKCResult_SignatureNoneZ CResult_SignatureNoneZ_clone(const struct LDKCResult_SignatureNoneZ *NONNULL_PTR orig); /** * Creates a new CResult_PublicKeyNoneZ in the success state. @@ -16823,26 +17377,6 @@ void CResult_SharedSecretNoneZ_free(struct LDKCResult_SharedSecretNoneZ _res); */ struct LDKCResult_SharedSecretNoneZ CResult_SharedSecretNoneZ_clone(const struct LDKCResult_SharedSecretNoneZ *NONNULL_PTR orig); -/** - * Creates a new CResult_SignDecodeErrorZ in the success state. - */ -struct LDKCResult_SignDecodeErrorZ CResult_SignDecodeErrorZ_ok(struct LDKSign o); - -/** - * Creates a new CResult_SignDecodeErrorZ in the error state. - */ -struct LDKCResult_SignDecodeErrorZ CResult_SignDecodeErrorZ_err(struct LDKDecodeError e); - -/** - * Checks if the given object is currently in the success state - */ -bool CResult_SignDecodeErrorZ_is_ok(const struct LDKCResult_SignDecodeErrorZ *NONNULL_PTR o); - -/** - * Frees any resources used by the CResult_SignDecodeErrorZ. - */ -void CResult_SignDecodeErrorZ_free(struct LDKCResult_SignDecodeErrorZ _res); - /** * Frees the buffer pointed to by `data` if `datalen` is non-0. */ @@ -16874,6 +17408,26 @@ void CResult_RecoverableSignatureNoneZ_free(struct LDKCResult_RecoverableSignatu */ struct LDKCResult_RecoverableSignatureNoneZ CResult_RecoverableSignatureNoneZ_clone(const struct LDKCResult_RecoverableSignatureNoneZ *NONNULL_PTR orig); +/** + * Creates a new CResult_WriteableEcdsaChannelSignerDecodeErrorZ in the success state. + */ +struct LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ CResult_WriteableEcdsaChannelSignerDecodeErrorZ_ok(struct LDKWriteableEcdsaChannelSigner o); + +/** + * Creates a new CResult_WriteableEcdsaChannelSignerDecodeErrorZ in the error state. + */ +struct LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ CResult_WriteableEcdsaChannelSignerDecodeErrorZ_err(struct LDKDecodeError e); + +/** + * Checks if the given object is currently in the success state + */ +bool CResult_WriteableEcdsaChannelSignerDecodeErrorZ_is_ok(const struct LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ *NONNULL_PTR o); + +/** + * Frees any resources used by the CResult_WriteableEcdsaChannelSignerDecodeErrorZ. + */ +void CResult_WriteableEcdsaChannelSignerDecodeErrorZ_free(struct LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ _res); + /** * Frees the buffer pointed to by `data` if `datalen` is non-0. */ @@ -17024,92 +17578,87 @@ void COption_u16Z_free(struct LDKCOption_u16Z _res); struct LDKCOption_u16Z COption_u16Z_clone(const struct LDKCOption_u16Z *NONNULL_PTR orig); /** - * Creates a new CResult_NoneAPIErrorZ in the success state. + * Creates a new CResult__u832APIErrorZ in the success state. */ -struct LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_ok(void); +struct LDKCResult__u832APIErrorZ CResult__u832APIErrorZ_ok(struct LDKThirtyTwoBytes o); /** - * Creates a new CResult_NoneAPIErrorZ in the error state. + * Creates a new CResult__u832APIErrorZ in the error state. */ -struct LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_err(struct LDKAPIError e); +struct LDKCResult__u832APIErrorZ CResult__u832APIErrorZ_err(struct LDKAPIError e); /** * Checks if the given object is currently in the success state */ -bool CResult_NoneAPIErrorZ_is_ok(const struct LDKCResult_NoneAPIErrorZ *NONNULL_PTR o); +bool CResult__u832APIErrorZ_is_ok(const struct LDKCResult__u832APIErrorZ *NONNULL_PTR o); /** - * Frees any resources used by the CResult_NoneAPIErrorZ. + * Frees any resources used by the CResult__u832APIErrorZ. */ -void CResult_NoneAPIErrorZ_free(struct LDKCResult_NoneAPIErrorZ _res); +void CResult__u832APIErrorZ_free(struct LDKCResult__u832APIErrorZ _res); /** - * Creates a new CResult_NoneAPIErrorZ which has the same data as `orig` + * Creates a new CResult__u832APIErrorZ which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKCResult_NoneAPIErrorZ CResult_NoneAPIErrorZ_clone(const struct LDKCResult_NoneAPIErrorZ *NONNULL_PTR orig); - -/** - * Frees the buffer pointed to by `data` if `datalen` is non-0. - */ -void CVec_CResult_NoneAPIErrorZZ_free(struct LDKCVec_CResult_NoneAPIErrorZZ _res); +struct LDKCResult__u832APIErrorZ CResult__u832APIErrorZ_clone(const struct LDKCResult__u832APIErrorZ *NONNULL_PTR orig); /** * Frees the buffer pointed to by `data` if `datalen` is non-0. */ -void CVec_APIErrorZ_free(struct LDKCVec_APIErrorZ _res); +void CVec_RecentPaymentDetailsZ_free(struct LDKCVec_RecentPaymentDetailsZ _res); /** - * Creates a new CResult__u832APIErrorZ in the success state. + * Creates a new CResult_NonePaymentSendFailureZ in the success state. */ -struct LDKCResult__u832APIErrorZ CResult__u832APIErrorZ_ok(struct LDKThirtyTwoBytes o); +struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_ok(void); /** - * Creates a new CResult__u832APIErrorZ in the error state. + * Creates a new CResult_NonePaymentSendFailureZ in the error state. */ -struct LDKCResult__u832APIErrorZ CResult__u832APIErrorZ_err(struct LDKAPIError e); +struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_err(struct LDKPaymentSendFailure e); /** * Checks if the given object is currently in the success state */ -bool CResult__u832APIErrorZ_is_ok(const struct LDKCResult__u832APIErrorZ *NONNULL_PTR o); +bool CResult_NonePaymentSendFailureZ_is_ok(const struct LDKCResult_NonePaymentSendFailureZ *NONNULL_PTR o); /** - * Frees any resources used by the CResult__u832APIErrorZ. + * Frees any resources used by the CResult_NonePaymentSendFailureZ. */ -void CResult__u832APIErrorZ_free(struct LDKCResult__u832APIErrorZ _res); +void CResult_NonePaymentSendFailureZ_free(struct LDKCResult_NonePaymentSendFailureZ _res); /** - * Creates a new CResult__u832APIErrorZ which has the same data as `orig` + * Creates a new CResult_NonePaymentSendFailureZ which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKCResult__u832APIErrorZ CResult__u832APIErrorZ_clone(const struct LDKCResult__u832APIErrorZ *NONNULL_PTR orig); +struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_clone(const struct LDKCResult_NonePaymentSendFailureZ *NONNULL_PTR orig); /** - * Creates a new CResult_NonePaymentSendFailureZ in the success state. + * Creates a new CResult_NoneRetryableSendFailureZ in the success state. */ -struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_ok(void); +struct LDKCResult_NoneRetryableSendFailureZ CResult_NoneRetryableSendFailureZ_ok(void); /** - * Creates a new CResult_NonePaymentSendFailureZ in the error state. + * Creates a new CResult_NoneRetryableSendFailureZ in the error state. */ -struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_err(struct LDKPaymentSendFailure e); +struct LDKCResult_NoneRetryableSendFailureZ CResult_NoneRetryableSendFailureZ_err(enum LDKRetryableSendFailure e); /** * Checks if the given object is currently in the success state */ -bool CResult_NonePaymentSendFailureZ_is_ok(const struct LDKCResult_NonePaymentSendFailureZ *NONNULL_PTR o); +bool CResult_NoneRetryableSendFailureZ_is_ok(const struct LDKCResult_NoneRetryableSendFailureZ *NONNULL_PTR o); /** - * Frees any resources used by the CResult_NonePaymentSendFailureZ. + * Frees any resources used by the CResult_NoneRetryableSendFailureZ. */ -void CResult_NonePaymentSendFailureZ_free(struct LDKCResult_NonePaymentSendFailureZ _res); +void CResult_NoneRetryableSendFailureZ_free(struct LDKCResult_NoneRetryableSendFailureZ _res); /** - * Creates a new CResult_NonePaymentSendFailureZ which has the same data as `orig` + * Creates a new CResult_NoneRetryableSendFailureZ which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. */ -struct LDKCResult_NonePaymentSendFailureZ CResult_NonePaymentSendFailureZ_clone(const struct LDKCResult_NonePaymentSendFailureZ *NONNULL_PTR orig); +struct LDKCResult_NoneRetryableSendFailureZ CResult_NoneRetryableSendFailureZ_clone(const struct LDKCResult_NoneRetryableSendFailureZ *NONNULL_PTR orig); /** * Creates a new CResult_PaymentHashPaymentSendFailureZ in the success state. @@ -17137,6 +17686,32 @@ void CResult_PaymentHashPaymentSendFailureZ_free(struct LDKCResult_PaymentHashPa */ struct LDKCResult_PaymentHashPaymentSendFailureZ CResult_PaymentHashPaymentSendFailureZ_clone(const struct LDKCResult_PaymentHashPaymentSendFailureZ *NONNULL_PTR orig); +/** + * Creates a new CResult_PaymentHashRetryableSendFailureZ in the success state. + */ +struct LDKCResult_PaymentHashRetryableSendFailureZ CResult_PaymentHashRetryableSendFailureZ_ok(struct LDKThirtyTwoBytes o); + +/** + * Creates a new CResult_PaymentHashRetryableSendFailureZ in the error state. + */ +struct LDKCResult_PaymentHashRetryableSendFailureZ CResult_PaymentHashRetryableSendFailureZ_err(enum LDKRetryableSendFailure e); + +/** + * Checks if the given object is currently in the success state + */ +bool CResult_PaymentHashRetryableSendFailureZ_is_ok(const struct LDKCResult_PaymentHashRetryableSendFailureZ *NONNULL_PTR o); + +/** + * Frees any resources used by the CResult_PaymentHashRetryableSendFailureZ. + */ +void CResult_PaymentHashRetryableSendFailureZ_free(struct LDKCResult_PaymentHashRetryableSendFailureZ _res); + +/** + * Creates a new CResult_PaymentHashRetryableSendFailureZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCResult_PaymentHashRetryableSendFailureZ CResult_PaymentHashRetryableSendFailureZ_clone(const struct LDKCResult_PaymentHashRetryableSendFailureZ *NONNULL_PTR orig); + /** * Creates a new tuple which has the same data as `orig` * but with all dynamically-allocated buffers duplicated in new buffers. @@ -17495,6 +18070,53 @@ void CResult_ChannelConfigDecodeErrorZ_free(struct LDKCResult_ChannelConfigDecod */ struct LDKCResult_ChannelConfigDecodeErrorZ CResult_ChannelConfigDecodeErrorZ_clone(const struct LDKCResult_ChannelConfigDecodeErrorZ *NONNULL_PTR orig); +/** + * Constructs a new COption_APIErrorZ containing a crate::lightning::util::errors::APIError + */ +struct LDKCOption_APIErrorZ COption_APIErrorZ_some(struct LDKAPIError o); + +/** + * Constructs a new COption_APIErrorZ containing nothing + */ +struct LDKCOption_APIErrorZ COption_APIErrorZ_none(void); + +/** + * Frees any resources associated with the crate::lightning::util::errors::APIError, if we are in the Some state + */ +void COption_APIErrorZ_free(struct LDKCOption_APIErrorZ _res); + +/** + * Creates a new COption_APIErrorZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCOption_APIErrorZ COption_APIErrorZ_clone(const struct LDKCOption_APIErrorZ *NONNULL_PTR orig); + +/** + * Creates a new CResult_COption_APIErrorZDecodeErrorZ in the success state. + */ +struct LDKCResult_COption_APIErrorZDecodeErrorZ CResult_COption_APIErrorZDecodeErrorZ_ok(struct LDKCOption_APIErrorZ o); + +/** + * Creates a new CResult_COption_APIErrorZDecodeErrorZ in the error state. + */ +struct LDKCResult_COption_APIErrorZDecodeErrorZ CResult_COption_APIErrorZDecodeErrorZ_err(struct LDKDecodeError e); + +/** + * Checks if the given object is currently in the success state + */ +bool CResult_COption_APIErrorZDecodeErrorZ_is_ok(const struct LDKCResult_COption_APIErrorZDecodeErrorZ *NONNULL_PTR o); + +/** + * Frees any resources used by the CResult_COption_APIErrorZDecodeErrorZ. + */ +void CResult_COption_APIErrorZDecodeErrorZ_free(struct LDKCResult_COption_APIErrorZDecodeErrorZ _res); + +/** + * Creates a new CResult_COption_APIErrorZDecodeErrorZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCResult_COption_APIErrorZDecodeErrorZ CResult_COption_APIErrorZDecodeErrorZ_clone(const struct LDKCResult_COption_APIErrorZDecodeErrorZ *NONNULL_PTR orig); + /** * Creates a new CResult_OutPointDecodeErrorZ in the success state. */ @@ -17965,6 +18587,27 @@ void COption_NetAddressZ_free(struct LDKCOption_NetAddressZ _res); */ struct LDKCOption_NetAddressZ COption_NetAddressZ_clone(const struct LDKCOption_NetAddressZ *NONNULL_PTR orig); +/** + * Creates a new tuple which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKC2Tuple_PublicKeyCOption_NetAddressZZ C2Tuple_PublicKeyCOption_NetAddressZZ_clone(const struct LDKC2Tuple_PublicKeyCOption_NetAddressZZ *NONNULL_PTR orig); + +/** + * Creates a new C2Tuple_PublicKeyCOption_NetAddressZZ from the contained elements. + */ +struct LDKC2Tuple_PublicKeyCOption_NetAddressZZ C2Tuple_PublicKeyCOption_NetAddressZZ_new(struct LDKPublicKey a, struct LDKCOption_NetAddressZ b); + +/** + * Frees any resources used by the C2Tuple_PublicKeyCOption_NetAddressZZ. + */ +void C2Tuple_PublicKeyCOption_NetAddressZZ_free(struct LDKC2Tuple_PublicKeyCOption_NetAddressZZ _res); + +/** + * Frees the buffer pointed to by `data` if `datalen` is non-0. + */ +void CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ_free(struct LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ _res); + /** * Creates a new CResult_CVec_u8ZPeerHandleErrorZ in the success state. */ @@ -18043,6 +18686,32 @@ void CResult_boolPeerHandleErrorZ_free(struct LDKCResult_boolPeerHandleErrorZ _r */ struct LDKCResult_boolPeerHandleErrorZ CResult_boolPeerHandleErrorZ_clone(const struct LDKCResult_boolPeerHandleErrorZ *NONNULL_PTR orig); +/** + * Creates a new CResult_TxOutUtxoLookupErrorZ in the success state. + */ +struct LDKCResult_TxOutUtxoLookupErrorZ CResult_TxOutUtxoLookupErrorZ_ok(struct LDKTxOut o); + +/** + * Creates a new CResult_TxOutUtxoLookupErrorZ in the error state. + */ +struct LDKCResult_TxOutUtxoLookupErrorZ CResult_TxOutUtxoLookupErrorZ_err(enum LDKUtxoLookupError e); + +/** + * Checks if the given object is currently in the success state + */ +bool CResult_TxOutUtxoLookupErrorZ_is_ok(const struct LDKCResult_TxOutUtxoLookupErrorZ *NONNULL_PTR o); + +/** + * Frees any resources used by the CResult_TxOutUtxoLookupErrorZ. + */ +void CResult_TxOutUtxoLookupErrorZ_free(struct LDKCResult_TxOutUtxoLookupErrorZ _res); + +/** + * Creates a new CResult_TxOutUtxoLookupErrorZ which has the same data as `orig` + * but with all dynamically-allocated buffers duplicated in new buffers. + */ +struct LDKCResult_TxOutUtxoLookupErrorZ CResult_TxOutUtxoLookupErrorZ_clone(const struct LDKCResult_TxOutUtxoLookupErrorZ *NONNULL_PTR orig); + /** * Creates a new CResult_NoneSendErrorZ in the success state. */ @@ -19385,6 +20054,12 @@ struct LDKPaymentPurpose PaymentPurpose_invoice_payment(struct LDKThirtyTwoBytes */ struct LDKPaymentPurpose PaymentPurpose_spontaneous_payment(struct LDKThirtyTwoBytes a); +/** + * Checks if two PaymentPurposes contain equal inner contents. + * This ignores pointers and is_owned flags and looks at the values in fields. + */ +bool PaymentPurpose_eq(const struct LDKPaymentPurpose *NONNULL_PTR a, const struct LDKPaymentPurpose *NONNULL_PTR b); + /** * Serialize the PaymentPurpose object into a byte array which can be read by PaymentPurpose_read */ @@ -19395,6 +20070,42 @@ struct LDKCVec_u8Z PaymentPurpose_write(const struct LDKPaymentPurpose *NONNULL_ */ struct LDKCResult_PaymentPurposeDecodeErrorZ PaymentPurpose_read(struct LDKu8slice ser); +/** + * Frees any resources used by the PathFailure + */ +void PathFailure_free(struct LDKPathFailure this_ptr); + +/** + * Creates a copy of the PathFailure + */ +struct LDKPathFailure PathFailure_clone(const struct LDKPathFailure *NONNULL_PTR orig); + +/** + * Utility method to constructs a new InitialSend-variant PathFailure + */ +struct LDKPathFailure PathFailure_initial_send(struct LDKAPIError err); + +/** + * Utility method to constructs a new OnPath-variant PathFailure + */ +struct LDKPathFailure PathFailure_on_path(struct LDKCOption_NetworkUpdateZ network_update); + +/** + * Checks if two PathFailures contain equal inner contents. + * This ignores pointers and is_owned flags and looks at the values in fields. + */ +bool PathFailure_eq(const struct LDKPathFailure *NONNULL_PTR a, const struct LDKPathFailure *NONNULL_PTR b); + +/** + * Serialize the PathFailure object into a byte array which can be read by PathFailure_read + */ +struct LDKCVec_u8Z PathFailure_write(const struct LDKPathFailure *NONNULL_PTR obj); + +/** + * Read a PathFailure from a byte array, created by PathFailure_write + */ +struct LDKCResult_COption_PathFailureZDecodeErrorZ PathFailure_read(struct LDKu8slice ser); + /** * Frees any resources used by the ClosureReason */ @@ -19550,7 +20261,7 @@ struct LDKEvent Event_payment_path_successful(struct LDKThirtyTwoBytes payment_i /** * Utility method to constructs a new PaymentPathFailed-variant Event */ -struct LDKEvent Event_payment_path_failed(struct LDKThirtyTwoBytes payment_id, struct LDKThirtyTwoBytes payment_hash, bool payment_failed_permanently, struct LDKCOption_NetworkUpdateZ network_update, bool all_paths_failed, struct LDKCVec_RouteHopZ path, struct LDKCOption_u64Z short_channel_id, struct LDKRouteParameters retry); +struct LDKEvent Event_payment_path_failed(struct LDKThirtyTwoBytes payment_id, struct LDKThirtyTwoBytes payment_hash, bool payment_failed_permanently, struct LDKPathFailure failure, struct LDKCVec_RouteHopZ path, struct LDKCOption_u64Z short_channel_id, struct LDKRouteParameters retry); /** * Utility method to constructs a new ProbeSuccessful-variant Event @@ -19607,6 +20318,12 @@ struct LDKEvent Event_open_channel_request(struct LDKThirtyTwoBytes temporary_ch */ struct LDKEvent Event_htlchandling_failed(struct LDKThirtyTwoBytes prev_channel_id, struct LDKHTLCDestination failed_next_destination); +/** + * Checks if two Events contain equal inner contents. + * This ignores pointers and is_owned flags and looks at the values in fields. + */ +bool Event_eq(const struct LDKEvent *NONNULL_PTR a, const struct LDKEvent *NONNULL_PTR b); + /** * Serialize the Event object into a byte array which can be read by Event_read */ @@ -19697,6 +20414,11 @@ struct LDKMessageSendEvent MessageSendEvent_broadcast_channel_announcement(struc */ struct LDKMessageSendEvent MessageSendEvent_broadcast_channel_update(struct LDKChannelUpdate msg); +/** + * Utility method to constructs a new BroadcastNodeAnnouncement-variant MessageSendEvent + */ +struct LDKMessageSendEvent MessageSendEvent_broadcast_node_announcement(struct LDKNodeAnnouncement msg); + /** * Utility method to constructs a new SendChannelUpdate-variant MessageSendEvent */ @@ -19793,6 +20515,16 @@ struct LDKAPIError APIError_incompatible_shutdown_script(struct LDKShutdownScrip */ bool APIError_eq(const struct LDKAPIError *NONNULL_PTR a, const struct LDKAPIError *NONNULL_PTR b); +/** + * Serialize the APIError object into a byte array which can be read by APIError_read + */ +struct LDKCVec_u8Z APIError_write(const struct LDKAPIError *NONNULL_PTR obj); + +/** + * Read a APIError from a byte array, created by APIError_write + */ +struct LDKCResult_COption_APIErrorZDecodeErrorZ APIError_read(struct LDKu8slice ser); + /** * Frees any resources used by the BigSize, if is_owned is set and inner is non-NULL. */ @@ -20241,11 +20973,11 @@ void ChannelHandshakeConfig_set_announced_channel(struct LDKChannelHandshakeConf * any attacker who is able to take control of a channel can just as easily send the funds via * lightning payments, so we never require that our counterparties support this option. * - * The upfront key committed is provided from [`KeysInterface::get_shutdown_scriptpubkey`]. + * The upfront key committed is provided from [`SignerProvider::get_shutdown_scriptpubkey`]. * * Default value: true. * - * [`KeysInterface::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::KeysInterface::get_shutdown_scriptpubkey + * [`SignerProvider::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::SignerProvider::get_shutdown_scriptpubkey */ bool ChannelHandshakeConfig_get_commit_upfront_shutdown_pubkey(const struct LDKChannelHandshakeConfig *NONNULL_PTR this_ptr); @@ -20258,11 +20990,11 @@ bool ChannelHandshakeConfig_get_commit_upfront_shutdown_pubkey(const struct LDKC * any attacker who is able to take control of a channel can just as easily send the funds via * lightning payments, so we never require that our counterparties support this option. * - * The upfront key committed is provided from [`KeysInterface::get_shutdown_scriptpubkey`]. + * The upfront key committed is provided from [`SignerProvider::get_shutdown_scriptpubkey`]. * * Default value: true. * - * [`KeysInterface::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::KeysInterface::get_shutdown_scriptpubkey + * [`SignerProvider::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::SignerProvider::get_shutdown_scriptpubkey */ void ChannelHandshakeConfig_set_commit_upfront_shutdown_pubkey(struct LDKChannelHandshakeConfig *NONNULL_PTR this_ptr, bool val); @@ -20981,42 +21713,22 @@ bool BestBlock_eq(const struct LDKBestBlock *NONNULL_PTR a, const struct LDKBest * Constructs a `BestBlock` that represents the genesis block at height 0 of the given * network. */ -MUST_USE_RES struct LDKBestBlock BestBlock_from_genesis(enum LDKNetwork network); - -/** - * Returns a `BestBlock` as identified by the given block hash and height. - */ -MUST_USE_RES struct LDKBestBlock BestBlock_new(struct LDKThirtyTwoBytes block_hash, uint32_t height); - -/** - * Returns the best block hash. - */ -MUST_USE_RES struct LDKThirtyTwoBytes BestBlock_block_hash(const struct LDKBestBlock *NONNULL_PTR this_arg); - -/** - * Returns the best block height. - */ -MUST_USE_RES uint32_t BestBlock_height(const struct LDKBestBlock *NONNULL_PTR this_arg); - -/** - * Creates a copy of the AccessError - */ -enum LDKAccessError AccessError_clone(const enum LDKAccessError *NONNULL_PTR orig); +MUST_USE_RES struct LDKBestBlock BestBlock_from_network(enum LDKNetwork network); /** - * Utility method to constructs a new UnknownChain-variant AccessError + * Returns a `BestBlock` as identified by the given block hash and height. */ -enum LDKAccessError AccessError_unknown_chain(void); +MUST_USE_RES struct LDKBestBlock BestBlock_new(struct LDKThirtyTwoBytes block_hash, uint32_t height); /** - * Utility method to constructs a new UnknownTx-variant AccessError + * Returns the best block hash. */ -enum LDKAccessError AccessError_unknown_tx(void); +MUST_USE_RES struct LDKThirtyTwoBytes BestBlock_block_hash(const struct LDKBestBlock *NONNULL_PTR this_arg); /** - * Calls the free function if one is set + * Returns the best block height. */ -void Access_free(struct LDKAccess this_ptr); +MUST_USE_RES uint32_t BestBlock_height(const struct LDKBestBlock *NONNULL_PTR this_arg); /** * Calls the free function if one is set @@ -21638,7 +22350,7 @@ MUST_USE_RES struct LDKCVec_BalanceZ ChannelMonitor_get_claimable_balances(const /** * Read a C2Tuple_BlockHashChannelMonitorZ from a byte array, created by C2Tuple_BlockHashChannelMonitorZ_write */ -struct LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ C2Tuple_BlockHashChannelMonitorZ_read(struct LDKu8slice ser, const struct LDKKeysInterface *NONNULL_PTR arg); +struct LDKCResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ C2Tuple_BlockHashChannelMonitorZ_read(struct LDKu8slice ser, const struct LDKEntropySource *NONNULL_PTR arg_a, const struct LDKSignerProvider *NONNULL_PTR arg_b); /** * Frees any resources used by the OutPoint, if is_owned is set and inner is non-NULL. @@ -21764,13 +22476,13 @@ struct LDKPublicKey DelayedPaymentOutputDescriptor_get_revocation_pubkey(const s void DelayedPaymentOutputDescriptor_set_revocation_pubkey(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKPublicKey val); /** - * Arbitrary identification information returned by a call to [`BaseSign::channel_keys_id`]. + * Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`]. * This may be useful in re-deriving keys used in the channel to spend the output. */ const uint8_t (*DelayedPaymentOutputDescriptor_get_channel_keys_id(const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr))[32]; /** - * Arbitrary identification information returned by a call to [`BaseSign::channel_keys_id`]. + * Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`]. * This may be useful in re-deriving keys used in the channel to spend the output. */ void DelayedPaymentOutputDescriptor_set_channel_keys_id(struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val); @@ -21840,13 +22552,13 @@ struct LDKTxOut StaticPaymentOutputDescriptor_get_output(const struct LDKStaticP void StaticPaymentOutputDescriptor_set_output(struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKTxOut val); /** - * Arbitrary identification information returned by a call to [`BaseSign::channel_keys_id`]. + * Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`]. * This may be useful in re-deriving keys used in the channel to spend the output. */ const uint8_t (*StaticPaymentOutputDescriptor_get_channel_keys_id(const struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr))[32]; /** - * Arbitrary identification information returned by a call to [`BaseSign::channel_keys_id`]. + * Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`]. * This may be useful in re-deriving keys used in the channel to spend the output. */ void StaticPaymentOutputDescriptor_set_channel_keys_id(struct LDKStaticPaymentOutputDescriptor *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val); @@ -21932,12 +22644,17 @@ struct LDKCResult_SpendableOutputDescriptorDecodeErrorZ SpendableOutputDescripto /** * Calls the free function if one is set */ -void BaseSign_free(struct LDKBaseSign this_ptr); +void ChannelSigner_free(struct LDKChannelSigner this_ptr); + +/** + * Calls the free function if one is set + */ +void EcdsaChannelSigner_free(struct LDKEcdsaChannelSigner this_ptr); /** * Calls the free function if one is set */ -void Sign_free(struct LDKSign this_ptr); +void WriteableEcdsaChannelSigner_free(struct LDKWriteableEcdsaChannelSigner this_ptr); /** * Creates a copy of the Recipient @@ -21957,7 +22674,17 @@ enum LDKRecipient Recipient_phantom_node(void); /** * Calls the free function if one is set */ -void KeysInterface_free(struct LDKKeysInterface this_ptr); +void EntropySource_free(struct LDKEntropySource this_ptr); + +/** + * Calls the free function if one is set + */ +void NodeSigner_free(struct LDKNodeSigner this_ptr); + +/** + * Calls the free function if one is set + */ +void SignerProvider_free(struct LDKSignerProvider this_ptr); /** * Frees any resources used by the InMemorySigner, if is_owned is set and inner is non-NULL. @@ -22034,12 +22761,12 @@ struct LDKInMemorySigner InMemorySigner_clone(const struct LDKInMemorySigner *NO /** * Creates a new [`InMemorySigner`]. */ -MUST_USE_RES struct LDKInMemorySigner InMemorySigner_new(struct LDKSecretKey node_secret, struct LDKSecretKey funding_key, struct LDKSecretKey revocation_base_key, struct LDKSecretKey payment_key, struct LDKSecretKey delayed_payment_base_key, struct LDKSecretKey htlc_base_key, struct LDKThirtyTwoBytes commitment_seed, uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id); +MUST_USE_RES struct LDKInMemorySigner InMemorySigner_new(struct LDKSecretKey funding_key, struct LDKSecretKey revocation_base_key, struct LDKSecretKey payment_key, struct LDKSecretKey delayed_payment_base_key, struct LDKSecretKey htlc_base_key, struct LDKThirtyTwoBytes commitment_seed, uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id); /** * Returns the counterparty's pubkeys. * - * Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. + * Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. */ MUST_USE_RES struct LDKChannelPublicKeys InMemorySigner_counterparty_pubkeys(const struct LDKInMemorySigner *NONNULL_PTR this_arg); @@ -22048,7 +22775,7 @@ MUST_USE_RES struct LDKChannelPublicKeys InMemorySigner_counterparty_pubkeys(con * transactions, i.e., the amount of time that we have to wait to recover our funds if we * broadcast a transaction. * - * Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. + * Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. */ MUST_USE_RES uint16_t InMemorySigner_counterparty_selected_contest_delay(const struct LDKInMemorySigner *NONNULL_PTR this_arg); @@ -22057,21 +22784,21 @@ MUST_USE_RES uint16_t InMemorySigner_counterparty_selected_contest_delay(const s * by our counterparty, i.e., the amount of time that they have to wait to recover their funds * if they broadcast a transaction. * - * Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. + * Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. */ MUST_USE_RES uint16_t InMemorySigner_holder_selected_contest_delay(const struct LDKInMemorySigner *NONNULL_PTR this_arg); /** * Returns whether the holder is the initiator. * - * Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. + * Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. */ MUST_USE_RES bool InMemorySigner_is_outbound(const struct LDKInMemorySigner *NONNULL_PTR this_arg); /** * Funding outpoint * - * Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. + * Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. */ MUST_USE_RES struct LDKOutPoint InMemorySigner_funding_outpoint(const struct LDKInMemorySigner *NONNULL_PTR this_arg); @@ -22079,14 +22806,14 @@ MUST_USE_RES struct LDKOutPoint InMemorySigner_funding_outpoint(const struct LDK * Returns a [`ChannelTransactionParameters`] for this channel, to be used when verifying or * building transactions. * - * Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. + * Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. */ MUST_USE_RES struct LDKChannelTransactionParameters InMemorySigner_get_channel_parameters(const struct LDKInMemorySigner *NONNULL_PTR this_arg); /** * Returns whether anchors should be used. * - * Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. + * Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. */ MUST_USE_RES bool InMemorySigner_opt_anchors(const struct LDKInMemorySigner *NONNULL_PTR this_arg); @@ -22117,16 +22844,22 @@ MUST_USE_RES struct LDKCResult_CVec_CVec_u8ZZNoneZ InMemorySigner_sign_counterpa MUST_USE_RES struct LDKCResult_CVec_CVec_u8ZZNoneZ InMemorySigner_sign_dynamic_p2wsh_input(const struct LDKInMemorySigner *NONNULL_PTR this_arg, struct LDKTransaction spend_tx, uintptr_t input_idx, const struct LDKDelayedPaymentOutputDescriptor *NONNULL_PTR descriptor); /** - * Constructs a new BaseSign which calls the relevant methods on this_arg. - * This copies the `inner` pointer in this_arg and thus the returned BaseSign must be freed before this_arg is + * Constructs a new ChannelSigner which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned ChannelSigner must be freed before this_arg is + */ +struct LDKChannelSigner InMemorySigner_as_ChannelSigner(const struct LDKInMemorySigner *NONNULL_PTR this_arg); + +/** + * Constructs a new EcdsaChannelSigner which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned EcdsaChannelSigner must be freed before this_arg is */ -struct LDKBaseSign InMemorySigner_as_BaseSign(const struct LDKInMemorySigner *NONNULL_PTR this_arg); +struct LDKEcdsaChannelSigner InMemorySigner_as_EcdsaChannelSigner(const struct LDKInMemorySigner *NONNULL_PTR this_arg); /** - * Constructs a new Sign which calls the relevant methods on this_arg. - * This copies the `inner` pointer in this_arg and thus the returned Sign must be freed before this_arg is + * Constructs a new WriteableEcdsaChannelSigner which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned WriteableEcdsaChannelSigner must be freed before this_arg is */ -struct LDKSign InMemorySigner_as_Sign(const struct LDKInMemorySigner *NONNULL_PTR this_arg); +struct LDKWriteableEcdsaChannelSigner InMemorySigner_as_WriteableEcdsaChannelSigner(const struct LDKInMemorySigner *NONNULL_PTR this_arg); /** * Serialize the InMemorySigner object into a byte array which can be read by InMemorySigner_read @@ -22136,7 +22869,7 @@ struct LDKCVec_u8Z InMemorySigner_write(const struct LDKInMemorySigner *NONNULL_ /** * Read a InMemorySigner from a byte array, created by InMemorySigner_write */ -struct LDKCResult_InMemorySignerDecodeErrorZ InMemorySigner_read(struct LDKu8slice ser, struct LDKSecretKey arg); +struct LDKCResult_InMemorySignerDecodeErrorZ InMemorySigner_read(struct LDKu8slice ser); /** * Frees any resources used by the KeysManager, if is_owned is set and inner is non-NULL. @@ -22165,7 +22898,12 @@ void KeysManager_free(struct LDKKeysManager this_obj); MUST_USE_RES struct LDKKeysManager KeysManager_new(const uint8_t (*seed)[32], uint64_t starting_time_secs, uint32_t starting_time_nanos); /** - * Derive an old [`Sign`] containing per-channel secrets based on a key derivation parameters. + * Gets the \"node_id\" secret key used to sign gossip announcements, decode onion data, etc. + */ +MUST_USE_RES struct LDKSecretKey KeysManager_get_node_secret_key(const struct LDKKeysManager *NONNULL_PTR this_arg); + +/** + * Derive an old [`WriteableEcdsaChannelSigner`] containing per-channel secrets based on a key derivation parameters. */ MUST_USE_RES struct LDKInMemorySigner KeysManager_derive_channel_keys(const struct LDKKeysManager *NONNULL_PTR this_arg, uint64_t channel_value_satoshis, const uint8_t (*params)[32]); @@ -22186,10 +22924,22 @@ MUST_USE_RES struct LDKInMemorySigner KeysManager_derive_channel_keys(const stru MUST_USE_RES struct LDKCResult_TransactionNoneZ KeysManager_spend_spendable_outputs(const struct LDKKeysManager *NONNULL_PTR this_arg, struct LDKCVec_SpendableOutputDescriptorZ descriptors, struct LDKCVec_TxOutZ outputs, struct LDKCVec_u8Z change_destination_script, uint32_t feerate_sat_per_1000_weight); /** - * Constructs a new KeysInterface which calls the relevant methods on this_arg. - * This copies the `inner` pointer in this_arg and thus the returned KeysInterface must be freed before this_arg is + * Constructs a new EntropySource which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned EntropySource must be freed before this_arg is + */ +struct LDKEntropySource KeysManager_as_EntropySource(const struct LDKKeysManager *NONNULL_PTR this_arg); + +/** + * Constructs a new NodeSigner which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned NodeSigner must be freed before this_arg is */ -struct LDKKeysInterface KeysManager_as_KeysInterface(const struct LDKKeysManager *NONNULL_PTR this_arg); +struct LDKNodeSigner KeysManager_as_NodeSigner(const struct LDKKeysManager *NONNULL_PTR this_arg); + +/** + * Constructs a new SignerProvider which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned SignerProvider must be freed before this_arg is + */ +struct LDKSignerProvider KeysManager_as_SignerProvider(const struct LDKKeysManager *NONNULL_PTR this_arg); /** * Frees any resources used by the PhantomKeysManager, if is_owned is set and inner is non-NULL. @@ -22197,10 +22947,22 @@ struct LDKKeysInterface KeysManager_as_KeysInterface(const struct LDKKeysManager void PhantomKeysManager_free(struct LDKPhantomKeysManager this_obj); /** - * Constructs a new KeysInterface which calls the relevant methods on this_arg. - * This copies the `inner` pointer in this_arg and thus the returned KeysInterface must be freed before this_arg is + * Constructs a new EntropySource which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned EntropySource must be freed before this_arg is + */ +struct LDKEntropySource PhantomKeysManager_as_EntropySource(const struct LDKPhantomKeysManager *NONNULL_PTR this_arg); + +/** + * Constructs a new NodeSigner which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned NodeSigner must be freed before this_arg is + */ +struct LDKNodeSigner PhantomKeysManager_as_NodeSigner(const struct LDKPhantomKeysManager *NONNULL_PTR this_arg); + +/** + * Constructs a new SignerProvider which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned SignerProvider must be freed before this_arg is */ -struct LDKKeysInterface PhantomKeysManager_as_KeysInterface(const struct LDKPhantomKeysManager *NONNULL_PTR this_arg); +struct LDKSignerProvider PhantomKeysManager_as_SignerProvider(const struct LDKPhantomKeysManager *NONNULL_PTR this_arg); /** * Constructs a [`PhantomKeysManager`] given a 32-byte seed and an additional `cross_node_seed` @@ -22227,6 +22989,37 @@ MUST_USE_RES struct LDKCResult_TransactionNoneZ PhantomKeysManager_spend_spendab */ MUST_USE_RES struct LDKInMemorySigner PhantomKeysManager_derive_channel_keys(const struct LDKPhantomKeysManager *NONNULL_PTR this_arg, uint64_t channel_value_satoshis, const uint8_t (*params)[32]); +/** + * Gets the \"node_id\" secret key used to sign gossip announcements, decode onion data, etc. + */ +MUST_USE_RES struct LDKSecretKey PhantomKeysManager_get_node_secret_key(const struct LDKPhantomKeysManager *NONNULL_PTR this_arg); + +/** + * Gets the \"node_id\" secret key of the phantom node used to sign invoices, decode the + * last-hop onion data, etc. + */ +MUST_USE_RES struct LDKSecretKey PhantomKeysManager_get_phantom_node_secret_key(const struct LDKPhantomKeysManager *NONNULL_PTR this_arg); + +/** + * Creates a copy of the FailureCode + */ +enum LDKFailureCode FailureCode_clone(const enum LDKFailureCode *NONNULL_PTR orig); + +/** + * Utility method to constructs a new TemporaryNodeFailure-variant FailureCode + */ +enum LDKFailureCode FailureCode_temporary_node_failure(void); + +/** + * Utility method to constructs a new RequiredNodeFeatureMissing-variant FailureCode + */ +enum LDKFailureCode FailureCode_required_node_feature_missing(void); + +/** + * Utility method to constructs a new IncorrectOrUnknownPaymentDetails-variant FailureCode + */ +enum LDKFailureCode FailureCode_incorrect_or_unknown_payment_details(void); + /** * Frees any resources used by the ChannelManager, if is_owned is set and inner is non-NULL. */ @@ -22927,39 +23720,29 @@ MUST_USE_RES struct LDKCOption_u64Z ChannelDetails_get_inbound_payment_scid(cons MUST_USE_RES struct LDKCOption_u64Z ChannelDetails_get_outbound_payment_scid(const struct LDKChannelDetails *NONNULL_PTR this_arg); /** - * Frees any resources used by the PaymentSendFailure - */ -void PaymentSendFailure_free(struct LDKPaymentSendFailure this_ptr); - -/** - * Creates a copy of the PaymentSendFailure - */ -struct LDKPaymentSendFailure PaymentSendFailure_clone(const struct LDKPaymentSendFailure *NONNULL_PTR orig); - -/** - * Utility method to constructs a new ParameterError-variant PaymentSendFailure + * Frees any resources used by the RecentPaymentDetails */ -struct LDKPaymentSendFailure PaymentSendFailure_parameter_error(struct LDKAPIError a); +void RecentPaymentDetails_free(struct LDKRecentPaymentDetails this_ptr); /** - * Utility method to constructs a new PathParameterError-variant PaymentSendFailure + * Creates a copy of the RecentPaymentDetails */ -struct LDKPaymentSendFailure PaymentSendFailure_path_parameter_error(struct LDKCVec_CResult_NoneAPIErrorZZ a); +struct LDKRecentPaymentDetails RecentPaymentDetails_clone(const struct LDKRecentPaymentDetails *NONNULL_PTR orig); /** - * Utility method to constructs a new AllFailedResendSafe-variant PaymentSendFailure + * Utility method to constructs a new Pending-variant RecentPaymentDetails */ -struct LDKPaymentSendFailure PaymentSendFailure_all_failed_resend_safe(struct LDKCVec_APIErrorZ a); +struct LDKRecentPaymentDetails RecentPaymentDetails_pending(struct LDKThirtyTwoBytes payment_hash, uint64_t total_msat); /** - * Utility method to constructs a new DuplicatePayment-variant PaymentSendFailure + * Utility method to constructs a new Fulfilled-variant RecentPaymentDetails */ -struct LDKPaymentSendFailure PaymentSendFailure_duplicate_payment(void); +struct LDKRecentPaymentDetails RecentPaymentDetails_fulfilled(struct LDKThirtyTwoBytes payment_hash); /** - * Utility method to constructs a new PartialFailure-variant PaymentSendFailure + * Utility method to constructs a new Abandoned-variant RecentPaymentDetails */ -struct LDKPaymentSendFailure PaymentSendFailure_partial_failure(struct LDKCVec_CResult_NoneAPIErrorZZ results, struct LDKRouteParameters failed_paths_retry, struct LDKThirtyTwoBytes payment_id); +struct LDKRecentPaymentDetails RecentPaymentDetails_abandoned(struct LDKThirtyTwoBytes payment_hash); /** * Frees any resources used by the PhantomRouteHints, if is_owned is set and inner is non-NULL. @@ -23020,7 +23803,7 @@ struct LDKPhantomRouteHints PhantomRouteHints_clone(const struct LDKPhantomRoute * disconnected using its `block_connected` and `block_disconnected` methods, starting * from after `params.latest_hash`. */ -MUST_USE_RES struct LDKChannelManager ChannelManager_new(struct LDKFeeEstimator fee_est, struct LDKWatch chain_monitor, struct LDKBroadcasterInterface tx_broadcaster, struct LDKLogger logger, struct LDKKeysInterface keys_manager, struct LDKUserConfig config, struct LDKChainParameters params); +MUST_USE_RES struct LDKChannelManager ChannelManager_new(struct LDKFeeEstimator fee_est, struct LDKWatch chain_monitor, struct LDKBroadcasterInterface tx_broadcaster, struct LDKRouter router, struct LDKLogger logger, struct LDKEntropySource entropy_source, struct LDKNodeSigner node_signer, struct LDKSignerProvider signer_provider, struct LDKUserConfig config, struct LDKChainParameters params); /** * Gets the current configuration applied to all new channels. @@ -23065,17 +23848,27 @@ MUST_USE_RES struct LDKCResult__u832APIErrorZ ChannelManager_create_channel(cons MUST_USE_RES struct LDKCVec_ChannelDetailsZ ChannelManager_list_channels(const struct LDKChannelManager *NONNULL_PTR this_arg); /** - * Gets the list of usable channels, in random order. Useful as an argument to [`find_route`] - * to ensure non-announced channels are used. + * Gets the list of usable channels, in random order. Useful as an argument to + * [`Router::find_route`] to ensure non-announced channels are used. * * These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the * documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria * are. - * - * [`find_route`]: crate::routing::router::find_route */ MUST_USE_RES struct LDKCVec_ChannelDetailsZ ChannelManager_list_usable_channels(const struct LDKChannelManager *NONNULL_PTR this_arg); +/** + * Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a + * successful path, or have unresolved HTLCs. + * + * This can be useful for payments that may have been prepared, but ultimately not sent, as a + * result of a crash. If such a payment exists, is not listed here, and an + * [`Event::PaymentSent`] has not been received, you may consider resending the payment. + * + * [`Event::PaymentSent`]: events::Event::PaymentSent + */ +MUST_USE_RES struct LDKCVec_RecentPaymentDetailsZ ChannelManager_list_recent_payments(const struct LDKChannelManager *NONNULL_PTR this_arg); + /** * Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs * will be accepted on the given channel, and after additional timeout/the closing of all @@ -23153,14 +23946,19 @@ void ChannelManager_force_close_all_channels_without_broadcasting_txn(const stru /** * Sends a payment along a given route. * - * Value parameters are provided via the last hop in route, see documentation for RouteHop + * Value parameters are provided via the last hop in route, see documentation for [`RouteHop`] * fields for more info. * + * May generate SendHTLCs message(s) event on success, which should be relayed (e.g. via + * [`PeerManager::process_events`]). + * + * # Avoiding Duplicate Payments + * * If a pending payment is currently in-flight with the same [`PaymentId`] provided, this * method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment * is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an - * [`Event::PaymentSent`]) LDK will not stop you from sending a second payment with the same - * [`PaymentId`]. + * [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a + * second payment with the same [`PaymentId`]. * * Thus, in order to ensure duplicate payments are not sent, you should implement your own * tracking of payments, including state to indicate once a payment has completed. Because you @@ -23168,12 +23966,16 @@ void ChannelManager_force_close_all_channels_without_broadcasting_txn(const stru * consider using the [`PaymentHash`] as the key for tracking payments. In that case, the * [`PaymentId`] should be a copy of the [`PaymentHash`] bytes. * - * May generate SendHTLCs message(s) event on success, which should be relayed (e.g. via - * [`PeerManager::process_events`]). + * Additionally, in the scenario where we begin the process of sending a payment, but crash + * before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're + * using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See + * [`ChannelManager::list_recent_payments`] for more information. + * + * # Possible Error States on [`PaymentSendFailure`] * * Each path may have a different return value, and PaymentSendValue may return a Vec with * each entry matching the corresponding-index entry in the route paths, see - * PaymentSendFailure for more info. + * [`PaymentSendFailure`] for more info. * * In general, a path may raise: * * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee, @@ -23188,56 +23990,50 @@ void ChannelManager_force_close_all_channels_without_broadcasting_txn(const stru * irrevocably committed to on our end. In such a case, do NOT retry the payment with a * different route unless you intend to pay twice! * - * payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate - * the sender to the recipient and prevent payment-probing (deanonymization) attacks. For - * newer nodes, it will be provided to you in the invoice. If you do not have one, the Route - * must not contain multiple paths as multi-path payments require a recipient-provided - * payment_secret. + * # A caution on `payment_secret` * - * If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature - * bit set (either as required or as available). If multiple paths are present in the Route, - * we assume the invoice had the basic_mpp feature set. + * `payment_secret` is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to + * authenticate the sender to the recipient and prevent payment-probing (deanonymization) + * attacks. For newer nodes, it will be provided to you in the invoice. If you do not have one, + * the [`Route`] must not contain multiple paths as multi-path payments require a + * recipient-provided `payment_secret`. + * + * If a `payment_secret` *is* provided, we assume that the invoice had the payment_secret + * feature bit set (either as required or as available). If multiple paths are present in the + * [`Route`], we assume the invoice had the basic_mpp feature set. * * [`Event::PaymentSent`]: events::Event::PaymentSent + * [`Event::PaymentFailed`]: events::Event::PaymentFailed * [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events + * [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress * * Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None */ MUST_USE_RES struct LDKCResult_NonePaymentSendFailureZ ChannelManager_send_payment(const struct LDKChannelManager *NONNULL_PTR this_arg, const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_hash, struct LDKThirtyTwoBytes payment_secret, struct LDKThirtyTwoBytes payment_id); /** - * Retries a payment along the given [`Route`]. + * Similar to [`ChannelManager::send_payment`], but will automatically find a route based on + * `route_params` and retry failed payment paths based on `retry_strategy`. * - * Errors returned are a superset of those returned from [`send_payment`], so see - * [`send_payment`] documentation for more details on errors. This method will also error if the - * retry amount puts the payment more than 10% over the payment's total amount, if the payment - * for the given `payment_id` cannot be found (likely due to timeout or success), or if - * further retries have been disabled with [`abandon_payment`]. - * - * [`send_payment`]: [`ChannelManager::send_payment`] - * [`abandon_payment`]: [`ChannelManager::abandon_payment`] + * Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None */ -MUST_USE_RES struct LDKCResult_NonePaymentSendFailureZ ChannelManager_retry_payment(const struct LDKChannelManager *NONNULL_PTR this_arg, const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_id); +MUST_USE_RES struct LDKCResult_NoneRetryableSendFailureZ ChannelManager_send_payment_with_retry(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKThirtyTwoBytes payment_hash, struct LDKThirtyTwoBytes payment_secret, struct LDKThirtyTwoBytes payment_id, struct LDKRouteParameters route_params, struct LDKRetry retry_strategy); /** - * Signals that no further retries for the given payment will occur. + * Signals that no further retries for the given payment should occur. Useful if you have a + * pending outbound payment with retries remaining, but wish to stop retrying the payment before + * retries are exhausted. * - * After this method returns, no future calls to [`retry_payment`] for the given `payment_id` - * are allowed. If no [`Event::PaymentFailed`] event had been generated before, one will be - * generated as soon as there are no remaining pending HTLCs for this payment. + * If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon + * as there are no remaining pending HTLCs for this payment. * * Note that calling this method does *not* prevent a payment from succeeding. You must still * wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to * determine the ultimate status of a payment. * * If an [`Event::PaymentFailed`] event is generated and we restart without this - * [`ChannelManager`] having been persisted, the payment may still be in the pending state - * upon restart. This allows further calls to [`retry_payment`] (and requiring a second call - * to [`abandon_payment`] to mark the payment as failed again). Otherwise, future calls to - * [`retry_payment`] will fail with [`PaymentSendFailure::ParameterError`]. + * [`ChannelManager`] having been persisted, another [`Event::PaymentFailed`] may be generated. * - * [`abandon_payment`]: Self::abandon_payment - * [`retry_payment`]: Self::retry_payment * [`Event::PaymentFailed`]: events::Event::PaymentFailed * [`Event::PaymentSent`]: events::Event::PaymentSent */ @@ -23264,6 +24060,19 @@ void ChannelManager_abandon_payment(const struct LDKChannelManager *NONNULL_PTR */ MUST_USE_RES struct LDKCResult_PaymentHashPaymentSendFailureZ ChannelManager_send_spontaneous_payment(const struct LDKChannelManager *NONNULL_PTR this_arg, const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_preimage, struct LDKThirtyTwoBytes payment_id); +/** + * Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route + * based on `route_params` and retry failed payment paths based on `retry_strategy`. + * + * See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous + * payments. + * + * [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend + * + * Note that payment_preimage (or a relevant inner pointer) may be NULL or all-0s to represent None + */ +MUST_USE_RES struct LDKCResult_PaymentHashRetryableSendFailureZ ChannelManager_send_spontaneous_payment_with_retry(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKThirtyTwoBytes payment_preimage, struct LDKThirtyTwoBytes payment_id, struct LDKRouteParameters route_params, struct LDKRetry retry_strategy); + /** * Send a payment that is probing the given route for liquidity. We calculate the * [`PaymentHash`] of probes based on a static secret and a random [`PaymentId`], which allows @@ -23353,7 +24162,7 @@ MUST_USE_RES struct LDKCResult_NoneAPIErrorZ ChannelManager_update_channel_confi * [`UserConfig::accept_intercept_htlcs`]: crate::util::config::UserConfig::accept_intercept_htlcs * [`HTLCIntercepted`]: events::Event::HTLCIntercepted */ -MUST_USE_RES struct LDKCResult_NoneAPIErrorZ ChannelManager_forward_intercepted_htlc(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKThirtyTwoBytes intercept_id, const uint8_t (*next_hop_channel_id)[32], struct LDKPublicKey _next_node_id, uint64_t amt_to_forward_msat); +MUST_USE_RES struct LDKCResult_NoneAPIErrorZ ChannelManager_forward_intercepted_htlc(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKThirtyTwoBytes intercept_id, const uint8_t (*next_hop_channel_id)[32], struct LDKPublicKey next_node_id, uint64_t amt_to_forward_msat); /** * Fails the intercepted HTLC indicated by intercept_id. Should only be called in response to @@ -23384,6 +24193,7 @@ void ChannelManager_process_pending_htlc_forwards(const struct LDKChannelManager * the channel. * * Expiring a channel's previous `ChannelConfig` if necessary to only allow forwarding HTLCs * with the current `ChannelConfig`. + * * Removing peers which have disconnected but and no longer have any channels. * * Note that this may cause reentrancy through `chain::Watch::update_channel` calls or feerate * estimate fetches. @@ -23407,6 +24217,14 @@ void ChannelManager_timer_tick_occurred(const struct LDKChannelManager *NONNULL_ */ void ChannelManager_fail_htlc_backwards(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*payment_hash)[32]); +/** + * This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the + * reason for the failure. + * + * See [`FailureCode`] for valid failure codes. + */ +void ChannelManager_fail_htlc_backwards_with_reason(const struct LDKChannelManager *NONNULL_PTR this_arg, const uint8_t (*payment_hash)[32], enum LDKFailureCode failure_code); + /** * Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any * [`MessageSendEvent`]s needed to claim the payment. @@ -23483,7 +24301,8 @@ MUST_USE_RES struct LDKCResult_NoneAPIErrorZ ChannelManager_accept_inbound_chann * [`PaymentHash`] and [`PaymentPreimage`] for you. * * The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which - * will have the [`PaymentClaimable::payment_preimage`] field filled in. That should then be + * will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with + * its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be * passed directly to [`claim_funds`]. * * See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements. @@ -23498,12 +24317,17 @@ MUST_USE_RES struct LDKCResult_NoneAPIErrorZ ChannelManager_accept_inbound_chann * * Errors if `min_value_msat` is greater than total bitcoin supply. * + * If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable + * on versions of LDK prior to 0.0.114. + * * [`claim_funds`]: Self::claim_funds * [`PaymentClaimable`]: events::Event::PaymentClaimable - * [`PaymentClaimable::payment_preimage`]: events::Event::PaymentClaimable::payment_preimage + * [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose + * [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment + * [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage * [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash */ -MUST_USE_RES struct LDKCResult_C2Tuple_PaymentHashPaymentSecretZNoneZ ChannelManager_create_inbound_payment(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKCOption_u64Z min_value_msat, uint32_t invoice_expiry_delta_secs); +MUST_USE_RES struct LDKCResult_C2Tuple_PaymentHashPaymentSecretZNoneZ ChannelManager_create_inbound_payment(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKCOption_u64Z min_value_msat, uint32_t invoice_expiry_delta_secs, struct LDKCOption_u16Z min_final_cltv_expiry_delta); /** * Legacy version of [`create_inbound_payment`]. Use this method if you wish to share @@ -23547,8 +24371,8 @@ MUST_USE_RES struct LDKCResult_C2Tuple_PaymentHashPaymentSecretZAPIErrorZ Channe * If you need exact expiry semantics, you should enforce them upon receipt of * [`PaymentClaimable`]. * - * Note that invoices generated for inbound payments should have their `min_final_cltv_expiry` - * set to at least [`MIN_FINAL_CLTV_EXPIRY`]. + * Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta` + * set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. * * Note that a malicious eavesdropper can intuit whether an inbound payment was created by * `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime. @@ -23560,10 +24384,13 @@ MUST_USE_RES struct LDKCResult_C2Tuple_PaymentHashPaymentSecretZAPIErrorZ Channe * * Errors if `min_value_msat` is greater than total bitcoin supply. * + * If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable + * on versions of LDK prior to 0.0.114. + * * [`create_inbound_payment`]: Self::create_inbound_payment * [`PaymentClaimable`]: events::Event::PaymentClaimable */ -MUST_USE_RES struct LDKCResult_PaymentSecretNoneZ ChannelManager_create_inbound_payment_for_hash(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKThirtyTwoBytes payment_hash, struct LDKCOption_u64Z min_value_msat, uint32_t invoice_expiry_delta_secs); +MUST_USE_RES struct LDKCResult_PaymentSecretNoneZ ChannelManager_create_inbound_payment_for_hash(const struct LDKChannelManager *NONNULL_PTR this_arg, struct LDKThirtyTwoBytes payment_hash, struct LDKCOption_u64Z min_value_msat, uint32_t invoice_expiry_delta_secs, struct LDKCOption_u16Z min_final_cltv_expiry); /** * Legacy version of [`create_inbound_payment_for_hash`]. Use this method if you wish to share @@ -23679,28 +24506,40 @@ MUST_USE_RES struct LDKFuture ChannelManager_get_persistable_update_future(const MUST_USE_RES struct LDKBestBlock ChannelManager_current_best_block(const struct LDKChannelManager *NONNULL_PTR this_arg); /** - * Constructs a new ChannelMessageHandler which calls the relevant methods on this_arg. - * This copies the `inner` pointer in this_arg and thus the returned ChannelMessageHandler must be freed before this_arg is + * Fetches the set of [`NodeFeatures`] flags which are provided by or required by + * [`ChannelManager`]. */ -struct LDKChannelMessageHandler ChannelManager_as_ChannelMessageHandler(const struct LDKChannelManager *NONNULL_PTR this_arg); +MUST_USE_RES struct LDKNodeFeatures ChannelManager_node_features(const struct LDKChannelManager *NONNULL_PTR this_arg); /** - * Fetches the set of [`NodeFeatures`] flags which are provided by or required by + * Fetches the set of [`ChannelFeatures`] flags which are provided by or required by * [`ChannelManager`]. */ -struct LDKNodeFeatures provided_node_features(void); +MUST_USE_RES struct LDKChannelFeatures ChannelManager_channel_features(const struct LDKChannelManager *NONNULL_PTR this_arg); /** - * Fetches the set of [`ChannelFeatures`] flags which are provided by or required by + * Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by + * [`ChannelManager`]. + */ +MUST_USE_RES struct LDKChannelTypeFeatures ChannelManager_channel_type_features(const struct LDKChannelManager *NONNULL_PTR this_arg); + +/** + * Fetches the set of [`InitFeatures`] flags which are provided by or required by * [`ChannelManager`]. */ -struct LDKChannelFeatures provided_channel_features(void); +MUST_USE_RES struct LDKInitFeatures ChannelManager_init_features(const struct LDKChannelManager *NONNULL_PTR this_arg); + +/** + * Constructs a new ChannelMessageHandler which calls the relevant methods on this_arg. + * This copies the `inner` pointer in this_arg and thus the returned ChannelMessageHandler must be freed before this_arg is + */ +struct LDKChannelMessageHandler ChannelManager_as_ChannelMessageHandler(const struct LDKChannelManager *NONNULL_PTR this_arg); /** * Fetches the set of [`InitFeatures`] flags which are provided by or required by * [`ChannelManager`]. */ -struct LDKInitFeatures provided_init_features(void); +struct LDKInitFeatures provided_init_features(const struct LDKUserConfig *NONNULL_PTR _config); /** * Serialize the CounterpartyForwardingInfo object into a byte array which can be read by CounterpartyForwardingInfo_read @@ -23752,19 +24591,39 @@ struct LDKCVec_u8Z ChannelManager_write(const struct LDKChannelManager *NONNULL_ */ void ChannelManagerReadArgs_free(struct LDKChannelManagerReadArgs this_obj); +/** + * A cryptographically secure source of entropy. + */ +const struct LDKEntropySource *ChannelManagerReadArgs_get_entropy_source(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr); + +/** + * A cryptographically secure source of entropy. + */ +void ChannelManagerReadArgs_set_entropy_source(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKEntropySource val); + +/** + * A signer that is able to perform node-scoped cryptographic operations. + */ +const struct LDKNodeSigner *ChannelManagerReadArgs_get_node_signer(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr); + +/** + * A signer that is able to perform node-scoped cryptographic operations. + */ +void ChannelManagerReadArgs_set_node_signer(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKNodeSigner val); + /** * The keys provider which will give us relevant keys. Some keys will be loaded during * deserialization and KeysInterface::read_chan_signer will be used to read per-Channel * signing data. */ -const struct LDKKeysInterface *ChannelManagerReadArgs_get_keys_manager(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr); +const struct LDKSignerProvider *ChannelManagerReadArgs_get_signer_provider(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr); /** * The keys provider which will give us relevant keys. Some keys will be loaded during * deserialization and KeysInterface::read_chan_signer will be used to read per-Channel * signing data. */ -void ChannelManagerReadArgs_set_keys_manager(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKKeysInterface val); +void ChannelManagerReadArgs_set_signer_provider(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKSignerProvider val); /** * The fee_estimator for use in the ChannelManager in the future. @@ -23812,6 +24671,22 @@ const struct LDKBroadcasterInterface *ChannelManagerReadArgs_get_tx_broadcaster( */ void ChannelManagerReadArgs_set_tx_broadcaster(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKBroadcasterInterface val); +/** + * The router which will be used in the ChannelManager in the future for finding routes + * on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding. + * + * No calls to the router will be made during deserialization. + */ +const struct LDKRouter *ChannelManagerReadArgs_get_router(const struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr); + +/** + * The router which will be used in the ChannelManager in the future for finding routes + * on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding. + * + * No calls to the router will be made during deserialization. + */ +void ChannelManagerReadArgs_set_router(struct LDKChannelManagerReadArgs *NONNULL_PTR this_ptr, struct LDKRouter val); + /** * The Logger for use in the ChannelManager and which may be used to log information during * deserialization. @@ -23841,7 +24716,7 @@ void ChannelManagerReadArgs_set_default_config(struct LDKChannelManagerReadArgs * HashMap for you. This is primarily useful for C bindings where it is not practical to * populate a HashMap directly from C. */ -MUST_USE_RES struct LDKChannelManagerReadArgs ChannelManagerReadArgs_new(struct LDKKeysInterface keys_manager, struct LDKFeeEstimator fee_estimator, struct LDKWatch chain_monitor, struct LDKBroadcasterInterface tx_broadcaster, struct LDKLogger logger, struct LDKUserConfig default_config, struct LDKCVec_ChannelMonitorZ channel_monitors); +MUST_USE_RES struct LDKChannelManagerReadArgs ChannelManagerReadArgs_new(struct LDKEntropySource entropy_source, struct LDKNodeSigner node_signer, struct LDKSignerProvider signer_provider, struct LDKFeeEstimator fee_estimator, struct LDKWatch chain_monitor, struct LDKBroadcasterInterface tx_broadcaster, struct LDKRouter router, struct LDKLogger logger, struct LDKUserConfig default_config, struct LDKCVec_ChannelMonitorZ channel_monitors); /** * Read a C2Tuple_BlockHashChannelManagerZ from a byte array, created by C2Tuple_BlockHashChannelManagerZ_write @@ -23865,15 +24740,19 @@ MUST_USE_RES struct LDKExpandedKey ExpandedKey_new(const uint8_t (*key_material) * `ChannelManager` is required. Useful for generating invoices for [phantom node payments] without * a `ChannelManager`. * - * `keys` is generated by calling [`KeysInterface::get_inbound_payment_key_material`] and then + * `keys` is generated by calling [`NodeSigner::get_inbound_payment_key_material`] and then * calling [`ExpandedKey::new`] with its result. It is recommended to cache this value and not * regenerate it for each new inbound payment. * * `current_time` is a Unix timestamp representing the current time. * + * Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable + * on versions of LDK prior to 0.0.114. + * * [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager + * [`NodeSigner::get_inbound_payment_key_material`]: crate::chain::keysinterface::NodeSigner::get_inbound_payment_key_material */ -struct LDKCResult_C2Tuple_PaymentHashPaymentSecretZNoneZ create(const struct LDKExpandedKey *NONNULL_PTR keys, struct LDKCOption_u64Z min_value_msat, uint32_t invoice_expiry_delta_secs, const struct LDKKeysInterface *NONNULL_PTR keys_manager, uint64_t current_time); +struct LDKCResult_C2Tuple_PaymentHashPaymentSecretZNoneZ create(const struct LDKExpandedKey *NONNULL_PTR keys, struct LDKCOption_u64Z min_value_msat, uint32_t invoice_expiry_delta_secs, const struct LDKEntropySource *NONNULL_PTR entropy_source, uint64_t current_time, struct LDKCOption_u16Z min_final_cltv_expiry_delta); /** * Equivalent to [`crate::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash`], @@ -23882,9 +24761,12 @@ struct LDKCResult_C2Tuple_PaymentHashPaymentSecretZNoneZ create(const struct LDK * * See [`create`] for information on the `keys` and `current_time` parameters. * + * Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable + * on versions of LDK prior to 0.0.114. + * * [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager */ -struct LDKCResult_PaymentSecretNoneZ create_from_hash(const struct LDKExpandedKey *NONNULL_PTR keys, struct LDKCOption_u64Z min_value_msat, struct LDKThirtyTwoBytes payment_hash, uint32_t invoice_expiry_delta_secs, uint64_t current_time); +struct LDKCResult_PaymentSecretNoneZ create_from_hash(const struct LDKExpandedKey *NONNULL_PTR keys, struct LDKCOption_u64Z min_value_msat, struct LDKThirtyTwoBytes payment_hash, uint32_t invoice_expiry_delta_secs, uint64_t current_time, struct LDKCOption_u16Z min_final_cltv_expiry_delta); /** * Frees any resources used by the DecodeError @@ -23943,28 +24825,32 @@ bool DecodeError_eq(const struct LDKDecodeError *NONNULL_PTR a, const struct LDK void Init_free(struct LDKInit this_obj); /** - * The relevant features which the sender supports + * The relevant features which the sender supports. */ struct LDKInitFeatures Init_get_features(const struct LDKInit *NONNULL_PTR this_ptr); /** - * The relevant features which the sender supports + * The relevant features which the sender supports. */ void Init_set_features(struct LDKInit *NONNULL_PTR this_ptr, struct LDKInitFeatures val); /** - * The receipient's network address. This adds the option to report a remote IP address - * back to a connecting peer using the init message. A node can decide to use that information - * to discover a potential update to its public IPv4 address (NAT) and use - * that for a node_announcement update message containing the new address. + * The receipient's network address. + * + * This adds the option to report a remote IP address back to a connecting peer using the init + * message. A node can decide to use that information to discover a potential update to its + * public IPv4 address (NAT) and use that for a [`NodeAnnouncement`] update message containing + * the new address. */ struct LDKCOption_NetAddressZ Init_get_remote_network_address(const struct LDKInit *NONNULL_PTR this_ptr); /** - * The receipient's network address. This adds the option to report a remote IP address - * back to a connecting peer using the init message. A node can decide to use that information - * to discover a potential update to its public IPv4 address (NAT) and use - * that for a node_announcement update message containing the new address. + * The receipient's network address. + * + * This adds the option to report a remote IP address back to a connecting peer using the init + * message. A node can decide to use that information to discover a potential update to its + * public IPv4 address (NAT) and use that for a [`NodeAnnouncement`] update message containing + * the new address. */ void Init_set_remote_network_address(struct LDKInit *NONNULL_PTR this_ptr, struct LDKCOption_NetAddressZ val); @@ -24008,16 +24894,18 @@ void ErrorMessage_set_channel_id(struct LDKErrorMessage *NONNULL_PTR this_ptr, s /** * A possibly human-readable error description. - * The string should be sanitized before it is used (e.g. emitted to logs or printed to - * stdout). Otherwise, a well crafted error message may trigger a security vulnerability in + * + * The string should be sanitized before it is used (e.g., emitted to logs or printed to + * `stdout`). Otherwise, a well crafted error message may trigger a security vulnerability in * the terminal emulator or the logging subsystem. */ struct LDKStr ErrorMessage_get_data(const struct LDKErrorMessage *NONNULL_PTR this_ptr); /** * A possibly human-readable error description. - * The string should be sanitized before it is used (e.g. emitted to logs or printed to - * stdout). Otherwise, a well crafted error message may trigger a security vulnerability in + * + * The string should be sanitized before it is used (e.g., emitted to logs or printed to + * `stdout`). Otherwise, a well crafted error message may trigger a security vulnerability in * the terminal emulator or the logging subsystem. */ void ErrorMessage_set_data(struct LDKErrorMessage *NONNULL_PTR this_ptr, struct LDKStr val); @@ -24060,6 +24948,7 @@ void WarningMessage_set_channel_id(struct LDKWarningMessage *NONNULL_PTR this_pt /** * A possibly human-readable warning description. + * * The string should be sanitized before it is used (e.g. emitted to logs or printed to * stdout). Otherwise, a well crafted error message may trigger a security vulnerability in * the terminal emulator or the logging subsystem. @@ -24068,6 +24957,7 @@ struct LDKStr WarningMessage_get_data(const struct LDKWarningMessage *NONNULL_PT /** * A possibly human-readable warning description. + * * The string should be sanitized before it is used (e.g. emitted to logs or printed to * stdout). Otherwise, a well crafted error message may trigger a security vulnerability in * the terminal emulator or the logging subsystem. @@ -24097,23 +24987,25 @@ bool WarningMessage_eq(const struct LDKWarningMessage *NONNULL_PTR a, const stru void Ping_free(struct LDKPing this_obj); /** - * The desired response length + * The desired response length. */ uint16_t Ping_get_ponglen(const struct LDKPing *NONNULL_PTR this_ptr); /** - * The desired response length + * The desired response length. */ void Ping_set_ponglen(struct LDKPing *NONNULL_PTR this_ptr, uint16_t val); /** * The ping packet size. + * * This field is not sent on the wire. byteslen zeros are sent. */ uint16_t Ping_get_byteslen(const struct LDKPing *NONNULL_PTR this_ptr); /** * The ping packet size. + * * This field is not sent on the wire. byteslen zeros are sent. */ void Ping_set_byteslen(struct LDKPing *NONNULL_PTR this_ptr, uint16_t val); @@ -24142,12 +25034,14 @@ void Pong_free(struct LDKPong this_obj); /** * The pong packet size. + * * This field is not sent on the wire. byteslen zeros are sent. */ uint16_t Pong_get_byteslen(const struct LDKPong *NONNULL_PTR this_ptr); /** * The pong packet size. + * * This field is not sent on the wire. byteslen zeros are sent. */ void Pong_set_byteslen(struct LDKPong *NONNULL_PTR this_ptr, uint16_t val); @@ -24255,22 +25149,26 @@ uint64_t OpenChannel_get_htlc_minimum_msat(const struct LDKOpenChannel *NONNULL_ void OpenChannel_set_htlc_minimum_msat(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint64_t val); /** - * The feerate per 1000-weight of sender generated transactions, until updated by update_fee + * The feerate per 1000-weight of sender generated transactions, until updated by + * [`UpdateFee`] */ uint32_t OpenChannel_get_feerate_per_kw(const struct LDKOpenChannel *NONNULL_PTR this_ptr); /** - * The feerate per 1000-weight of sender generated transactions, until updated by update_fee + * The feerate per 1000-weight of sender generated transactions, until updated by + * [`UpdateFee`] */ void OpenChannel_set_feerate_per_kw(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint32_t val); /** - * The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction + * The number of blocks which the counterparty will have to wait to claim on-chain funds if + * they broadcast a commitment transaction */ uint16_t OpenChannel_get_to_self_delay(const struct LDKOpenChannel *NONNULL_PTR this_ptr); /** - * The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction + * The number of blocks which the counterparty will have to wait to claim on-chain funds if + * they broadcast a commitment transaction */ void OpenChannel_set_to_self_delay(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint16_t val); @@ -24345,28 +25243,30 @@ struct LDKPublicKey OpenChannel_get_first_per_commitment_point(const struct LDKO void OpenChannel_set_first_per_commitment_point(struct LDKOpenChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val); /** - * Channel flags + * The channel flags to be used */ uint8_t OpenChannel_get_channel_flags(const struct LDKOpenChannel *NONNULL_PTR this_ptr); /** - * Channel flags + * The channel flags to be used */ void OpenChannel_set_channel_flags(struct LDKOpenChannel *NONNULL_PTR this_ptr, uint8_t val); /** - * The channel type that this channel will represent. If none is set, we derive the channel - * type from the intersection of our feature bits with our counterparty's feature bits from - * the Init message. + * The channel type that this channel will represent + * + * If this is `None`, we derive the channel type from the intersection of our + * feature bits with our counterparty's feature bits from the [`Init`] message. * * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None */ struct LDKChannelTypeFeatures OpenChannel_get_channel_type(const struct LDKOpenChannel *NONNULL_PTR this_ptr); /** - * The channel type that this channel will represent. If none is set, we derive the channel - * type from the intersection of our feature bits with our counterparty's feature bits from - * the Init message. + * The channel type that this channel will represent + * + * If this is `None`, we derive the channel type from the intersection of our + * feature bits with our counterparty's feature bits from the [`Init`] message. * * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None */ @@ -24530,10 +25430,10 @@ struct LDKPublicKey AcceptChannel_get_first_per_commitment_point(const struct LD void AcceptChannel_set_first_per_commitment_point(struct LDKAcceptChannel *NONNULL_PTR this_ptr, struct LDKPublicKey val); /** - * The channel type that this channel will represent. If none is set, we derive the channel - * type from the intersection of our feature bits with our counterparty's feature bits from - * the Init message. + * The channel type that this channel will represent. * + * If this is `None`, we derive the channel type from the intersection of + * our feature bits with our counterparty's feature bits from the [`Init`] message. * This is required to match the equivalent field in [`OpenChannel::channel_type`]. * * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None @@ -24541,10 +25441,10 @@ void AcceptChannel_set_first_per_commitment_point(struct LDKAcceptChannel *NONNU struct LDKChannelTypeFeatures AcceptChannel_get_channel_type(const struct LDKAcceptChannel *NONNULL_PTR this_ptr); /** - * The channel type that this channel will represent. If none is set, we derive the channel - * type from the intersection of our feature bits with our counterparty's feature bits from - * the Init message. + * The channel type that this channel will represent. * + * If this is `None`, we derive the channel type from the intersection of + * our feature bits with our counterparty's feature bits from the [`Init`] message. * This is required to match the equivalent field in [`OpenChannel::channel_type`]. * * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None @@ -24693,14 +25593,18 @@ struct LDKPublicKey ChannelReady_get_next_per_commitment_point(const struct LDKC void ChannelReady_set_next_per_commitment_point(struct LDKChannelReady *NONNULL_PTR this_ptr, struct LDKPublicKey val); /** - * If set, provides a short_channel_id alias for this channel. The sender will accept payments - * to be forwarded over this SCID and forward them to this messages' recipient. + * If set, provides a `short_channel_id` alias for this channel. + * + * The sender will accept payments to be forwarded over this SCID and forward them to this + * messages' recipient. */ struct LDKCOption_u64Z ChannelReady_get_short_channel_id_alias(const struct LDKChannelReady *NONNULL_PTR this_ptr); /** - * If set, provides a short_channel_id alias for this channel. The sender will accept payments - * to be forwarded over this SCID and forward them to this messages' recipient. + * If set, provides a `short_channel_id` alias for this channel. + * + * The sender will accept payments to be forwarded over this SCID and forward them to this + * messages' recipient. */ void ChannelReady_set_short_channel_id_alias(struct LDKChannelReady *NONNULL_PTR this_ptr, struct LDKCOption_u64Z val); @@ -24738,13 +25642,15 @@ void Shutdown_set_channel_id(struct LDKShutdown *NONNULL_PTR this_ptr, struct LD /** * The destination of this peer's funds on closing. - * Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh. + * + * Must be in one of these forms: P2PKH, P2SH, P2WPKH, P2WSH, P2TR. */ struct LDKu8slice Shutdown_get_scriptpubkey(const struct LDKShutdown *NONNULL_PTR this_ptr); /** * The destination of this peer's funds on closing. - * Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh. + * + * Must be in one of these forms: P2PKH, P2SH, P2WPKH, P2WSH, P2TR. */ void Shutdown_set_scriptpubkey(struct LDKShutdown *NONNULL_PTR this_ptr, struct LDKCVec_u8Z val); @@ -25461,6 +26367,36 @@ struct LDKCVec_u8Z NetAddress_write(const struct LDKNetAddress *NONNULL_PTR obj) */ struct LDKCResult_NetAddressDecodeErrorZ NetAddress_read(struct LDKu8slice ser); +/** + * Frees any resources used by the UnsignedGossipMessage + */ +void UnsignedGossipMessage_free(struct LDKUnsignedGossipMessage this_ptr); + +/** + * Creates a copy of the UnsignedGossipMessage + */ +struct LDKUnsignedGossipMessage UnsignedGossipMessage_clone(const struct LDKUnsignedGossipMessage *NONNULL_PTR orig); + +/** + * Utility method to constructs a new ChannelAnnouncement-variant UnsignedGossipMessage + */ +struct LDKUnsignedGossipMessage UnsignedGossipMessage_channel_announcement(struct LDKUnsignedChannelAnnouncement a); + +/** + * Utility method to constructs a new ChannelUpdate-variant UnsignedGossipMessage + */ +struct LDKUnsignedGossipMessage UnsignedGossipMessage_channel_update(struct LDKUnsignedChannelUpdate a); + +/** + * Utility method to constructs a new NodeAnnouncement-variant UnsignedGossipMessage + */ +struct LDKUnsignedGossipMessage UnsignedGossipMessage_node_announcement(struct LDKUnsignedNodeAnnouncement a); + +/** + * Serialize the UnsignedGossipMessage object into a byte array which can be read by UnsignedGossipMessage_read + */ +struct LDKCVec_u8Z UnsignedGossipMessage_write(const struct LDKUnsignedGossipMessage *NONNULL_PTR obj); + /** * Frees any resources used by the UnsignedNodeAnnouncement, if is_owned is set and inner is non-NULL. */ @@ -25487,16 +26423,16 @@ uint32_t UnsignedNodeAnnouncement_get_timestamp(const struct LDKUnsignedNodeAnno void UnsignedNodeAnnouncement_set_timestamp(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, uint32_t val); /** - * The node_id this announcement originated from (don't rebroadcast the node_announcement back + * The `node_id` this announcement originated from (don't rebroadcast the `node_announcement` back * to this node). */ -struct LDKPublicKey UnsignedNodeAnnouncement_get_node_id(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr); +struct LDKNodeId UnsignedNodeAnnouncement_get_node_id(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr); /** - * The node_id this announcement originated from (don't rebroadcast the node_announcement back + * The `node_id` this announcement originated from (don't rebroadcast the `node_announcement` back * to this node). */ -void UnsignedNodeAnnouncement_set_node_id(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val); +void UnsignedNodeAnnouncement_set_node_id(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKNodeId val); /** * An RGB color for UI purposes @@ -25509,14 +26445,16 @@ const uint8_t (*UnsignedNodeAnnouncement_get_rgb(const struct LDKUnsignedNodeAnn void UnsignedNodeAnnouncement_set_rgb(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKThreeBytes val); /** - * An alias, for UI purposes. This should be sanitized before use. There is no guarantee - * of uniqueness. + * An alias, for UI purposes. + * + * This should be sanitized before use. There is no guarantee of uniqueness. */ const uint8_t (*UnsignedNodeAnnouncement_get_alias(const struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr))[32]; /** - * An alias, for UI purposes. This should be sanitized before use. There is no guarantee - * of uniqueness. + * An alias, for UI purposes. + * + * This should be sanitized before use. There is no guarantee of uniqueness. */ void UnsignedNodeAnnouncement_set_alias(struct LDKUnsignedNodeAnnouncement *NONNULL_PTR this_ptr, struct LDKThirtyTwoBytes val); @@ -25622,44 +26560,44 @@ uint64_t UnsignedChannelAnnouncement_get_short_channel_id(const struct LDKUnsign void UnsignedChannelAnnouncement_set_short_channel_id(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, uint64_t val); /** - * One of the two node_ids which are endpoints of this channel + * One of the two `node_id`s which are endpoints of this channel */ -struct LDKPublicKey UnsignedChannelAnnouncement_get_node_id_1(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr); +struct LDKNodeId UnsignedChannelAnnouncement_get_node_id_1(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr); /** - * One of the two node_ids which are endpoints of this channel + * One of the two `node_id`s which are endpoints of this channel */ -void UnsignedChannelAnnouncement_set_node_id_1(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val); +void UnsignedChannelAnnouncement_set_node_id_1(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKNodeId val); /** - * The other of the two node_ids which are endpoints of this channel + * The other of the two `node_id`s which are endpoints of this channel */ -struct LDKPublicKey UnsignedChannelAnnouncement_get_node_id_2(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr); +struct LDKNodeId UnsignedChannelAnnouncement_get_node_id_2(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr); /** - * The other of the two node_ids which are endpoints of this channel + * The other of the two `node_id`s which are endpoints of this channel */ -void UnsignedChannelAnnouncement_set_node_id_2(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val); +void UnsignedChannelAnnouncement_set_node_id_2(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKNodeId val); /** * The funding key for the first node */ -struct LDKPublicKey UnsignedChannelAnnouncement_get_bitcoin_key_1(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr); +struct LDKNodeId UnsignedChannelAnnouncement_get_bitcoin_key_1(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr); /** * The funding key for the first node */ -void UnsignedChannelAnnouncement_set_bitcoin_key_1(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val); +void UnsignedChannelAnnouncement_set_bitcoin_key_1(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKNodeId val); /** * The funding key for the second node */ -struct LDKPublicKey UnsignedChannelAnnouncement_get_bitcoin_key_2(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr); +struct LDKNodeId UnsignedChannelAnnouncement_get_bitcoin_key_2(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr); /** * The funding key for the second node */ -void UnsignedChannelAnnouncement_set_bitcoin_key_2(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKPublicKey val); +void UnsignedChannelAnnouncement_set_bitcoin_key_2(struct LDKUnsignedChannelAnnouncement *NONNULL_PTR this_ptr, struct LDKNodeId val); /** * Creates a copy of the UnsignedChannelAnnouncement @@ -25793,10 +26731,10 @@ void UnsignedChannelUpdate_set_flags(struct LDKUnsignedChannelUpdate *NONNULL_PT /** * The number of blocks such that if: * `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta` - * then we need to fail the HTLC backwards. When forwarding an HTLC, cltv_expiry_delta determines - * the outgoing HTLC's minimum cltv_expiry value -- so, if an incoming HTLC comes in with a - * cltv_expiry of 100000, and the node we're forwarding to has a cltv_expiry_delta value of 10, - * then we'll check that the outgoing HTLC's cltv_expiry value is at least 100010 before + * then we need to fail the HTLC backwards. When forwarding an HTLC, `cltv_expiry_delta` determines + * the outgoing HTLC's minimum `cltv_expiry` value -- so, if an incoming HTLC comes in with a + * `cltv_expiry` of 100000, and the node we're forwarding to has a `cltv_expiry_delta` value of 10, + * then we'll check that the outgoing HTLC's `cltv_expiry` value is at least 100010 before * forwarding. Note that the HTLC sender is the one who originally sets this value when * constructing the route. */ @@ -25805,10 +26743,10 @@ uint16_t UnsignedChannelUpdate_get_cltv_expiry_delta(const struct LDKUnsignedCha /** * The number of blocks such that if: * `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta` - * then we need to fail the HTLC backwards. When forwarding an HTLC, cltv_expiry_delta determines - * the outgoing HTLC's minimum cltv_expiry value -- so, if an incoming HTLC comes in with a - * cltv_expiry of 100000, and the node we're forwarding to has a cltv_expiry_delta value of 10, - * then we'll check that the outgoing HTLC's cltv_expiry value is at least 100010 before + * then we need to fail the HTLC backwards. When forwarding an HTLC, `cltv_expiry_delta` determines + * the outgoing HTLC's minimum `cltv_expiry` value -- so, if an incoming HTLC comes in with a + * `cltv_expiry` of 100000, and the node we're forwarding to has a `cltv_expiry_delta` value of 10, + * then we'll check that the outgoing HTLC's `cltv_expiry` value is at least 100010 before * forwarding. Note that the HTLC sender is the one who originally sets this value when * constructing the route. */ @@ -25825,12 +26763,16 @@ uint64_t UnsignedChannelUpdate_get_htlc_minimum_msat(const struct LDKUnsignedCha void UnsignedChannelUpdate_set_htlc_minimum_msat(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, uint64_t val); /** - * The maximum HTLC value incoming to sender, in milli-satoshi. Used to be optional. + * The maximum HTLC value incoming to sender, in milli-satoshi. + * + * This used to be optional. */ uint64_t UnsignedChannelUpdate_get_htlc_maximum_msat(const struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr); /** - * The maximum HTLC value incoming to sender, in milli-satoshi. Used to be optional. + * The maximum HTLC value incoming to sender, in milli-satoshi. + * + * This used to be optional. */ void UnsignedChannelUpdate_set_htlc_maximum_msat(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, uint64_t val); @@ -25856,8 +26798,9 @@ void UnsignedChannelUpdate_set_fee_proportional_millionths(struct LDKUnsignedCha /** * Excess data which was signed as a part of the message which we do not (yet) understand how - * to decode. This is stored to ensure forward-compatibility as new fields are added to the - * lightning gossip + * to decode. + * + * This is stored to ensure forward-compatibility as new fields are added to the lightning gossip protocol. * * Returns a copy of the field. */ @@ -25865,8 +26808,9 @@ struct LDKCVec_u8Z UnsignedChannelUpdate_get_excess_data(const struct LDKUnsigne /** * Excess data which was signed as a part of the message which we do not (yet) understand how - * to decode. This is stored to ensure forward-compatibility as new fields are added to the - * lightning gossip + * to decode. + * + * This is stored to ensure forward-compatibility as new fields are added to the lightning gossip protocol. */ void UnsignedChannelUpdate_set_excess_data(struct LDKUnsignedChannelUpdate *NONNULL_PTR this_ptr, struct LDKCVec_u8Z val); @@ -26027,14 +26971,14 @@ bool ReplyChannelRange_get_sync_complete(const struct LDKReplyChannelRange *NONN void ReplyChannelRange_set_sync_complete(struct LDKReplyChannelRange *NONNULL_PTR this_ptr, bool val); /** - * The short_channel_ids in the channel range + * The `short_channel_id`s in the channel range * * Returns a copy of the field. */ struct LDKCVec_u64Z ReplyChannelRange_get_short_channel_ids(const struct LDKReplyChannelRange *NONNULL_PTR this_ptr); /** - * The short_channel_ids in the channel range + * The `short_channel_id`s in the channel range */ void ReplyChannelRange_set_short_channel_ids(struct LDKReplyChannelRange *NONNULL_PTR this_ptr, struct LDKCVec_u64Z val); @@ -26116,13 +27060,13 @@ void ReplyShortChannelIdsEnd_set_chain_hash(struct LDKReplyShortChannelIdsEnd *N /** * Indicates if the query recipient maintains up-to-date channel - * information for the chain_hash + * information for the `chain_hash` */ bool ReplyShortChannelIdsEnd_get_full_information(const struct LDKReplyShortChannelIdsEnd *NONNULL_PTR this_ptr); /** * Indicates if the query recipient maintains up-to-date channel - * information for the chain_hash + * information for the `chain_hash` */ void ReplyShortChannelIdsEnd_set_full_information(struct LDKReplyShortChannelIdsEnd *NONNULL_PTR this_ptr, bool val); @@ -26276,66 +27220,66 @@ struct LDKLightningError LightningError_clone(const struct LDKLightningError *NO void CommitmentUpdate_free(struct LDKCommitmentUpdate this_obj); /** - * update_add_htlc messages which should be sent + * `update_add_htlc` messages which should be sent */ struct LDKCVec_UpdateAddHTLCZ CommitmentUpdate_get_update_add_htlcs(const struct LDKCommitmentUpdate *NONNULL_PTR this_ptr); /** - * update_add_htlc messages which should be sent + * `update_add_htlc` messages which should be sent */ void CommitmentUpdate_set_update_add_htlcs(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCVec_UpdateAddHTLCZ val); /** - * update_fulfill_htlc messages which should be sent + * `update_fulfill_htlc` messages which should be sent */ struct LDKCVec_UpdateFulfillHTLCZ CommitmentUpdate_get_update_fulfill_htlcs(const struct LDKCommitmentUpdate *NONNULL_PTR this_ptr); /** - * update_fulfill_htlc messages which should be sent + * `update_fulfill_htlc` messages which should be sent */ void CommitmentUpdate_set_update_fulfill_htlcs(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCVec_UpdateFulfillHTLCZ val); /** - * update_fail_htlc messages which should be sent + * `update_fail_htlc` messages which should be sent */ struct LDKCVec_UpdateFailHTLCZ CommitmentUpdate_get_update_fail_htlcs(const struct LDKCommitmentUpdate *NONNULL_PTR this_ptr); /** - * update_fail_htlc messages which should be sent + * `update_fail_htlc` messages which should be sent */ void CommitmentUpdate_set_update_fail_htlcs(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCVec_UpdateFailHTLCZ val); /** - * update_fail_malformed_htlc messages which should be sent + * `update_fail_malformed_htlc` messages which should be sent */ struct LDKCVec_UpdateFailMalformedHTLCZ CommitmentUpdate_get_update_fail_malformed_htlcs(const struct LDKCommitmentUpdate *NONNULL_PTR this_ptr); /** - * update_fail_malformed_htlc messages which should be sent + * `update_fail_malformed_htlc` messages which should be sent */ void CommitmentUpdate_set_update_fail_malformed_htlcs(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCVec_UpdateFailMalformedHTLCZ val); /** - * An update_fee message which should be sent + * An `update_fee` message which should be sent * * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None */ struct LDKUpdateFee CommitmentUpdate_get_update_fee(const struct LDKCommitmentUpdate *NONNULL_PTR this_ptr); /** - * An update_fee message which should be sent + * An `update_fee` message which should be sent * * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None */ void CommitmentUpdate_set_update_fee(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKUpdateFee val); /** - * Finally, the commitment_signed message which should be sent + * A `commitment_signed` message which should be sent */ struct LDKCommitmentSigned CommitmentUpdate_get_commitment_signed(const struct LDKCommitmentUpdate *NONNULL_PTR this_ptr); /** - * Finally, the commitment_signed message which should be sent + * A `commitment_signed` message which should be sent */ void CommitmentUpdate_set_commitment_signed(struct LDKCommitmentUpdate *NONNULL_PTR this_ptr, struct LDKCommitmentSigned val); @@ -26682,7 +27626,9 @@ struct LDKCVec_u8Z ReplyShortChannelIdsEnd_write(const struct LDKReplyShortChann struct LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ ReplyShortChannelIdsEnd_read(struct LDKu8slice ser); /** - *\n\t * Calculates the overflow safe ending block height for the query.\n\t * Overflow returns `0xffffffff`, otherwise returns `first_blocknum + number_of_blocks`\n\t + * Calculates the overflow safe ending block height for the query. + * + * Overflow returns `0xffffffff`, otherwise returns `first_blocknum + number_of_blocks`. */ MUST_USE_RES uint32_t QueryChannelRange_end_blocknum(const struct LDKQueryChannelRange *NONNULL_PTR this_arg); @@ -26864,32 +27810,10 @@ void SocketDescriptor_free(struct LDKSocketDescriptor this_ptr); */ void PeerHandleError_free(struct LDKPeerHandleError this_obj); -/** - * Used to indicate that we probably can't make any future connections to this peer (e.g. - * because we required features that our peer was missing, or vice versa). - * - * While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close - * any channels with this peer or check for new versions of LDK. - * - * [`ChannelManager`]: crate::ln::channelmanager::ChannelManager - */ -bool PeerHandleError_get_no_connection_possible(const struct LDKPeerHandleError *NONNULL_PTR this_ptr); - -/** - * Used to indicate that we probably can't make any future connections to this peer (e.g. - * because we required features that our peer was missing, or vice versa). - * - * While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close - * any channels with this peer or check for new versions of LDK. - * - * [`ChannelManager`]: crate::ln::channelmanager::ChannelManager - */ -void PeerHandleError_set_no_connection_possible(struct LDKPeerHandleError *NONNULL_PTR this_ptr, bool val); - /** * Constructs a new PeerHandleError given each field */ -MUST_USE_RES struct LDKPeerHandleError PeerHandleError_new(bool no_connection_possible_arg); +MUST_USE_RES struct LDKPeerHandleError PeerHandleError_new(void); /** * Creates a copy of the PeerHandleError @@ -26911,19 +27835,24 @@ void PeerManager_free(struct LDKPeerManager this_obj); * timestamp, however if it is not available a persistent counter that increases once per * minute should suffice. */ -MUST_USE_RES struct LDKPeerManager PeerManager_new(struct LDKMessageHandler message_handler, struct LDKSecretKey our_node_secret, uint32_t current_time, const uint8_t (*ephemeral_random_data)[32], struct LDKLogger logger, struct LDKCustomMessageHandler custom_message_handler); +MUST_USE_RES struct LDKPeerManager PeerManager_new(struct LDKMessageHandler message_handler, uint32_t current_time, const uint8_t (*ephemeral_random_data)[32], struct LDKLogger logger, struct LDKCustomMessageHandler custom_message_handler, struct LDKNodeSigner node_signer); /** - * Get the list of node ids for peers which have completed the initial handshake. + * Get a list of tuples mapping from node id to network addresses for peers which have + * completed the initial handshake. * - * For outbound connections, this will be the same as the their_node_id parameter passed in to - * new_outbound_connection, however entries will only appear once the initial handshake has - * completed and we are sure the remote peer has the private key for the given node_id. + * For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter + * passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial + * handshake has completed and we are sure the remote peer has the private key for the given + * [`PublicKey`]. + * + * The returned `Option`s will only be `Some` if an address had been previously given via + * [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`]. */ -MUST_USE_RES struct LDKCVec_PublicKeyZ PeerManager_get_peer_node_ids(const struct LDKPeerManager *NONNULL_PTR this_arg); +MUST_USE_RES struct LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ PeerManager_get_peer_node_ids(const struct LDKPeerManager *NONNULL_PTR this_arg); /** - * Indicates a new outbound connection has been established to a node with the given node_id + * Indicates a new outbound connection has been established to a node with the given `node_id` * and an optional remote network address. * * The remote network address adds the option to report a remote IP address back to a connecting @@ -26989,6 +27918,9 @@ MUST_USE_RES struct LDKCResult_NonePeerHandleErrorZ PeerManager_write_buffer_spa * [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the * send buffer). * + * In order to avoid processing too many messages at once per peer, `data` should be on the + * order of 4KiB. + * * [`send_data`]: SocketDescriptor::send_data * [`process_events`]: PeerManager::process_events */ @@ -27023,15 +27955,12 @@ void PeerManager_socket_disconnected(const struct LDKPeerManager *NONNULL_PTR th /** * Disconnect a peer given its node id. * - * Set `no_connection_possible` to true to prevent any further connection with this peer, - * force-closing any channels we have with it. - * * If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the * peer. Thus, be very careful about reentrancy issues. * * [`disconnect_socket`]: SocketDescriptor::disconnect_socket */ -void PeerManager_disconnect_by_node_id(const struct LDKPeerManager *NONNULL_PTR this_arg, struct LDKPublicKey node_id, bool no_connection_possible); +void PeerManager_disconnect_by_node_id(const struct LDKPeerManager *NONNULL_PTR this_arg, struct LDKPublicKey node_id); /** * Disconnects all currently-connected peers. This is useful on platforms where there may be @@ -28134,6 +29063,20 @@ bool OfferFeatures_eq(const struct LDKOfferFeatures *NONNULL_PTR a, const struct */ bool InvoiceRequestFeatures_eq(const struct LDKInvoiceRequestFeatures *NONNULL_PTR a, const struct LDKInvoiceRequestFeatures *NONNULL_PTR b); +/** + * Checks if two Bolt12InvoiceFeaturess contain equal inner contents. + * This ignores pointers and is_owned flags and looks at the values in fields. + * Two objects with NULL inner values will be considered "equal" here. + */ +bool Bolt12InvoiceFeatures_eq(const struct LDKBolt12InvoiceFeatures *NONNULL_PTR a, const struct LDKBolt12InvoiceFeatures *NONNULL_PTR b); + +/** + * Checks if two BlindedHopFeaturess contain equal inner contents. + * This ignores pointers and is_owned flags and looks at the values in fields. + * Two objects with NULL inner values will be considered "equal" here. + */ +bool BlindedHopFeatures_eq(const struct LDKBlindedHopFeatures *NONNULL_PTR a, const struct LDKBlindedHopFeatures *NONNULL_PTR b); + /** * Checks if two ChannelTypeFeaturess contain equal inner contents. * This ignores pointers and is_owned flags and looks at the values in fields. @@ -28171,6 +29114,16 @@ struct LDKOfferFeatures OfferFeatures_clone(const struct LDKOfferFeatures *NONNU */ struct LDKInvoiceRequestFeatures InvoiceRequestFeatures_clone(const struct LDKInvoiceRequestFeatures *NONNULL_PTR orig); +/** + * Creates a copy of the Bolt12InvoiceFeatures + */ +struct LDKBolt12InvoiceFeatures Bolt12InvoiceFeatures_clone(const struct LDKBolt12InvoiceFeatures *NONNULL_PTR orig); + +/** + * Creates a copy of the BlindedHopFeatures + */ +struct LDKBlindedHopFeatures BlindedHopFeatures_clone(const struct LDKBlindedHopFeatures *NONNULL_PTR orig); + /** * Creates a copy of the ChannelTypeFeatures */ @@ -28206,6 +29159,16 @@ void OfferFeatures_free(struct LDKOfferFeatures this_obj); */ void InvoiceRequestFeatures_free(struct LDKInvoiceRequestFeatures this_obj); +/** + * Frees any resources used by the Bolt12InvoiceFeatures, if is_owned is set and inner is non-NULL. + */ +void Bolt12InvoiceFeatures_free(struct LDKBolt12InvoiceFeatures this_obj); + +/** + * Frees any resources used by the BlindedHopFeatures, if is_owned is set and inner is non-NULL. + */ +void BlindedHopFeatures_free(struct LDKBlindedHopFeatures this_obj); + /** * Frees any resources used by the ChannelTypeFeatures, if is_owned is set and inner is non-NULL. */ @@ -28242,40 +29205,62 @@ MUST_USE_RES struct LDKChannelFeatures ChannelFeatures_empty(void); * Returns true if this `Features` object contains unknown feature flags which are set as * \"required\". */ -MUST_USE_RES bool ChannelFeatures_requires_unknown_bits(const struct LDKChannelFeatures *NONNULL_PTR this_arg); +MUST_USE_RES bool ChannelFeatures_requires_unknown_bits(const struct LDKChannelFeatures *NONNULL_PTR this_arg); + +/** + * Create a blank Features with no features set + */ +MUST_USE_RES struct LDKInvoiceFeatures InvoiceFeatures_empty(void); + +/** + * Returns true if this `Features` object contains unknown feature flags which are set as + * \"required\". + */ +MUST_USE_RES bool InvoiceFeatures_requires_unknown_bits(const struct LDKInvoiceFeatures *NONNULL_PTR this_arg); + +/** + * Create a blank Features with no features set + */ +MUST_USE_RES struct LDKOfferFeatures OfferFeatures_empty(void); + +/** + * Returns true if this `Features` object contains unknown feature flags which are set as + * \"required\". + */ +MUST_USE_RES bool OfferFeatures_requires_unknown_bits(const struct LDKOfferFeatures *NONNULL_PTR this_arg); /** * Create a blank Features with no features set */ -MUST_USE_RES struct LDKInvoiceFeatures InvoiceFeatures_empty(void); +MUST_USE_RES struct LDKInvoiceRequestFeatures InvoiceRequestFeatures_empty(void); /** * Returns true if this `Features` object contains unknown feature flags which are set as * \"required\". */ -MUST_USE_RES bool InvoiceFeatures_requires_unknown_bits(const struct LDKInvoiceFeatures *NONNULL_PTR this_arg); +MUST_USE_RES bool InvoiceRequestFeatures_requires_unknown_bits(const struct LDKInvoiceRequestFeatures *NONNULL_PTR this_arg); /** * Create a blank Features with no features set */ -MUST_USE_RES struct LDKOfferFeatures OfferFeatures_empty(void); +MUST_USE_RES struct LDKBolt12InvoiceFeatures Bolt12InvoiceFeatures_empty(void); /** * Returns true if this `Features` object contains unknown feature flags which are set as * \"required\". */ -MUST_USE_RES bool OfferFeatures_requires_unknown_bits(const struct LDKOfferFeatures *NONNULL_PTR this_arg); +MUST_USE_RES bool Bolt12InvoiceFeatures_requires_unknown_bits(const struct LDKBolt12InvoiceFeatures *NONNULL_PTR this_arg); /** * Create a blank Features with no features set */ -MUST_USE_RES struct LDKInvoiceRequestFeatures InvoiceRequestFeatures_empty(void); +MUST_USE_RES struct LDKBlindedHopFeatures BlindedHopFeatures_empty(void); /** * Returns true if this `Features` object contains unknown feature flags which are set as * \"required\". */ -MUST_USE_RES bool InvoiceRequestFeatures_requires_unknown_bits(const struct LDKInvoiceRequestFeatures *NONNULL_PTR this_arg); +MUST_USE_RES bool BlindedHopFeatures_requires_unknown_bits(const struct LDKBlindedHopFeatures *NONNULL_PTR this_arg); /** * Create a blank Features with no features set @@ -28329,34 +29314,24 @@ struct LDKCVec_u8Z InvoiceFeatures_write(const struct LDKInvoiceFeatures *NONNUL struct LDKCResult_InvoiceFeaturesDecodeErrorZ InvoiceFeatures_read(struct LDKu8slice ser); /** - * Serialize the ChannelTypeFeatures object into a byte array which can be read by ChannelTypeFeatures_read - */ -struct LDKCVec_u8Z ChannelTypeFeatures_write(const struct LDKChannelTypeFeatures *NONNULL_PTR obj); - -/** - * Read a ChannelTypeFeatures from a byte array, created by ChannelTypeFeatures_write - */ -struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ ChannelTypeFeatures_read(struct LDKu8slice ser); - -/** - * Serialize the OfferFeatures object into a byte array which can be read by OfferFeatures_read + * Serialize the BlindedHopFeatures object into a byte array which can be read by BlindedHopFeatures_read */ -struct LDKCVec_u8Z OfferFeatures_write(const struct LDKOfferFeatures *NONNULL_PTR obj); +struct LDKCVec_u8Z BlindedHopFeatures_write(const struct LDKBlindedHopFeatures *NONNULL_PTR obj); /** - * Read a OfferFeatures from a byte array, created by OfferFeatures_write + * Read a BlindedHopFeatures from a byte array, created by BlindedHopFeatures_write */ -struct LDKCResult_OfferFeaturesDecodeErrorZ OfferFeatures_read(struct LDKu8slice ser); +struct LDKCResult_BlindedHopFeaturesDecodeErrorZ BlindedHopFeatures_read(struct LDKu8slice ser); /** - * Serialize the InvoiceRequestFeatures object into a byte array which can be read by InvoiceRequestFeatures_read + * Serialize the ChannelTypeFeatures object into a byte array which can be read by ChannelTypeFeatures_read */ -struct LDKCVec_u8Z InvoiceRequestFeatures_write(const struct LDKInvoiceRequestFeatures *NONNULL_PTR obj); +struct LDKCVec_u8Z ChannelTypeFeatures_write(const struct LDKChannelTypeFeatures *NONNULL_PTR obj); /** - * Read a InvoiceRequestFeatures from a byte array, created by InvoiceRequestFeatures_write + * Read a ChannelTypeFeatures from a byte array, created by ChannelTypeFeatures_write */ -struct LDKCResult_InvoiceRequestFeaturesDecodeErrorZ InvoiceRequestFeatures_read(struct LDKu8slice ser); +struct LDKCResult_ChannelTypeFeaturesDecodeErrorZ ChannelTypeFeatures_read(struct LDKu8slice ser); /** * Set this feature as optional. @@ -28718,6 +29693,21 @@ void InvoiceFeatures_set_basic_mpp_required(struct LDKInvoiceFeatures *NONNULL_P */ MUST_USE_RES bool InvoiceFeatures_supports_basic_mpp(const struct LDKInvoiceFeatures *NONNULL_PTR this_arg); +/** + * Set this feature as optional. + */ +void Bolt12InvoiceFeatures_set_basic_mpp_optional(struct LDKBolt12InvoiceFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as required. + */ +void Bolt12InvoiceFeatures_set_basic_mpp_required(struct LDKBolt12InvoiceFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is supported. + */ +MUST_USE_RES bool Bolt12InvoiceFeatures_supports_basic_mpp(const struct LDKBolt12InvoiceFeatures *NONNULL_PTR this_arg); + /** * Checks if this feature is required. */ @@ -28733,6 +29723,11 @@ MUST_USE_RES bool NodeFeatures_requires_basic_mpp(const struct LDKNodeFeatures * */ MUST_USE_RES bool InvoiceFeatures_requires_basic_mpp(const struct LDKInvoiceFeatures *NONNULL_PTR this_arg); +/** + * Checks if this feature is required. + */ +MUST_USE_RES bool Bolt12InvoiceFeatures_requires_basic_mpp(const struct LDKBolt12InvoiceFeatures *NONNULL_PTR this_arg); + /** * Set this feature as optional. */ @@ -28773,6 +29768,66 @@ MUST_USE_RES bool InitFeatures_requires_wumbo(const struct LDKInitFeatures *NONN */ MUST_USE_RES bool NodeFeatures_requires_wumbo(const struct LDKNodeFeatures *NONNULL_PTR this_arg); +/** + * Set this feature as optional. + */ +void InitFeatures_set_anchors_zero_fee_htlc_tx_optional(struct LDKInitFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as required. + */ +void InitFeatures_set_anchors_zero_fee_htlc_tx_required(struct LDKInitFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is supported. + */ +MUST_USE_RES bool InitFeatures_supports_anchors_zero_fee_htlc_tx(const struct LDKInitFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as optional. + */ +void NodeFeatures_set_anchors_zero_fee_htlc_tx_optional(struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as required. + */ +void NodeFeatures_set_anchors_zero_fee_htlc_tx_required(struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is supported. + */ +MUST_USE_RES bool NodeFeatures_supports_anchors_zero_fee_htlc_tx(const struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as optional. + */ +void ChannelTypeFeatures_set_anchors_zero_fee_htlc_tx_optional(struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as required. + */ +void ChannelTypeFeatures_set_anchors_zero_fee_htlc_tx_required(struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is supported. + */ +MUST_USE_RES bool ChannelTypeFeatures_supports_anchors_zero_fee_htlc_tx(const struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is required. + */ +MUST_USE_RES bool InitFeatures_requires_anchors_zero_fee_htlc_tx(const struct LDKInitFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is required. + */ +MUST_USE_RES bool NodeFeatures_requires_anchors_zero_fee_htlc_tx(const struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is required. + */ +MUST_USE_RES bool ChannelTypeFeatures_requires_anchors_zero_fee_htlc_tx(const struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); + /** * Set this feature as optional. */ @@ -28969,176 +30024,347 @@ void InitFeatures_set_zero_conf_required(struct LDKInitFeatures *NONNULL_PTR thi MUST_USE_RES bool InitFeatures_supports_zero_conf(const struct LDKInitFeatures *NONNULL_PTR this_arg); /** - * Set this feature as optional. + * Set this feature as optional. + */ +void NodeFeatures_set_zero_conf_optional(struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as required. + */ +void NodeFeatures_set_zero_conf_required(struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is supported. + */ +MUST_USE_RES bool NodeFeatures_supports_zero_conf(const struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as optional. + */ +void ChannelTypeFeatures_set_zero_conf_optional(struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as required. + */ +void ChannelTypeFeatures_set_zero_conf_required(struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is supported. + */ +MUST_USE_RES bool ChannelTypeFeatures_supports_zero_conf(const struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is required. + */ +MUST_USE_RES bool InitFeatures_requires_zero_conf(const struct LDKInitFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is required. + */ +MUST_USE_RES bool NodeFeatures_requires_zero_conf(const struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is required. + */ +MUST_USE_RES bool ChannelTypeFeatures_requires_zero_conf(const struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as optional. + */ +void NodeFeatures_set_keysend_optional(struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Set this feature as required. + */ +void NodeFeatures_set_keysend_required(struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is supported. + */ +MUST_USE_RES bool NodeFeatures_supports_keysend(const struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Checks if this feature is required. + */ +MUST_USE_RES bool NodeFeatures_requires_keysend(const struct LDKNodeFeatures *NONNULL_PTR this_arg); + +/** + * Frees any resources used by the ShutdownScript, if is_owned is set and inner is non-NULL. + */ +void ShutdownScript_free(struct LDKShutdownScript this_obj); + +/** + * Creates a copy of the ShutdownScript + */ +struct LDKShutdownScript ShutdownScript_clone(const struct LDKShutdownScript *NONNULL_PTR orig); + +/** + * Checks if two ShutdownScripts contain equal inner contents. + * This ignores pointers and is_owned flags and looks at the values in fields. + * Two objects with NULL inner values will be considered "equal" here. + */ +bool ShutdownScript_eq(const struct LDKShutdownScript *NONNULL_PTR a, const struct LDKShutdownScript *NONNULL_PTR b); + +/** + * Frees any resources used by the InvalidShutdownScript, if is_owned is set and inner is non-NULL. + */ +void InvalidShutdownScript_free(struct LDKInvalidShutdownScript this_obj); + +/** + * The script that did not meet the requirements from [BOLT #2]. + * + * [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md + */ +struct LDKu8slice InvalidShutdownScript_get_script(const struct LDKInvalidShutdownScript *NONNULL_PTR this_ptr); + +/** + * The script that did not meet the requirements from [BOLT #2]. + * + * [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md + */ +void InvalidShutdownScript_set_script(struct LDKInvalidShutdownScript *NONNULL_PTR this_ptr, struct LDKCVec_u8Z val); + +/** + * Constructs a new InvalidShutdownScript given each field + */ +MUST_USE_RES struct LDKInvalidShutdownScript InvalidShutdownScript_new(struct LDKCVec_u8Z script_arg); + +/** + * Creates a copy of the InvalidShutdownScript + */ +struct LDKInvalidShutdownScript InvalidShutdownScript_clone(const struct LDKInvalidShutdownScript *NONNULL_PTR orig); + +/** + * Serialize the ShutdownScript object into a byte array which can be read by ShutdownScript_read + */ +struct LDKCVec_u8Z ShutdownScript_write(const struct LDKShutdownScript *NONNULL_PTR obj); + +/** + * Read a ShutdownScript from a byte array, created by ShutdownScript_write + */ +struct LDKCResult_ShutdownScriptDecodeErrorZ ShutdownScript_read(struct LDKu8slice ser); + +/** + * Generates a P2WPKH script pubkey from the given [`WPubkeyHash`]. + */ +MUST_USE_RES struct LDKShutdownScript ShutdownScript_new_p2wpkh(const uint8_t (*pubkey_hash)[20]); + +/** + * Generates a P2WSH script pubkey from the given [`WScriptHash`]. + */ +MUST_USE_RES struct LDKShutdownScript ShutdownScript_new_p2wsh(const uint8_t (*script_hash)[32]); + +/** + * Generates a witness script pubkey from the given segwit version and program. + * + * Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or + * [`ShutdownScript::new_p2wsh`] instead. + * + * # Errors + * + * This function may return an error if `program` is invalid for the segwit `version`. + */ +MUST_USE_RES struct LDKCResult_ShutdownScriptInvalidShutdownScriptZ ShutdownScript_new_witness_program(struct LDKWitnessVersion version, struct LDKu8slice program); + +/** + * Converts the shutdown script into the underlying [`Script`]. + */ +MUST_USE_RES struct LDKCVec_u8Z ShutdownScript_into_inner(struct LDKShutdownScript this_arg); + +/** + * Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it. + * + * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None + */ +MUST_USE_RES struct LDKPublicKey ShutdownScript_as_legacy_pubkey(const struct LDKShutdownScript *NONNULL_PTR this_arg); + +/** + * Returns whether the shutdown script is compatible with the features as defined by BOLT #2. + * + * Specifically, checks for compliance with feature `option_shutdown_anysegwit`. + */ +MUST_USE_RES bool ShutdownScript_is_compatible(const struct LDKShutdownScript *NONNULL_PTR this_arg, const struct LDKInitFeatures *NONNULL_PTR features); + +/** + * Frees any resources used by the Retry + */ +void Retry_free(struct LDKRetry this_ptr); + +/** + * Creates a copy of the Retry */ -void NodeFeatures_set_zero_conf_optional(struct LDKNodeFeatures *NONNULL_PTR this_arg); +struct LDKRetry Retry_clone(const struct LDKRetry *NONNULL_PTR orig); /** - * Set this feature as required. + * Utility method to constructs a new Attempts-variant Retry */ -void NodeFeatures_set_zero_conf_required(struct LDKNodeFeatures *NONNULL_PTR this_arg); +struct LDKRetry Retry_attempts(uintptr_t a); /** - * Checks if this feature is supported. + * Utility method to constructs a new Timeout-variant Retry */ -MUST_USE_RES bool NodeFeatures_supports_zero_conf(const struct LDKNodeFeatures *NONNULL_PTR this_arg); +struct LDKRetry Retry_timeout(uint64_t a); /** - * Set this feature as optional. + * Checks if two Retrys contain equal inner contents. + * This ignores pointers and is_owned flags and looks at the values in fields. */ -void ChannelTypeFeatures_set_zero_conf_optional(struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); +bool Retry_eq(const struct LDKRetry *NONNULL_PTR a, const struct LDKRetry *NONNULL_PTR b); /** - * Set this feature as required. + * Checks if two Retrys contain equal inner contents. */ -void ChannelTypeFeatures_set_zero_conf_required(struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); +uint64_t Retry_hash(const struct LDKRetry *NONNULL_PTR o); /** - * Checks if this feature is supported. + * Creates a copy of the RetryableSendFailure */ -MUST_USE_RES bool ChannelTypeFeatures_supports_zero_conf(const struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); +enum LDKRetryableSendFailure RetryableSendFailure_clone(const enum LDKRetryableSendFailure *NONNULL_PTR orig); /** - * Checks if this feature is required. + * Utility method to constructs a new PaymentExpired-variant RetryableSendFailure */ -MUST_USE_RES bool InitFeatures_requires_zero_conf(const struct LDKInitFeatures *NONNULL_PTR this_arg); +enum LDKRetryableSendFailure RetryableSendFailure_payment_expired(void); /** - * Checks if this feature is required. + * Utility method to constructs a new RouteNotFound-variant RetryableSendFailure */ -MUST_USE_RES bool NodeFeatures_requires_zero_conf(const struct LDKNodeFeatures *NONNULL_PTR this_arg); +enum LDKRetryableSendFailure RetryableSendFailure_route_not_found(void); /** - * Checks if this feature is required. + * Utility method to constructs a new DuplicatePayment-variant RetryableSendFailure */ -MUST_USE_RES bool ChannelTypeFeatures_requires_zero_conf(const struct LDKChannelTypeFeatures *NONNULL_PTR this_arg); +enum LDKRetryableSendFailure RetryableSendFailure_duplicate_payment(void); /** - * Set this feature as optional. + * Frees any resources used by the PaymentSendFailure */ -void NodeFeatures_set_keysend_optional(struct LDKNodeFeatures *NONNULL_PTR this_arg); +void PaymentSendFailure_free(struct LDKPaymentSendFailure this_ptr); /** - * Set this feature as required. + * Creates a copy of the PaymentSendFailure */ -void NodeFeatures_set_keysend_required(struct LDKNodeFeatures *NONNULL_PTR this_arg); +struct LDKPaymentSendFailure PaymentSendFailure_clone(const struct LDKPaymentSendFailure *NONNULL_PTR orig); /** - * Checks if this feature is supported. + * Utility method to constructs a new ParameterError-variant PaymentSendFailure */ -MUST_USE_RES bool NodeFeatures_supports_keysend(const struct LDKNodeFeatures *NONNULL_PTR this_arg); +struct LDKPaymentSendFailure PaymentSendFailure_parameter_error(struct LDKAPIError a); /** - * Checks if this feature is required. + * Utility method to constructs a new PathParameterError-variant PaymentSendFailure */ -MUST_USE_RES bool NodeFeatures_requires_keysend(const struct LDKNodeFeatures *NONNULL_PTR this_arg); +struct LDKPaymentSendFailure PaymentSendFailure_path_parameter_error(struct LDKCVec_CResult_NoneAPIErrorZZ a); /** - * Frees any resources used by the ShutdownScript, if is_owned is set and inner is non-NULL. + * Utility method to constructs a new AllFailedResendSafe-variant PaymentSendFailure */ -void ShutdownScript_free(struct LDKShutdownScript this_obj); +struct LDKPaymentSendFailure PaymentSendFailure_all_failed_resend_safe(struct LDKCVec_APIErrorZ a); /** - * Creates a copy of the ShutdownScript + * Utility method to constructs a new DuplicatePayment-variant PaymentSendFailure */ -struct LDKShutdownScript ShutdownScript_clone(const struct LDKShutdownScript *NONNULL_PTR orig); +struct LDKPaymentSendFailure PaymentSendFailure_duplicate_payment(void); /** - * Checks if two ShutdownScripts contain equal inner contents. - * This ignores pointers and is_owned flags and looks at the values in fields. - * Two objects with NULL inner values will be considered "equal" here. + * Utility method to constructs a new PartialFailure-variant PaymentSendFailure */ -bool ShutdownScript_eq(const struct LDKShutdownScript *NONNULL_PTR a, const struct LDKShutdownScript *NONNULL_PTR b); +struct LDKPaymentSendFailure PaymentSendFailure_partial_failure(struct LDKCVec_CResult_NoneAPIErrorZZ results, struct LDKRouteParameters failed_paths_retry, struct LDKThirtyTwoBytes payment_id); /** - * Frees any resources used by the InvalidShutdownScript, if is_owned is set and inner is non-NULL. + * Calls the free function if one is set */ -void InvalidShutdownScript_free(struct LDKInvalidShutdownScript this_obj); +void CustomMessageReader_free(struct LDKCustomMessageReader this_ptr); /** - * The script that did not meet the requirements from [BOLT #2]. - * - * [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md + * Calls the free function if one is set */ -struct LDKu8slice InvalidShutdownScript_get_script(const struct LDKInvalidShutdownScript *NONNULL_PTR this_ptr); +void Type_free(struct LDKType this_ptr); /** - * The script that did not meet the requirements from [BOLT #2]. - * - * [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md + * Creates a copy of the UtxoLookupError */ -void InvalidShutdownScript_set_script(struct LDKInvalidShutdownScript *NONNULL_PTR this_ptr, struct LDKCVec_u8Z val); +enum LDKUtxoLookupError UtxoLookupError_clone(const enum LDKUtxoLookupError *NONNULL_PTR orig); /** - * Constructs a new InvalidShutdownScript given each field + * Utility method to constructs a new UnknownChain-variant UtxoLookupError */ -MUST_USE_RES struct LDKInvalidShutdownScript InvalidShutdownScript_new(struct LDKCVec_u8Z script_arg); +enum LDKUtxoLookupError UtxoLookupError_unknown_chain(void); /** - * Creates a copy of the InvalidShutdownScript + * Utility method to constructs a new UnknownTx-variant UtxoLookupError */ -struct LDKInvalidShutdownScript InvalidShutdownScript_clone(const struct LDKInvalidShutdownScript *NONNULL_PTR orig); +enum LDKUtxoLookupError UtxoLookupError_unknown_tx(void); /** - * Serialize the ShutdownScript object into a byte array which can be read by ShutdownScript_read + * Frees any resources used by the UtxoResult */ -struct LDKCVec_u8Z ShutdownScript_write(const struct LDKShutdownScript *NONNULL_PTR obj); +void UtxoResult_free(struct LDKUtxoResult this_ptr); /** - * Read a ShutdownScript from a byte array, created by ShutdownScript_write + * Creates a copy of the UtxoResult */ -struct LDKCResult_ShutdownScriptDecodeErrorZ ShutdownScript_read(struct LDKu8slice ser); +struct LDKUtxoResult UtxoResult_clone(const struct LDKUtxoResult *NONNULL_PTR orig); /** - * Generates a P2WPKH script pubkey from the given [`WPubkeyHash`]. + * Utility method to constructs a new Sync-variant UtxoResult */ -MUST_USE_RES struct LDKShutdownScript ShutdownScript_new_p2wpkh(const uint8_t (*pubkey_hash)[20]); +struct LDKUtxoResult UtxoResult_sync(struct LDKCResult_TxOutUtxoLookupErrorZ a); /** - * Generates a P2WSH script pubkey from the given [`WScriptHash`]. + * Utility method to constructs a new Async-variant UtxoResult */ -MUST_USE_RES struct LDKShutdownScript ShutdownScript_new_p2wsh(const uint8_t (*script_hash)[32]); +struct LDKUtxoResult UtxoResult_async(struct LDKUtxoFuture a); /** - * Generates a witness script pubkey from the given segwit version and program. - * - * Note for version-zero witness scripts you must use [`ShutdownScript::new_p2wpkh`] or - * [`ShutdownScript::new_p2wsh`] instead. - * - * # Errors - * - * This function may return an error if `program` is invalid for the segwit `version`. + * Calls the free function if one is set */ -MUST_USE_RES struct LDKCResult_ShutdownScriptInvalidShutdownScriptZ ShutdownScript_new_witness_program(struct LDKWitnessVersion version, struct LDKu8slice program); +void UtxoLookup_free(struct LDKUtxoLookup this_ptr); /** - * Converts the shutdown script into the underlying [`Script`]. + * Frees any resources used by the UtxoFuture, if is_owned is set and inner is non-NULL. */ -MUST_USE_RES struct LDKCVec_u8Z ShutdownScript_into_inner(struct LDKShutdownScript this_arg); +void UtxoFuture_free(struct LDKUtxoFuture this_obj); /** - * Returns the [`PublicKey`] used for a P2WPKH shutdown script if constructed directly from it. - * - * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None + * Creates a copy of the UtxoFuture */ -MUST_USE_RES struct LDKPublicKey ShutdownScript_as_legacy_pubkey(const struct LDKShutdownScript *NONNULL_PTR this_arg); +struct LDKUtxoFuture UtxoFuture_clone(const struct LDKUtxoFuture *NONNULL_PTR orig); /** - * Returns whether the shutdown script is compatible with the features as defined by BOLT #2. - * - * Specifically, checks for compliance with feature `option_shutdown_anysegwit`. + * Builds a new future for later resolution. */ -MUST_USE_RES bool ShutdownScript_is_compatible(const struct LDKShutdownScript *NONNULL_PTR this_arg, const struct LDKInitFeatures *NONNULL_PTR features); +MUST_USE_RES struct LDKUtxoFuture UtxoFuture_new(void); /** - * Calls the free function if one is set + * Resolves this future against the given `graph` and with the given `result`. + * + * This is identical to calling [`UtxoFuture::resolve`] with a dummy `gossip`, disabling + * forwarding the validated gossip message onwards to peers. + * + * Because this may cause the [`NetworkGraph`]'s [`processing_queue_high`] to flip, in order + * to allow us to interact with peers again, you should call [`PeerManager::process_events`] + * after this. + * + * [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high + * [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events */ -void CustomMessageReader_free(struct LDKCustomMessageReader this_ptr); +void UtxoFuture_resolve_without_forwarding(const struct LDKUtxoFuture *NONNULL_PTR this_arg, const struct LDKNetworkGraph *NONNULL_PTR graph, struct LDKCResult_TxOutUtxoLookupErrorZ result); /** - * Calls the free function if one is set + * Resolves this future against the given `graph` and with the given `result`. + * + * The given `gossip` is used to broadcast any validated messages onwards to all peers which + * have available buffer space. + * + * Because this may cause the [`NetworkGraph`]'s [`processing_queue_high`] to flip, in order + * to allow us to interact with peers again, you should call [`PeerManager::process_events`] + * after this. + * + * [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high + * [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events */ -void Type_free(struct LDKType this_ptr); +void UtxoFuture_resolve(const struct LDKUtxoFuture *NONNULL_PTR this_arg, const struct LDKNetworkGraph *NONNULL_PTR graph, const struct LDKP2PGossipSync *NONNULL_PTR gossip, struct LDKCResult_TxOutUtxoLookupErrorZ result); /** * Frees any resources used by the NodeId, if is_owned is set and inner is non-NULL. @@ -29234,18 +30460,17 @@ void P2PGossipSync_free(struct LDKP2PGossipSync this_obj); /** * Creates a new tracker of the actual state of the network of channels and nodes, * assuming an existing Network Graph. - * Chain monitor is used to make sure announced channels exist on-chain, - * channel data is correct, and that the announcement is signed with - * channel owners' keys. + * UTXO lookup is used to make sure announced channels exist on-chain, channel data is + * correct, and the announcement is signed with channel owners' keys. */ -MUST_USE_RES struct LDKP2PGossipSync P2PGossipSync_new(const struct LDKNetworkGraph *NONNULL_PTR network_graph, struct LDKCOption_AccessZ chain_access, struct LDKLogger logger); +MUST_USE_RES struct LDKP2PGossipSync P2PGossipSync_new(const struct LDKNetworkGraph *NONNULL_PTR network_graph, struct LDKCOption_UtxoLookupZ utxo_lookup, struct LDKLogger logger); /** * Adds a provider used to check new announcements. Does not affect * existing announcements unless they are updated. * Add, update or remove the provider would replace the current one. */ -void P2PGossipSync_add_chain_access(struct LDKP2PGossipSync *NONNULL_PTR this_arg, struct LDKCOption_AccessZ chain_access); +void P2PGossipSync_add_utxo_lookup(struct LDKP2PGossipSync *NONNULL_PTR this_arg, struct LDKCOption_UtxoLookupZ utxo_lookup); /** * Handles any network updates originating from [`Event`]s. @@ -29577,12 +30802,12 @@ MUST_USE_RES uint64_t EffectiveCapacity_as_msat(const struct LDKEffectiveCapacit void RoutingFees_free(struct LDKRoutingFees this_obj); /** - * Flat routing fee in satoshis + * Flat routing fee in millisatoshis. */ uint32_t RoutingFees_get_base_msat(const struct LDKRoutingFees *NONNULL_PTR this_ptr); /** - * Flat routing fee in satoshis + * Flat routing fee in millisatoshis. */ void RoutingFees_set_base_msat(struct LDKRoutingFees *NONNULL_PTR this_ptr, uint32_t val); @@ -29793,24 +31018,6 @@ struct LDKCVec_u64Z NodeInfo_get_channels(const struct LDKNodeInfo *NONNULL_PTR */ void NodeInfo_set_channels(struct LDKNodeInfo *NONNULL_PTR this_ptr, struct LDKCVec_u64Z val); -/** - * Lowest fees enabling routing via any of the enabled, known channels to a node. - * The two fields (flat and proportional fee) are independent, - * meaning they don't have to refer to the same channel. - * - * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None - */ -struct LDKRoutingFees NodeInfo_get_lowest_inbound_channel_fees(const struct LDKNodeInfo *NONNULL_PTR this_ptr); - -/** - * Lowest fees enabling routing via any of the enabled, known channels to a node. - * The two fields (flat and proportional fee) are independent, - * meaning they don't have to refer to the same channel. - * - * Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None - */ -void NodeInfo_set_lowest_inbound_channel_fees(struct LDKNodeInfo *NONNULL_PTR this_ptr, struct LDKRoutingFees val); - /** * More information about a node from node_announcement. * Optional because we store a Node entry after learning about it from @@ -29832,7 +31039,7 @@ void NodeInfo_set_announcement_info(struct LDKNodeInfo *NONNULL_PTR this_ptr, st /** * Constructs a new NodeInfo given each field */ -MUST_USE_RES struct LDKNodeInfo NodeInfo_new(struct LDKCVec_u64Z channels_arg, struct LDKRoutingFees lowest_inbound_channel_fees_arg, struct LDKNodeAnnouncementInfo announcement_info_arg); +MUST_USE_RES struct LDKNodeInfo NodeInfo_new(struct LDKCVec_u64Z channels_arg, struct LDKNodeAnnouncementInfo announcement_info_arg); /** * Creates a copy of the NodeInfo @@ -29869,7 +31076,7 @@ struct LDKCResult_NetworkGraphDecodeErrorZ NetworkGraph_read(struct LDKu8slice s /** * Creates a new, empty, network graph. */ -MUST_USE_RES struct LDKNetworkGraph NetworkGraph_new(struct LDKThirtyTwoBytes genesis_hash, struct LDKLogger logger); +MUST_USE_RES struct LDKNetworkGraph NetworkGraph_new(enum LDKNetwork network, struct LDKLogger logger); /** * Returns a read-only view of the network graph. @@ -29913,20 +31120,20 @@ MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_node_from * RoutingMessageHandler implementation to call it indirectly. This may be useful to accept * routing messages from a source using a protocol other than the lightning P2P protocol. * - * If a `chain::Access` object is provided via `chain_access`, it will be called to verify + * If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify * the corresponding UTXO exists on chain and is correctly-formatted. */ -MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_announcement(const struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKChannelAnnouncement *NONNULL_PTR msg, struct LDKCOption_AccessZ chain_access); +MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_announcement(const struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKChannelAnnouncement *NONNULL_PTR msg, struct LDKCOption_UtxoLookupZ utxo_lookup); /** * Store or update channel info from a channel announcement without verifying the associated * signatures. Because we aren't given the associated signatures here we cannot relay the * channel announcement to any of our peers. * - * If a `chain::Access` object is provided via `chain_access`, it will be called to verify + * If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify * the corresponding UTXO exists on chain and is correctly-formatted. */ -MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_unsigned_announcement(const struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg, struct LDKCOption_AccessZ chain_access); +MUST_USE_RES struct LDKCResult_NoneLightningErrorZ NetworkGraph_update_channel_from_unsigned_announcement(const struct LDKNetworkGraph *NONNULL_PTR this_arg, const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg, struct LDKCOption_UtxoLookupZ utxo_lookup); /** * Update channel from partial announcement data received via rapid gossip sync @@ -30072,7 +31279,7 @@ void ScorerAccountingForInFlightHtlcs_free(struct LDKScorerAccountingForInFlight /** * Initialize a new `ScorerAccountingForInFlightHtlcs`. */ -MUST_USE_RES struct LDKScorerAccountingForInFlightHtlcs ScorerAccountingForInFlightHtlcs_new(struct LDKScore scorer, struct LDKInFlightHtlcs inflight_htlcs); +MUST_USE_RES struct LDKScorerAccountingForInFlightHtlcs ScorerAccountingForInFlightHtlcs_new(struct LDKScore scorer, const struct LDKInFlightHtlcs *NONNULL_PTR inflight_htlcs); /** * Serialize the ScorerAccountingForInFlightHtlcs object into a byte array which can be read by ScorerAccountingForInFlightHtlcs_read @@ -30338,26 +31545,23 @@ uint64_t RouteParameters_get_final_value_msat(const struct LDKRouteParameters *N */ void RouteParameters_set_final_value_msat(struct LDKRouteParameters *NONNULL_PTR this_ptr, uint64_t val); -/** - * The CLTV on the final hop of the failed payment path. - */ -uint32_t RouteParameters_get_final_cltv_expiry_delta(const struct LDKRouteParameters *NONNULL_PTR this_ptr); - -/** - * The CLTV on the final hop of the failed payment path. - */ -void RouteParameters_set_final_cltv_expiry_delta(struct LDKRouteParameters *NONNULL_PTR this_ptr, uint32_t val); - /** * Constructs a new RouteParameters given each field */ -MUST_USE_RES struct LDKRouteParameters RouteParameters_new(struct LDKPaymentParameters payment_params_arg, uint64_t final_value_msat_arg, uint32_t final_cltv_expiry_delta_arg); +MUST_USE_RES struct LDKRouteParameters RouteParameters_new(struct LDKPaymentParameters payment_params_arg, uint64_t final_value_msat_arg); /** * Creates a copy of the RouteParameters */ struct LDKRouteParameters RouteParameters_clone(const struct LDKRouteParameters *NONNULL_PTR orig); +/** + * Checks if two RouteParameterss contain equal inner contents. + * This ignores pointers and is_owned flags and looks at the values in fields. + * Two objects with NULL inner values will be considered "equal" here. + */ +bool RouteParameters_eq(const struct LDKRouteParameters *NONNULL_PTR a, const struct LDKRouteParameters *NONNULL_PTR b); + /** * Serialize the RouteParameters object into a byte array which can be read by RouteParameters_read */ @@ -30501,10 +31705,20 @@ struct LDKCVec_u64Z PaymentParameters_get_previously_failed_channels(const struc */ void PaymentParameters_set_previously_failed_channels(struct LDKPaymentParameters *NONNULL_PTR this_ptr, struct LDKCVec_u64Z val); +/** + * The minimum CLTV delta at the end of the route. This value must not be zero. + */ +uint32_t PaymentParameters_get_final_cltv_expiry_delta(const struct LDKPaymentParameters *NONNULL_PTR this_ptr); + +/** + * The minimum CLTV delta at the end of the route. This value must not be zero. + */ +void PaymentParameters_set_final_cltv_expiry_delta(struct LDKPaymentParameters *NONNULL_PTR this_ptr, uint32_t val); + /** * Constructs a new PaymentParameters given each field */ -MUST_USE_RES struct LDKPaymentParameters PaymentParameters_new(struct LDKPublicKey payee_pubkey_arg, struct LDKInvoiceFeatures features_arg, struct LDKCVec_RouteHintZ route_hints_arg, struct LDKCOption_u64Z expiry_time_arg, uint32_t max_total_cltv_expiry_delta_arg, uint8_t max_path_count_arg, uint8_t max_channel_saturation_power_of_half_arg, struct LDKCVec_u64Z previously_failed_channels_arg); +MUST_USE_RES struct LDKPaymentParameters PaymentParameters_new(struct LDKPublicKey payee_pubkey_arg, struct LDKInvoiceFeatures features_arg, struct LDKCVec_RouteHintZ route_hints_arg, struct LDKCOption_u64Z expiry_time_arg, uint32_t max_total_cltv_expiry_delta_arg, uint8_t max_path_count_arg, uint8_t max_channel_saturation_power_of_half_arg, struct LDKCVec_u64Z previously_failed_channels_arg, uint32_t final_cltv_expiry_delta_arg); /** * Creates a copy of the PaymentParameters @@ -30531,17 +31745,23 @@ struct LDKCVec_u8Z PaymentParameters_write(const struct LDKPaymentParameters *NO /** * Read a PaymentParameters from a byte array, created by PaymentParameters_write */ -struct LDKCResult_PaymentParametersDecodeErrorZ PaymentParameters_read(struct LDKu8slice ser); +struct LDKCResult_PaymentParametersDecodeErrorZ PaymentParameters_read(struct LDKu8slice ser, uint32_t arg); /** * Creates a payee with the node id of the given `pubkey`. + * + * The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has + * provided. */ -MUST_USE_RES struct LDKPaymentParameters PaymentParameters_from_node_id(struct LDKPublicKey payee_pubkey); +MUST_USE_RES struct LDKPaymentParameters PaymentParameters_from_node_id(struct LDKPublicKey payee_pubkey, uint32_t final_cltv_expiry_delta); /** * Creates a payee with the node id of the given `pubkey` to use for keysend payments. + * + * The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has + * provided. */ -MUST_USE_RES struct LDKPaymentParameters PaymentParameters_for_keysend(struct LDKPublicKey payee_pubkey); +MUST_USE_RES struct LDKPaymentParameters PaymentParameters_for_keysend(struct LDKPublicKey payee_pubkey, uint32_t final_cltv_expiry_delta); /** * Frees any resources used by the RouteHint, if is_owned is set and inner is non-NULL. @@ -31237,6 +32457,31 @@ void ProbabilisticScorer_debug_log_liquidity_stats(const struct LDKProbabilistic */ MUST_USE_RES struct LDKCOption_C2Tuple_u64u64ZZ ProbabilisticScorer_estimated_channel_liquidity_range(const struct LDKProbabilisticScorer *NONNULL_PTR this_arg, uint64_t scid, const struct LDKNodeId *NONNULL_PTR target); +/** + * Query the historical estimated minimum and maximum liquidity available for sending a + * payment over the channel with `scid` towards the given `target` node. + * + * Returns two sets of 8 buckets. The first set describes the octiles for lower-bound + * liquidity estimates, the second set describes the octiles for upper-bound liquidity + * estimates. Each bucket describes the relative frequency at which we've seen a liquidity + * bound in the octile relative to the channel's total capacity, on an arbitrary scale. + * Because the values are slowly decayed, more recent data points are weighted more heavily + * than older datapoints. + * + * When scoring, the estimated probability that an upper-/lower-bound lies in a given octile + * relative to the channel's total capacity is calculated by dividing that bucket's value with + * the total of all buckets for the given bound. + * + * For example, a value of `[0, 0, 0, 0, 0, 0, 32]` indicates that we believe the probability + * of a bound being in the top octile to be 100%, and have never (recently) seen it in any + * other octiles. A value of `[31, 0, 0, 0, 0, 0, 0, 32]` indicates we've seen the bound being + * both in the top and bottom octile, and roughly with similar (recent) frequency. + * + * Because the datapoints are decayed slowly over time, values will eventually return to + * `Some(([0; 8], [0; 8]))`. + */ +MUST_USE_RES struct LDKCOption_C2Tuple_EightU16sEightU16sZZ ProbabilisticScorer_historical_estimated_channel_liquidity_probabilities(const struct LDKProbabilisticScorer *NONNULL_PTR this_arg, uint64_t scid, const struct LDKNodeId *NONNULL_PTR target); + /** * Marks the node with the given `node_id` as banned, i.e., * it will be avoided during path finding. @@ -31316,7 +32561,7 @@ struct LDKBlindedHop BlindedHop_clone(const struct LDKBlindedHop *NONNULL_PTR or * * Errors if less than two hops are provided or if `node_pk`(s) are invalid. */ -MUST_USE_RES struct LDKCResult_BlindedPathNoneZ BlindedPath_new(struct LDKCVec_PublicKeyZ node_pks, const struct LDKKeysInterface *NONNULL_PTR keys_manager); +MUST_USE_RES struct LDKCResult_BlindedPathNoneZ BlindedPath_new(struct LDKCVec_PublicKeyZ node_pks, const struct LDKEntropySource *NONNULL_PTR entropy_source); /** * Serialize the BlindedPath object into a byte array which can be read by BlindedPath_read @@ -31428,7 +32673,7 @@ void CustomOnionMessageHandler_free(struct LDKCustomOnionMessageHandler this_ptr * Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to * their respective handlers. */ -MUST_USE_RES struct LDKOnionMessenger OnionMessenger_new(struct LDKKeysInterface keys_manager, struct LDKLogger logger, struct LDKCustomOnionMessageHandler custom_handler); +MUST_USE_RES struct LDKOnionMessenger OnionMessenger_new(struct LDKEntropySource entropy_source, struct LDKNodeSigner node_signer, struct LDKLogger logger, struct LDKCustomOnionMessageHandler custom_handler); /** * Send an onion message with contents `message` to `destination`, routing it through `intermediate_nodes`. @@ -31484,7 +32729,7 @@ MUST_USE_RES struct LDKStr FilesystemPersister_get_data_dir(const struct LDKFile /** * Read `ChannelMonitor`s from disk. */ -MUST_USE_RES struct LDKCResult_CVec_C2Tuple_BlockHashChannelMonitorZZErrorZ FilesystemPersister_read_channelmonitors(const struct LDKFilesystemPersister *NONNULL_PTR this_arg, struct LDKKeysInterface keys_manager); +MUST_USE_RES struct LDKCResult_CVec_C2Tuple_BlockHashChannelMonitorZZErrorZ FilesystemPersister_read_channelmonitors(const struct LDKFilesystemPersister *NONNULL_PTR this_arg, struct LDKEntropySource entropy_source, const struct LDKSignerProvider *NONNULL_PTR signer_provider); /** * Frees any resources used by the BackgroundProcessor, if is_owned is set and inner is non-NULL. @@ -32028,35 +33273,35 @@ uint64_t ExpiryTime_hash(const struct LDKExpiryTime *NONNULL_PTR o); bool ExpiryTime_eq(const struct LDKExpiryTime *NONNULL_PTR a, const struct LDKExpiryTime *NONNULL_PTR b); /** - * Frees any resources used by the MinFinalCltvExpiry, if is_owned is set and inner is non-NULL. + * Frees any resources used by the MinFinalCltvExpiryDelta, if is_owned is set and inner is non-NULL. */ -void MinFinalCltvExpiry_free(struct LDKMinFinalCltvExpiry this_obj); +void MinFinalCltvExpiryDelta_free(struct LDKMinFinalCltvExpiryDelta this_obj); -uint64_t MinFinalCltvExpiry_get_a(const struct LDKMinFinalCltvExpiry *NONNULL_PTR this_ptr); +uint64_t MinFinalCltvExpiryDelta_get_a(const struct LDKMinFinalCltvExpiryDelta *NONNULL_PTR this_ptr); -void MinFinalCltvExpiry_set_a(struct LDKMinFinalCltvExpiry *NONNULL_PTR this_ptr, uint64_t val); +void MinFinalCltvExpiryDelta_set_a(struct LDKMinFinalCltvExpiryDelta *NONNULL_PTR this_ptr, uint64_t val); /** - * Constructs a new MinFinalCltvExpiry given each field + * Constructs a new MinFinalCltvExpiryDelta given each field */ -MUST_USE_RES struct LDKMinFinalCltvExpiry MinFinalCltvExpiry_new(uint64_t a_arg); +MUST_USE_RES struct LDKMinFinalCltvExpiryDelta MinFinalCltvExpiryDelta_new(uint64_t a_arg); /** - * Creates a copy of the MinFinalCltvExpiry + * Creates a copy of the MinFinalCltvExpiryDelta */ -struct LDKMinFinalCltvExpiry MinFinalCltvExpiry_clone(const struct LDKMinFinalCltvExpiry *NONNULL_PTR orig); +struct LDKMinFinalCltvExpiryDelta MinFinalCltvExpiryDelta_clone(const struct LDKMinFinalCltvExpiryDelta *NONNULL_PTR orig); /** - * Checks if two MinFinalCltvExpirys contain equal inner contents. + * Checks if two MinFinalCltvExpiryDeltas contain equal inner contents. */ -uint64_t MinFinalCltvExpiry_hash(const struct LDKMinFinalCltvExpiry *NONNULL_PTR o); +uint64_t MinFinalCltvExpiryDelta_hash(const struct LDKMinFinalCltvExpiryDelta *NONNULL_PTR o); /** - * Checks if two MinFinalCltvExpirys contain equal inner contents. + * Checks if two MinFinalCltvExpiryDeltas contain equal inner contents. * This ignores pointers and is_owned flags and looks at the values in fields. * Two objects with NULL inner values will be considered "equal" here. */ -bool MinFinalCltvExpiry_eq(const struct LDKMinFinalCltvExpiry *NONNULL_PTR a, const struct LDKMinFinalCltvExpiry *NONNULL_PTR b); +bool MinFinalCltvExpiryDelta_eq(const struct LDKMinFinalCltvExpiryDelta *NONNULL_PTR a, const struct LDKMinFinalCltvExpiryDelta *NONNULL_PTR b); /** * Frees any resources used by the Fallback @@ -32211,7 +33456,7 @@ MUST_USE_RES struct LDKExpiryTime RawInvoice_expiry_time(const struct LDKRawInvo * * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None */ -MUST_USE_RES struct LDKMinFinalCltvExpiry RawInvoice_min_final_cltv_expiry(const struct LDKRawInvoice *NONNULL_PTR this_arg); +MUST_USE_RES struct LDKMinFinalCltvExpiryDelta RawInvoice_min_final_cltv_expiry_delta(const struct LDKRawInvoice *NONNULL_PTR this_arg); /** * @@ -32363,10 +33608,10 @@ MUST_USE_RES bool Invoice_is_expired(const struct LDKInvoice *NONNULL_PTR this_a MUST_USE_RES bool Invoice_would_expire(const struct LDKInvoice *NONNULL_PTR this_arg, uint64_t at_time); /** - * Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise - * [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`]. + * Returns the invoice's `min_final_cltv_expiry_delta` time, if present, otherwise + * [`DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA`]. */ -MUST_USE_RES uint64_t Invoice_min_final_cltv_expiry(const struct LDKInvoice *NONNULL_PTR this_arg); +MUST_USE_RES uint64_t Invoice_min_final_cltv_expiry_delta(const struct LDKInvoice *NONNULL_PTR this_arg); /** * Returns a list of all routes included in the invoice @@ -32461,6 +33706,11 @@ enum LDKCreationError CreationError_invalid_amount(void); */ enum LDKCreationError CreationError_missing_route_hints(void); +/** + * Utility method to constructs a new MinFinalCltvExpiryDeltaTooShort-variant CreationError + */ +enum LDKCreationError CreationError_min_final_cltv_expiry_delta_too_short(void); + /** * Checks if two CreationErrors contain equal inner contents. * This ignores pointers and is_owned flags and looks at the values in fields. @@ -32570,94 +33820,18 @@ bool SignOrCreationError_eq(const struct LDKSignOrCreationError *NONNULL_PTR a, struct LDKStr SignOrCreationError_to_str(const struct LDKSignOrCreationError *NONNULL_PTR o); /** - * Frees any resources used by the InvoicePayer, if is_owned is set and inner is non-NULL. - */ -void InvoicePayer_free(struct LDKInvoicePayer this_obj); - -/** - * Calls the free function if one is set - */ -void Payer_free(struct LDKPayer this_ptr); - -/** - * Frees any resources used by the Retry - */ -void Retry_free(struct LDKRetry this_ptr); - -/** - * Creates a copy of the Retry - */ -struct LDKRetry Retry_clone(const struct LDKRetry *NONNULL_PTR orig); - -/** - * Utility method to constructs a new Attempts-variant Retry - */ -struct LDKRetry Retry_attempts(uintptr_t a); - -/** - * Utility method to constructs a new Timeout-variant Retry - */ -struct LDKRetry Retry_timeout(uint64_t a); - -/** - * Checks if two Retrys contain equal inner contents. - * This ignores pointers and is_owned flags and looks at the values in fields. - */ -bool Retry_eq(const struct LDKRetry *NONNULL_PTR a, const struct LDKRetry *NONNULL_PTR b); - -/** - * Checks if two Retrys contain equal inner contents. - */ -uint64_t Retry_hash(const struct LDKRetry *NONNULL_PTR o); - -/** - * Frees any resources used by the PaymentError - */ -void PaymentError_free(struct LDKPaymentError this_ptr); - -/** - * Creates a copy of the PaymentError - */ -struct LDKPaymentError PaymentError_clone(const struct LDKPaymentError *NONNULL_PTR orig); - -/** - * Utility method to constructs a new Invoice-variant PaymentError - */ -struct LDKPaymentError PaymentError_invoice(struct LDKStr a); - -/** - * Utility method to constructs a new Routing-variant PaymentError - */ -struct LDKPaymentError PaymentError_routing(struct LDKLightningError a); - -/** - * Utility method to constructs a new Sending-variant PaymentError - */ -struct LDKPaymentError PaymentError_sending(struct LDKPaymentSendFailure a); - -/** - * Creates an invoice payer that retries failed payment paths. - * - * Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once - * `retry` has been exceeded for a given [`Invoice`]. - */ -MUST_USE_RES struct LDKInvoicePayer InvoicePayer_new(struct LDKPayer payer, struct LDKRouter router, struct LDKLogger logger, struct LDKEventHandler event_handler, struct LDKRetry retry); - -/** - * Pays the given [`Invoice`], caching it for later use in case a retry is needed. + * Pays the given [`Invoice`], retrying if needed based on [`Retry`]. * * [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long * as the payment is still pending. Once the payment completes or fails, you must ensure that * a second payment with the same [`PaymentHash`] is never sent. * - * If you wish to use a different payment idempotency token, see - * [`Self::pay_invoice_with_id`]. + * If you wish to use a different payment idempotency token, see [`pay_invoice_with_id`]. */ -MUST_USE_RES struct LDKCResult_PaymentIdPaymentErrorZ InvoicePayer_pay_invoice(const struct LDKInvoicePayer *NONNULL_PTR this_arg, const struct LDKInvoice *NONNULL_PTR invoice); +struct LDKCResult_PaymentIdPaymentErrorZ pay_invoice(const struct LDKInvoice *NONNULL_PTR invoice, struct LDKRetry retry_strategy, const struct LDKChannelManager *NONNULL_PTR channelmanager); /** - * Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use - * in case a retry is needed. + * Pays the given [`Invoice`] with a custom idempotency key, retrying if needed based on [`Retry`]. * * Note that idempotency is only guaranteed as long as the payment is still pending. Once the * payment completes or fails, no idempotency guarantees are made. @@ -32665,27 +33839,26 @@ MUST_USE_RES struct LDKCResult_PaymentIdPaymentErrorZ InvoicePayer_pay_invoice(c * You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`] * has never been paid before. * - * See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency - * token. + * See [`pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency token. */ -MUST_USE_RES struct LDKCResult_NonePaymentErrorZ InvoicePayer_pay_invoice_with_id(const struct LDKInvoicePayer *NONNULL_PTR this_arg, const struct LDKInvoice *NONNULL_PTR invoice, struct LDKThirtyTwoBytes payment_id); +struct LDKCResult_NonePaymentErrorZ pay_invoice_with_id(const struct LDKInvoice *NONNULL_PTR invoice, struct LDKThirtyTwoBytes payment_id, struct LDKRetry retry_strategy, const struct LDKChannelManager *NONNULL_PTR channelmanager); /** - * Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in - * case a retry is needed. + * Pays the given zero-value [`Invoice`] using the given amount, retrying if needed based on + * [`Retry`]. * * [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long * as the payment is still pending. Once the payment completes or fails, you must ensure that * a second payment with the same [`PaymentHash`] is never sent. * * If you wish to use a different payment idempotency token, see - * [`Self::pay_zero_value_invoice_with_id`]. + * [`pay_zero_value_invoice_with_id`]. */ -MUST_USE_RES struct LDKCResult_PaymentIdPaymentErrorZ InvoicePayer_pay_zero_value_invoice(const struct LDKInvoicePayer *NONNULL_PTR this_arg, const struct LDKInvoice *NONNULL_PTR invoice, uint64_t amount_msats); +struct LDKCResult_PaymentIdPaymentErrorZ pay_zero_value_invoice(const struct LDKInvoice *NONNULL_PTR invoice, uint64_t amount_msats, struct LDKRetry retry_strategy, const struct LDKChannelManager *NONNULL_PTR channelmanager); /** * Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key, - * caching the invoice for later use in case a retry is needed. + * , retrying if needed based on [`Retry`]. * * Note that idempotency is only guaranteed as long as the payment is still pending. Once the * payment completes or fails, no idempotency guarantees are made. @@ -32693,46 +33866,30 @@ MUST_USE_RES struct LDKCResult_PaymentIdPaymentErrorZ InvoicePayer_pay_zero_valu * You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`] * has never been paid before. * - * See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the + * See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the * idempotency token. */ -MUST_USE_RES struct LDKCResult_NonePaymentErrorZ InvoicePayer_pay_zero_value_invoice_with_id(const struct LDKInvoicePayer *NONNULL_PTR this_arg, const struct LDKInvoice *NONNULL_PTR invoice, uint64_t amount_msats, struct LDKThirtyTwoBytes payment_id); +struct LDKCResult_NonePaymentErrorZ pay_zero_value_invoice_with_id(const struct LDKInvoice *NONNULL_PTR invoice, uint64_t amount_msats, struct LDKThirtyTwoBytes payment_id, struct LDKRetry retry_strategy, const struct LDKChannelManager *NONNULL_PTR channelmanager); /** - * Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in - * case a retry is needed. - * - * The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency - * as long as the payment is still pending. Once the payment completes or fails, you must - * ensure that a second payment with the same [`PaymentPreimage`] is never sent. + * Frees any resources used by the PaymentError */ -MUST_USE_RES struct LDKCResult_PaymentIdPaymentErrorZ InvoicePayer_pay_pubkey(const struct LDKInvoicePayer *NONNULL_PTR this_arg, struct LDKPublicKey pubkey, struct LDKThirtyTwoBytes payment_preimage, uint64_t amount_msats, uint32_t final_cltv_expiry_delta); +void PaymentError_free(struct LDKPaymentError this_ptr); /** - * Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key, - * caching the invoice for later use in case a retry is needed. - * - * Note that idempotency is only guaranteed as long as the payment is still pending. Once the - * payment completes or fails, no idempotency guarantees are made. - * - * You should ensure that the [`PaymentPreimage`] is unique and the corresponding - * [`PaymentHash`] has never been paid before. + * Creates a copy of the PaymentError */ -MUST_USE_RES struct LDKCResult_NonePaymentErrorZ InvoicePayer_pay_pubkey_with_id(const struct LDKInvoicePayer *NONNULL_PTR this_arg, struct LDKPublicKey pubkey, struct LDKThirtyTwoBytes payment_preimage, struct LDKThirtyTwoBytes payment_id, uint64_t amount_msats, uint32_t final_cltv_expiry_delta); +struct LDKPaymentError PaymentError_clone(const struct LDKPaymentError *NONNULL_PTR orig); /** - * Removes the payment cached by the given payment hash. - * - * Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an - * [`EventHandler`]. Otherwise, calling this method is unnecessary. + * Utility method to constructs a new Invoice-variant PaymentError */ -void InvoicePayer_remove_cached_payment(const struct LDKInvoicePayer *NONNULL_PTR this_arg, const uint8_t (*payment_hash)[32]); +struct LDKPaymentError PaymentError_invoice(struct LDKStr a); /** - * Constructs a new EventHandler which calls the relevant methods on this_arg. - * This copies the `inner` pointer in this_arg and thus the returned EventHandler must be freed before this_arg is + * Utility method to constructs a new Sending-variant PaymentError */ -struct LDKEventHandler InvoicePayer_as_EventHandler(const struct LDKInvoicePayer *NONNULL_PTR this_arg); +struct LDKPaymentError PaymentError_sending(enum LDKRetryableSendFailure a); /** * Utility to create an invoice that can be paid to one of multiple nodes, or a \"phantom invoice.\" @@ -32755,7 +33912,14 @@ struct LDKEventHandler InvoicePayer_as_EventHandler(const struct LDKInvoicePayer * `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for * in excess of the current time. * - * Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom + * `duration_since_epoch` is the current time since epoch in seconds. + * + * You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to + * [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`] - 3. + * Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block + * confirmations during routing. + * + * Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom * invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this * requirement). * @@ -32764,10 +33928,14 @@ struct LDKEventHandler InvoicePayer_as_EventHandler(const struct LDKInvoicePayer * [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment * [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash * [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels + * [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA + * + * This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not + * available and the current time is supplied by the caller. * * Note that payment_hash (or a relevant inner pointer) may be NULL or all-0s to represent None */ -struct LDKCResult_InvoiceSignOrCreationErrorZ create_phantom_invoice(struct LDKCOption_u64Z amt_msat, struct LDKThirtyTwoBytes payment_hash, struct LDKStr description, uint32_t invoice_expiry_delta_secs, struct LDKCVec_PhantomRouteHintsZ phantom_route_hints, struct LDKKeysInterface keys_manager, struct LDKLogger logger, enum LDKCurrency network); +struct LDKCResult_InvoiceSignOrCreationErrorZ create_phantom_invoice(struct LDKCOption_u64Z amt_msat, struct LDKThirtyTwoBytes payment_hash, struct LDKStr description, uint32_t invoice_expiry_delta_secs, struct LDKCVec_PhantomRouteHintsZ phantom_route_hints, struct LDKEntropySource entropy_source, struct LDKNodeSigner node_signer, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u16Z min_final_cltv_expiry_delta, uint64_t duration_since_epoch); /** * Utility to create an invoice that can be paid to one of multiple nodes, or a \"phantom invoice.\" @@ -32792,7 +33960,9 @@ struct LDKCResult_InvoiceSignOrCreationErrorZ create_phantom_invoice(struct LDKC * `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for * in excess of the current time. * - * Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom + * `duration_since_epoch` is the current time since epoch in seconds. + * + * Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom * invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this * requirement). * @@ -32802,9 +33972,12 @@ struct LDKCResult_InvoiceSignOrCreationErrorZ create_phantom_invoice(struct LDKC * [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash * [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels * + * This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not + * available and the current time is supplied by the caller. + * * Note that payment_hash (or a relevant inner pointer) may be NULL or all-0s to represent None */ -struct LDKCResult_InvoiceSignOrCreationErrorZ create_phantom_invoice_with_description_hash(struct LDKCOption_u64Z amt_msat, struct LDKThirtyTwoBytes payment_hash, uint32_t invoice_expiry_delta_secs, struct LDKSha256 description_hash, struct LDKCVec_PhantomRouteHintsZ phantom_route_hints, struct LDKKeysInterface keys_manager, struct LDKLogger logger, enum LDKCurrency network); +struct LDKCResult_InvoiceSignOrCreationErrorZ create_phantom_invoice_with_description_hash(struct LDKCOption_u64Z amt_msat, struct LDKThirtyTwoBytes payment_hash, uint32_t invoice_expiry_delta_secs, struct LDKSha256 description_hash, struct LDKCVec_PhantomRouteHintsZ phantom_route_hints, struct LDKEntropySource entropy_source, struct LDKNodeSigner node_signer, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u16Z min_final_cltv_expiry_delta, uint64_t duration_since_epoch); /** * Utility to construct an invoice. Generally, unless you want to do something like a custom @@ -32815,8 +33988,15 @@ struct LDKCResult_InvoiceSignOrCreationErrorZ create_phantom_invoice_with_descri * * `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for * in excess of the current time. + * + * You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to + * [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. + * Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block + * confirmations during routing. + * + * [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA */ -struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKKeysInterface keys_manager, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKStr description, uint32_t invoice_expiry_delta_secs); +struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKNodeSigner node_signer, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKStr description, uint32_t invoice_expiry_delta_secs, struct LDKCOption_u16Z min_final_cltv_expiry_delta); /** * Utility to construct an invoice. Generally, unless you want to do something like a custom @@ -32828,22 +34008,29 @@ struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager * * `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for * in excess of the current time. + * + * You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to + * [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. + * Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block + * confirmations during routing. + * + * [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA */ -struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager_with_description_hash(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKKeysInterface keys_manager, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKSha256 description_hash, uint32_t invoice_expiry_delta_secs); +struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager_with_description_hash(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKNodeSigner node_signer, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKSha256 description_hash, uint32_t invoice_expiry_delta_secs, struct LDKCOption_u16Z min_final_cltv_expiry_delta); /** * See [`create_invoice_from_channelmanager_with_description_hash`] * This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not * available and the current time is supplied by the caller. */ -struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKKeysInterface keys_manager, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKSha256 description_hash, uint64_t duration_since_epoch, uint32_t invoice_expiry_delta_secs); +struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKNodeSigner node_signer, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKSha256 description_hash, uint64_t duration_since_epoch, uint32_t invoice_expiry_delta_secs, struct LDKCOption_u16Z min_final_cltv_expiry_delta); /** * See [`create_invoice_from_channelmanager`] * This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not * available and the current time is supplied by the caller. */ -struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager_and_duration_since_epoch(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKKeysInterface keys_manager, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKStr description, uint64_t duration_since_epoch, uint32_t invoice_expiry_delta_secs); +struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager_and_duration_since_epoch(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKNodeSigner node_signer, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKStr description, uint64_t duration_since_epoch, uint32_t invoice_expiry_delta_secs, struct LDKCOption_u16Z min_final_cltv_expiry_delta); /** * See [`create_invoice_from_channelmanager_and_duration_since_epoch`] @@ -32851,13 +34038,7 @@ struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager * This may be useful if you're building an on-chain swap or involving another protocol where * the payment hash is also involved outside the scope of lightning. */ -struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKKeysInterface keys_manager, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKStr description, uint64_t duration_since_epoch, uint32_t invoice_expiry_delta_secs, struct LDKThirtyTwoBytes payment_hash); - -/** - * Constructs a new Payer which calls the relevant methods on this_arg. - * This copies the `inner` pointer in this_arg and thus the returned Payer must be freed before this_arg is - */ -struct LDKPayer ChannelManager_as_Payer(const struct LDKChannelManager *NONNULL_PTR this_arg); +struct LDKCResult_InvoiceSignOrCreationErrorZ create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(const struct LDKChannelManager *NONNULL_PTR channelmanager, struct LDKNodeSigner node_signer, struct LDKLogger logger, enum LDKCurrency network, struct LDKCOption_u64Z amt_msat, struct LDKStr description, uint64_t duration_since_epoch, uint32_t invoice_expiry_delta_secs, struct LDKThirtyTwoBytes payment_hash, struct LDKCOption_u16Z min_final_cltv_expiry_delta); /** * Read a SiPrefix object from a string @@ -32912,18 +34093,25 @@ void RapidGossipSync_free(struct LDKRapidGossipSync this_obj); /** * Instantiate a new [`RapidGossipSync`] instance. */ -MUST_USE_RES struct LDKRapidGossipSync RapidGossipSync_new(const struct LDKNetworkGraph *NONNULL_PTR network_graph); +MUST_USE_RES struct LDKRapidGossipSync RapidGossipSync_new(const struct LDKNetworkGraph *NONNULL_PTR network_graph, struct LDKLogger logger); /** * Update network graph from binary data. * Returns the last sync timestamp to be used the next time rapid sync data is queried. * - * `network_graph`: network graph to be updated - * * `update_data`: `&[u8]` binary stream that comprises the update data */ MUST_USE_RES struct LDKCResult_u32GraphSyncErrorZ RapidGossipSync_update_network_graph(const struct LDKRapidGossipSync *NONNULL_PTR this_arg, struct LDKu8slice update_data); +/** + * Update network graph from binary data. + * Returns the last sync timestamp to be used the next time rapid sync data is queried. + * + * `update_data`: `&[u8]` binary stream that comprises the update data + * `current_time_unix`: `Option` optional current timestamp to verify data age + */ +MUST_USE_RES struct LDKCResult_u32GraphSyncErrorZ RapidGossipSync_update_network_graph_no_std(const struct LDKRapidGossipSync *NONNULL_PTR this_arg, struct LDKu8slice update_data, struct LDKCOption_u64Z current_time_unix); + /** * Returns whether a rapid gossip sync has completed at least once. */ diff --git a/lightning-c-bindings/include/lightningpp.hpp b/lightning-c-bindings/include/lightningpp.hpp index 3949222..c9e30a3 100644 --- a/lightning-c-bindings/include/lightningpp.hpp +++ b/lightning-c-bindings/include/lightningpp.hpp @@ -2,6 +2,9 @@ namespace LDK { // Forward declarations class Str; +class Retry; +class RetryableSendFailure; +class PaymentSendFailure; class HTLCClaim; class CounterpartyCommitmentSecrets; class TxCreationKeys; @@ -36,6 +39,7 @@ class BroadcasterInterface; class ConfirmationTarget; class FeeEstimator; class PaymentPurpose; +class PathFailure; class ClosureReason; class HTLCDestination; class Event; @@ -45,8 +49,6 @@ class OnionMessageProvider; class EventsProvider; class EventHandler; class BestBlock; -class AccessError; -class Access; class Listen; class Confirm; class ChannelMonitorUpdateStatus; @@ -68,6 +70,8 @@ class ChannelFeatures; class InvoiceFeatures; class OfferFeatures; class InvoiceRequestFeatures; +class Bolt12InvoiceFeatures; +class BlindedHopFeatures; class ChannelTypeFeatures; class OnionMessageContents; class CustomOnionMessageContents; @@ -87,20 +91,24 @@ class NodeInfo; class DelayedPaymentOutputDescriptor; class StaticPaymentOutputDescriptor; class SpendableOutputDescriptor; -class BaseSign; -class Sign; +class ChannelSigner; +class EcdsaChannelSigner; +class WriteableEcdsaChannelSigner; class Recipient; -class KeysInterface; +class EntropySource; +class NodeSigner; +class SignerProvider; class InMemorySigner; class KeysManager; class PhantomKeysManager; class FilesystemPersister; +class FailureCode; class ChannelManager; class ChainParameters; class CounterpartyForwardingInfo; class ChannelCounterparty; class ChannelDetails; -class PaymentSendFailure; +class RecentPaymentDetails; class PhantomRouteHints; class ChannelManagerReadArgs; class ChannelHandshakeConfig; @@ -114,9 +122,6 @@ class PrintableString; class OutPoint; class CustomMessageReader; class Type; -class InvoicePayer; -class Payer; -class Retry; class PaymentError; class ChannelMonitorUpdate; class MonitorEvent; @@ -131,6 +136,10 @@ class MessageHandler; class SocketDescriptor; class PeerHandleError; class PeerManager; +class UtxoLookupError; +class UtxoResult; +class UtxoLookup; +class UtxoFuture; class OnionMessenger; class Destination; class SendError; @@ -148,7 +157,7 @@ class Sha256; class Description; class PayeePubKey; class ExpiryTime; -class MinFinalCltvExpiry; +class MinFinalCltvExpiryDelta; class Fallback; class InvoiceSignature; class PrivateRoute; @@ -183,6 +192,7 @@ class DataLossProtect; class ChannelReestablish; class AnnouncementSignatures; class NetAddress; +class UnsignedGossipMessage; class UnsignedNodeAnnouncement; class NodeAnnouncement; class UnsignedChannelAnnouncement; @@ -226,8 +236,9 @@ class CResult_PaymentPreimageAPIErrorZ; class CResult_RouteHintDecodeErrorZ; class COption_FilterZ; class COption_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ; -class CResult_CommitmentSignedDecodeErrorZ; +class CResult_COption_APIErrorZDecodeErrorZ; class CVec_UpdateAddHTLCZ; +class CResult_CommitmentSignedDecodeErrorZ; class COption_u32Z; class CResult_StaticPaymentOutputDescriptorDecodeErrorZ; class CVec_C2Tuple_TxidBlockHashZZ; @@ -236,6 +247,7 @@ class CResult_TransactionNoneZ; class CResult_ClosingSignedFeeRangeDecodeErrorZ; class CResult_ErrorMessageDecodeErrorZ; class CResult_OpenChannelDecodeErrorZ; +class COption_APIErrorZ; class CResult_QueryChannelRangeDecodeErrorZ; class CVec_TransactionZ; class C2Tuple_TxidBlockHashZ; @@ -250,8 +262,10 @@ class C2Tuple_BlockHashChannelMonitorZ; class CResult_ShutdownScriptInvalidShutdownScriptZ; class CResult_NodeAnnouncementInfoDecodeErrorZ; class CResult_COption_NetworkUpdateZDecodeErrorZ; +class CResult_NoneRetryableSendFailureZ; class CVec_UpdateFailMalformedHTLCZ; class CVec_C2Tuple_OutPointCVec_MonitorUpdateIdZZZ; +class CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ; class CVec_RouteHopZ; class COption_CustomOnionMessageContentsZ; class CVec_C2Tuple_BlockHashChannelMonitorZZ; @@ -260,19 +274,19 @@ class CResult_ClosingSignedDecodeErrorZ; class CResult_NonePaymentErrorZ; class CVec_CResult_NoneAPIErrorZZ; class CResult_CounterpartyCommitmentSecretsDecodeErrorZ; +class CVec_RecentPaymentDetailsZ; class CResult_C2Tuple_PaymentHashPaymentSecretZNoneZ; class CVec_RouteHintHopZ; class CResult_PaymentParametersDecodeErrorZ; class CVec_U5Z; -class CResult_SignDecodeErrorZ; -class CResult_UnsignedChannelAnnouncementDecodeErrorZ; -class COption_AccessZ; +class COption_UtxoLookupZ; class CResult_PongDecodeErrorZ; +class CResult_UnsignedChannelAnnouncementDecodeErrorZ; class C2Tuple_OutPointCVec_MonitorUpdateIdZZ; class CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ; -class C2Tuple_SignatureSignatureZ; class C2Tuple_BlockHashChannelManagerZ; class CResult_ChannelTransactionParametersDecodeErrorZ; +class CResult_WriteableEcdsaChannelSignerDecodeErrorZ; class CResult_DelayedPaymentOutputDescriptorDecodeErrorZ; class C2Tuple_PaymentHashPaymentIdZ; class CResult_C2Tuple_PaymentHashPaymentSecretZAPIErrorZ; @@ -284,10 +298,12 @@ class CResult_BlindedHopDecodeErrorZ; class CResult_TrustedCommitmentTransactionNoneZ; class CResult_FixedPenaltyScorerDecodeErrorZ; class CResult_NoneLightningErrorZ; -class CResult_NonePeerHandleErrorZ; +class CResult_PaymentHashRetryableSendFailureZ; +class C2Tuple_PublicKeyCOption_NetAddressZZ; class CResult_COption_EventZDecodeErrorZ; class CResult_CVec_SignatureZNoneZ; class COption_CVec_NetAddressZZ; +class CResult_NonePeerHandleErrorZ; class CResult__u832APIErrorZ; class CResult_PaymentIdPaymentErrorZ; class CResult_COption_MonitorEventZDecodeErrorZ; @@ -300,6 +316,7 @@ class CResult_UpdateAddHTLCDecodeErrorZ; class COption_MonitorEventZ; class COption_TypeZ; class CResult_COption_TypeZDecodeErrorZ; +class CResult_COption_PathFailureZDecodeErrorZ; class CResult_UpdateFailHTLCDecodeErrorZ; class CResult_InvoiceParseOrSemanticErrorZ; class CResult_RevokeAndACKDecodeErrorZ; @@ -320,6 +337,7 @@ class CResult_UpdateFulfillHTLCDecodeErrorZ; class CResult_NodeFeaturesDecodeErrorZ; class CResult_InMemorySignerDecodeErrorZ; class CResult_ReplyShortChannelIdsEndDecodeErrorZ; +class COption_PathFailureZ; class COption_ScalarZ; class CResult_ChannelUpdateInfoDecodeErrorZ; class CResult_BuiltCommitmentTransactionDecodeErrorZ; @@ -329,26 +347,26 @@ class CVec_UpdateFailHTLCZ; class CVec_SpendableOutputDescriptorZ; class COption_C2Tuple_u64u64ZZ; class CResult_ChannelAnnouncementDecodeErrorZ; -class CResult_OfferFeaturesDecodeErrorZ; -class C2Tuple_SignatureCVec_SignatureZZ; class CResult_HTLCUpdateDecodeErrorZ; +class C2Tuple_SignatureCVec_SignatureZZ; class CVec_OutPointZ; class COption_WriteableScoreZ; class CResult_PositiveTimestampCreationErrorZ; +class C2Tuple__u168_u168Z; class CResult_InvoiceFeaturesDecodeErrorZ; class CResult_ChannelMonitorUpdateDecodeErrorZ; class CResult_ReplyChannelRangeDecodeErrorZ; -class CResult_TxOutAccessErrorZ; +class CResult_InvoiceSignOrCreationErrorZ; class CResult_TrustedClosingTransactionNoneZ; class CResult_NetAddressDecodeErrorZ; class C2Tuple_PublicKeyTypeZ; class CResult_ChannelReestablishDecodeErrorZ; class CResult_OnionMessageDecodeErrorZ; class CResult_UnsignedNodeAnnouncementDecodeErrorZ; -class CResult_InvoiceSignOrCreationErrorZ; class CResult_InitFeaturesDecodeErrorZ; class CResult_PublicKeyNoneZ; class CResult_PingDecodeErrorZ; +class CResult_BlindedHopFeaturesDecodeErrorZ; class CVec_TransactionOutputsZ; class COption_HTLCClaimZ; class CVec_CVec_u8ZZ; @@ -364,6 +382,7 @@ class CResult_RouteHopDecodeErrorZ; class CVec_BalanceZ; class CResult_FundingSignedDecodeErrorZ; class CResult_RecoverableSignatureNoneZ; +class C2Tuple_Z; class C3Tuple_RawInvoice_u832InvoiceSignatureZ; class CResult_NetworkGraphDecodeErrorZ; class CResult_NodeInfoDecodeErrorZ; @@ -377,7 +396,6 @@ class CResult_WarningMessageDecodeErrorZ; class CResult_ChannelCounterpartyDecodeErrorZ; class CResult_SignatureNoneZ; class C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ; -class CResult_SecretKeyNoneZ; class CResult_InitDecodeErrorZ; class CVec_MonitorUpdateIdZ; class CResult_PaymentPurposeDecodeErrorZ; @@ -387,7 +405,6 @@ class CVec_MessageSendEventZ; class COption_NetAddressZ; class C2Tuple_OutPointScriptZ; class CResult_RouteHintHopDecodeErrorZ; -class CResult_C2Tuple_SignatureSignatureZNoneZ; class CResult_UpdateFailMalformedHTLCDecodeErrorZ; class CResult_SharedSecretNoneZ; class CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ; @@ -407,10 +424,9 @@ class CVec_CVec_RouteHopZZ; class CVec_C2Tuple_PublicKeyTypeZZ; class C3Tuple_OutPointCVec_MonitorEventZPublicKeyZ; class CResult_u32GraphSyncErrorZ; -class CResult_InvoiceRequestFeaturesDecodeErrorZ; class CVec_PhantomRouteHintsZ; -class CResult_CounterpartyChannelTransactionParametersDecodeErrorZ; class CResult_NoneAPIErrorZ; +class CResult_CounterpartyChannelTransactionParametersDecodeErrorZ; class CVec_NetAddressZ; class CResult_ChannelDetailsDecodeErrorZ; class CVec_PublicKeyZ; @@ -422,6 +438,7 @@ class CResult_ChannelConfigDecodeErrorZ; class CVec_PrivateRouteZ; class CResult_BlindedPathNoneZ; class CResult_ShutdownDecodeErrorZ; +class CResult_TxOutUtxoLookupErrorZ; class CVec_MonitorEventZ; class CVec_PaymentPreimageZ; class CResult_PublicKeyErrorZ; @@ -436,6 +453,7 @@ class CResult_PaymentSecretAPIErrorZ; class CResult_CounterpartyForwardingInfoDecodeErrorZ; class C2Tuple_u32ScriptZ; class CResult_SignedRawInvoiceParseErrorZ; +class COption_C2Tuple_EightU16sEightU16sZZ; class CResult_RouteDecodeErrorZ; class COption_NoneZ; @@ -454,6 +472,50 @@ public: const LDKStr* operator &() const { return &self; } const LDKStr* operator ->() const { return &self; } }; +class Retry { +private: + LDKRetry self; +public: + Retry(const Retry&) = delete; + Retry(Retry&& o) : self(o.self) { memset(&o, 0, sizeof(Retry)); } + Retry(LDKRetry&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRetry)); } + operator LDKRetry() && { LDKRetry res = self; memset(&self, 0, sizeof(LDKRetry)); return res; } + ~Retry() { Retry_free(self); } + Retry& operator=(Retry&& o) { Retry_free(self); self = o.self; memset(&o, 0, sizeof(Retry)); return *this; } + LDKRetry* operator &() { return &self; } + LDKRetry* operator ->() { return &self; } + const LDKRetry* operator &() const { return &self; } + const LDKRetry* operator ->() const { return &self; } +}; +class RetryableSendFailure { +private: + LDKRetryableSendFailure self; +public: + RetryableSendFailure(const RetryableSendFailure&) = delete; + RetryableSendFailure(RetryableSendFailure&& o) : self(o.self) { memset(&o, 0, sizeof(RetryableSendFailure)); } + RetryableSendFailure(LDKRetryableSendFailure&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRetryableSendFailure)); } + operator LDKRetryableSendFailure() && { LDKRetryableSendFailure res = self; memset(&self, 0, sizeof(LDKRetryableSendFailure)); return res; } + RetryableSendFailure& operator=(RetryableSendFailure&& o) { self = o.self; memset(&o, 0, sizeof(RetryableSendFailure)); return *this; } + LDKRetryableSendFailure* operator &() { return &self; } + LDKRetryableSendFailure* operator ->() { return &self; } + const LDKRetryableSendFailure* operator &() const { return &self; } + const LDKRetryableSendFailure* operator ->() const { return &self; } +}; +class PaymentSendFailure { +private: + LDKPaymentSendFailure self; +public: + PaymentSendFailure(const PaymentSendFailure&) = delete; + PaymentSendFailure(PaymentSendFailure&& o) : self(o.self) { memset(&o, 0, sizeof(PaymentSendFailure)); } + PaymentSendFailure(LDKPaymentSendFailure&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPaymentSendFailure)); } + operator LDKPaymentSendFailure() && { LDKPaymentSendFailure res = self; memset(&self, 0, sizeof(LDKPaymentSendFailure)); return res; } + ~PaymentSendFailure() { PaymentSendFailure_free(self); } + PaymentSendFailure& operator=(PaymentSendFailure&& o) { PaymentSendFailure_free(self); self = o.self; memset(&o, 0, sizeof(PaymentSendFailure)); return *this; } + LDKPaymentSendFailure* operator &() { return &self; } + LDKPaymentSendFailure* operator ->() { return &self; } + const LDKPaymentSendFailure* operator &() const { return &self; } + const LDKPaymentSendFailure* operator ->() const { return &self; } +}; class HTLCClaim { private: LDKHTLCClaim self; @@ -787,30 +849,14 @@ public: * * Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None */ - inline LDK::CResult_RouteLightningErrorZ find_route(struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, struct LDKInFlightHtlcs inflight_htlcs); + inline LDK::CResult_RouteLightningErrorZ find_route(struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, const struct LDKInFlightHtlcs *NONNULL_PTR inflight_htlcs); /** * Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes * `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment. * * Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None */ - inline LDK::CResult_RouteLightningErrorZ find_route_with_id(struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, struct LDKInFlightHtlcs inflight_htlcs, struct LDKThirtyTwoBytes _payment_hash, struct LDKThirtyTwoBytes _payment_id); - /** - * Lets the router know that payment through a specific path has failed. - */ - inline void notify_payment_path_failed(struct LDKCVec_RouteHopZ path, uint64_t short_channel_id); - /** - * Lets the router know that payment through a specific path was successful. - */ - inline void notify_payment_path_successful(struct LDKCVec_RouteHopZ path); - /** - * Lets the router know that a payment probe was successful. - */ - inline void notify_payment_probe_successful(struct LDKCVec_RouteHopZ path); - /** - * Lets the router know that a payment probe failed. - */ - inline void notify_payment_probe_failed(struct LDKCVec_RouteHopZ path, uint64_t short_channel_id); + inline LDK::CResult_RouteLightningErrorZ find_route_with_id(struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, const struct LDKInFlightHtlcs *NONNULL_PTR inflight_htlcs, struct LDKThirtyTwoBytes _payment_hash, struct LDKThirtyTwoBytes _payment_id); }; class ScorerAccountingForInFlightHtlcs { private: @@ -1006,6 +1052,21 @@ public: const LDKPaymentPurpose* operator &() const { return &self; } const LDKPaymentPurpose* operator ->() const { return &self; } }; +class PathFailure { +private: + LDKPathFailure self; +public: + PathFailure(const PathFailure&) = delete; + PathFailure(PathFailure&& o) : self(o.self) { memset(&o, 0, sizeof(PathFailure)); } + PathFailure(LDKPathFailure&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPathFailure)); } + operator LDKPathFailure() && { LDKPathFailure res = self; memset(&self, 0, sizeof(LDKPathFailure)); return res; } + ~PathFailure() { PathFailure_free(self); } + PathFailure& operator=(PathFailure&& o) { PathFailure_free(self); self = o.self; memset(&o, 0, sizeof(PathFailure)); return *this; } + LDKPathFailure* operator &() { return &self; } + LDKPathFailure* operator ->() { return &self; } + const LDKPathFailure* operator &() const { return &self; } + const LDKPathFailure* operator ->() const { return &self; } +}; class ClosureReason { private: LDKClosureReason self; @@ -1164,43 +1225,6 @@ public: const LDKBestBlock* operator &() const { return &self; } const LDKBestBlock* operator ->() const { return &self; } }; -class AccessError { -private: - LDKAccessError self; -public: - AccessError(const AccessError&) = delete; - AccessError(AccessError&& o) : self(o.self) { memset(&o, 0, sizeof(AccessError)); } - AccessError(LDKAccessError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKAccessError)); } - operator LDKAccessError() && { LDKAccessError res = self; memset(&self, 0, sizeof(LDKAccessError)); return res; } - AccessError& operator=(AccessError&& o) { self = o.self; memset(&o, 0, sizeof(AccessError)); return *this; } - LDKAccessError* operator &() { return &self; } - LDKAccessError* operator ->() { return &self; } - const LDKAccessError* operator &() const { return &self; } - const LDKAccessError* operator ->() const { return &self; } -}; -class Access { -private: - LDKAccess self; -public: - Access(const Access&) = delete; - Access(Access&& o) : self(o.self) { memset(&o, 0, sizeof(Access)); } - Access(LDKAccess&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKAccess)); } - operator LDKAccess() && { LDKAccess res = self; memset(&self, 0, sizeof(LDKAccess)); return res; } - ~Access() { Access_free(self); } - Access& operator=(Access&& o) { Access_free(self); self = o.self; memset(&o, 0, sizeof(Access)); return *this; } - LDKAccess* operator &() { return &self; } - LDKAccess* operator ->() { return &self; } - const LDKAccess* operator &() const { return &self; } - const LDKAccess* operator ->() const { return &self; } - /** - * Returns the transaction output of a funding transaction encoded by [`short_channel_id`]. - * Returns an error if `genesis_hash` is for a different chain or if such a transaction output - * is unknown. - * - * [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id - */ - inline LDK::CResult_TxOutAccessErrorZ get_utxo(const uint8_t (*genesis_hash)[32], uint64_t short_channel_id); -}; class Listen { private: LDKListen self; @@ -1282,6 +1306,9 @@ public: * Returns transactions that must be monitored for reorganization out of the chain along * with the hash of the block as part of which it had been previously confirmed. * + * Note that the returned `Option` might be `None` for channels created with LDK + * 0.0.112 and prior, in which case you need to manually track previous confirmations. + * * Will include any transactions passed to [`transactions_confirmed`] that have insufficient * confirmations to be safe from a chain reorganization. Will not include any transactions * passed to [`transaction_unconfirmed`], unless later reconfirmed. @@ -1351,7 +1378,7 @@ public: * * [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor */ - inline LDK::ChannelMonitorUpdateStatus update_channel(struct LDKOutPoint funding_txo, struct LDKChannelMonitorUpdate update); + inline LDK::ChannelMonitorUpdateStatus update_channel(struct LDKOutPoint funding_txo, const struct LDKChannelMonitorUpdate *NONNULL_PTR update); /** * Returns any monitor events since the last call. Subsequent calls must only return new * events. @@ -1665,6 +1692,36 @@ public: const LDKInvoiceRequestFeatures* operator &() const { return &self; } const LDKInvoiceRequestFeatures* operator ->() const { return &self; } }; +class Bolt12InvoiceFeatures { +private: + LDKBolt12InvoiceFeatures self; +public: + Bolt12InvoiceFeatures(const Bolt12InvoiceFeatures&) = delete; + Bolt12InvoiceFeatures(Bolt12InvoiceFeatures&& o) : self(o.self) { memset(&o, 0, sizeof(Bolt12InvoiceFeatures)); } + Bolt12InvoiceFeatures(LDKBolt12InvoiceFeatures&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKBolt12InvoiceFeatures)); } + operator LDKBolt12InvoiceFeatures() && { LDKBolt12InvoiceFeatures res = self; memset(&self, 0, sizeof(LDKBolt12InvoiceFeatures)); return res; } + ~Bolt12InvoiceFeatures() { Bolt12InvoiceFeatures_free(self); } + Bolt12InvoiceFeatures& operator=(Bolt12InvoiceFeatures&& o) { Bolt12InvoiceFeatures_free(self); self = o.self; memset(&o, 0, sizeof(Bolt12InvoiceFeatures)); return *this; } + LDKBolt12InvoiceFeatures* operator &() { return &self; } + LDKBolt12InvoiceFeatures* operator ->() { return &self; } + const LDKBolt12InvoiceFeatures* operator &() const { return &self; } + const LDKBolt12InvoiceFeatures* operator ->() const { return &self; } +}; +class BlindedHopFeatures { +private: + LDKBlindedHopFeatures self; +public: + BlindedHopFeatures(const BlindedHopFeatures&) = delete; + BlindedHopFeatures(BlindedHopFeatures&& o) : self(o.self) { memset(&o, 0, sizeof(BlindedHopFeatures)); } + BlindedHopFeatures(LDKBlindedHopFeatures&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKBlindedHopFeatures)); } + operator LDKBlindedHopFeatures() && { LDKBlindedHopFeatures res = self; memset(&self, 0, sizeof(LDKBlindedHopFeatures)); return res; } + ~BlindedHopFeatures() { BlindedHopFeatures_free(self); } + BlindedHopFeatures& operator=(BlindedHopFeatures&& o) { BlindedHopFeatures_free(self); self = o.self; memset(&o, 0, sizeof(BlindedHopFeatures)); return *this; } + LDKBlindedHopFeatures* operator &() { return &self; } + LDKBlindedHopFeatures* operator ->() { return &self; } + const LDKBlindedHopFeatures* operator &() const { return &self; } + const LDKBlindedHopFeatures* operator ->() const { return &self; } +}; class ChannelTypeFeatures { private: LDKChannelTypeFeatures self; @@ -1954,20 +2011,20 @@ public: const LDKSpendableOutputDescriptor* operator &() const { return &self; } const LDKSpendableOutputDescriptor* operator ->() const { return &self; } }; -class BaseSign { +class ChannelSigner { private: - LDKBaseSign self; + LDKChannelSigner self; public: - BaseSign(const BaseSign&) = delete; - BaseSign(BaseSign&& o) : self(o.self) { memset(&o, 0, sizeof(BaseSign)); } - BaseSign(LDKBaseSign&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKBaseSign)); } - operator LDKBaseSign() && { LDKBaseSign res = self; memset(&self, 0, sizeof(LDKBaseSign)); return res; } - ~BaseSign() { BaseSign_free(self); } - BaseSign& operator=(BaseSign&& o) { BaseSign_free(self); self = o.self; memset(&o, 0, sizeof(BaseSign)); return *this; } - LDKBaseSign* operator &() { return &self; } - LDKBaseSign* operator ->() { return &self; } - const LDKBaseSign* operator &() const { return &self; } - const LDKBaseSign* operator ->() const { return &self; } + ChannelSigner(const ChannelSigner&) = delete; + ChannelSigner(ChannelSigner&& o) : self(o.self) { memset(&o, 0, sizeof(ChannelSigner)); } + ChannelSigner(LDKChannelSigner&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKChannelSigner)); } + operator LDKChannelSigner() && { LDKChannelSigner res = self; memset(&self, 0, sizeof(LDKChannelSigner)); return res; } + ~ChannelSigner() { ChannelSigner_free(self); } + ChannelSigner& operator=(ChannelSigner&& o) { ChannelSigner_free(self); self = o.self; memset(&o, 0, sizeof(ChannelSigner)); return *this; } + LDKChannelSigner* operator &() { return &self; } + LDKChannelSigner* operator ->() { return &self; } + const LDKChannelSigner* operator &() const { return &self; } + const LDKChannelSigner* operator ->() const { return &self; } /** * Gets the per-commitment point for a specific commitment number * @@ -2004,9 +2061,36 @@ public: /** * Returns an arbitrary identifier describing the set of keys which are provided back to you in * some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this - * [`BaseSign`] object uniquely and lookup or re-derive its keys. + * [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys. */ inline LDKThirtyTwoBytes channel_keys_id(); + /** + * Set the counterparty static channel data, including basepoints, + * `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint. + * + * This data is static, and will never change for a channel once set. For a given [`ChannelSigner`] + * instance, LDK will call this method exactly once - either immediately after construction + * (not including if done via [`SignerProvider::read_chan_signer`]) or when the funding + * information has been generated. + * + * channel_parameters.is_populated() MUST be true. + */ + inline void provide_channel_parameters(const struct LDKChannelTransactionParameters *NONNULL_PTR channel_parameters); +}; +class EcdsaChannelSigner { +private: + LDKEcdsaChannelSigner self; +public: + EcdsaChannelSigner(const EcdsaChannelSigner&) = delete; + EcdsaChannelSigner(EcdsaChannelSigner&& o) : self(o.self) { memset(&o, 0, sizeof(EcdsaChannelSigner)); } + EcdsaChannelSigner(LDKEcdsaChannelSigner&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKEcdsaChannelSigner)); } + operator LDKEcdsaChannelSigner() && { LDKEcdsaChannelSigner res = self; memset(&self, 0, sizeof(LDKEcdsaChannelSigner)); return res; } + ~EcdsaChannelSigner() { EcdsaChannelSigner_free(self); } + EcdsaChannelSigner& operator=(EcdsaChannelSigner&& o) { EcdsaChannelSigner_free(self); self = o.self; memset(&o, 0, sizeof(EcdsaChannelSigner)); return *this; } + LDKEcdsaChannelSigner* operator &() { return &self; } + LDKEcdsaChannelSigner* operator ->() { return &self; } + const LDKEcdsaChannelSigner* operator &() const { return &self; } + const LDKEcdsaChannelSigner* operator ->() const { return &self; } /** * Create a signature for a counterparty's commitment transaction and associated HTLC transactions. * @@ -2119,41 +2203,32 @@ public: */ inline LDK::CResult_SignatureNoneZ sign_holder_anchor_input(struct LDKTransaction anchor_tx, uintptr_t input); /** - * Signs a channel announcement message with our funding key and our node secret key (aka - * node_id or network_key), proving it comes from one of the channel participants. + * Signs a channel announcement message with our funding key proving it comes from one of the + * channel participants. * - * The first returned signature should be from our node secret key, the second from our - * funding key. + * Channel announcements also require a signature from each node's network key. Our node + * signature is computed through [`NodeSigner::sign_gossip_message`]. * * Note that if this fails or is rejected, the channel will not be publicly announced and * our counterparty may (though likely will not) close the channel on us for violating the * protocol. */ - inline LDK::CResult_C2Tuple_SignatureSignatureZNoneZ sign_channel_announcement(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg); - /** - * Set the counterparty static channel data, including basepoints, - * `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint. Since these - * are static channel data, they MUST NOT be allowed to change to different values once set, - * as LDK may call this method more than once. - * - * channel_parameters.is_populated() MUST be true. - */ - inline void provide_channel_parameters(const struct LDKChannelTransactionParameters *NONNULL_PTR channel_parameters); + inline LDK::CResult_SignatureNoneZ sign_channel_announcement_with_funding_key(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg); }; -class Sign { +class WriteableEcdsaChannelSigner { private: - LDKSign self; + LDKWriteableEcdsaChannelSigner self; public: - Sign(const Sign&) = delete; - Sign(Sign&& o) : self(o.self) { memset(&o, 0, sizeof(Sign)); } - Sign(LDKSign&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKSign)); } - operator LDKSign() && { LDKSign res = self; memset(&self, 0, sizeof(LDKSign)); return res; } - ~Sign() { Sign_free(self); } - Sign& operator=(Sign&& o) { Sign_free(self); self = o.self; memset(&o, 0, sizeof(Sign)); return *this; } - LDKSign* operator &() { return &self; } - LDKSign* operator ->() { return &self; } - const LDKSign* operator &() const { return &self; } - const LDKSign* operator ->() const { return &self; } + WriteableEcdsaChannelSigner(const WriteableEcdsaChannelSigner&) = delete; + WriteableEcdsaChannelSigner(WriteableEcdsaChannelSigner&& o) : self(o.self) { memset(&o, 0, sizeof(WriteableEcdsaChannelSigner)); } + WriteableEcdsaChannelSigner(LDKWriteableEcdsaChannelSigner&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKWriteableEcdsaChannelSigner)); } + operator LDKWriteableEcdsaChannelSigner() && { LDKWriteableEcdsaChannelSigner res = self; memset(&self, 0, sizeof(LDKWriteableEcdsaChannelSigner)); return res; } + ~WriteableEcdsaChannelSigner() { WriteableEcdsaChannelSigner_free(self); } + WriteableEcdsaChannelSigner& operator=(WriteableEcdsaChannelSigner&& o) { WriteableEcdsaChannelSigner_free(self); self = o.self; memset(&o, 0, sizeof(WriteableEcdsaChannelSigner)); return *this; } + LDKWriteableEcdsaChannelSigner* operator &() { return &self; } + LDKWriteableEcdsaChannelSigner* operator ->() { return &self; } + const LDKWriteableEcdsaChannelSigner* operator &() const { return &self; } + const LDKWriteableEcdsaChannelSigner* operator ->() const { return &self; } }; class Recipient { private: @@ -2169,70 +2244,115 @@ public: const LDKRecipient* operator &() const { return &self; } const LDKRecipient* operator ->() const { return &self; } }; -class KeysInterface { +class EntropySource { +private: + LDKEntropySource self; +public: + EntropySource(const EntropySource&) = delete; + EntropySource(EntropySource&& o) : self(o.self) { memset(&o, 0, sizeof(EntropySource)); } + EntropySource(LDKEntropySource&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKEntropySource)); } + operator LDKEntropySource() && { LDKEntropySource res = self; memset(&self, 0, sizeof(LDKEntropySource)); return res; } + ~EntropySource() { EntropySource_free(self); } + EntropySource& operator=(EntropySource&& o) { EntropySource_free(self); self = o.self; memset(&o, 0, sizeof(EntropySource)); return *this; } + LDKEntropySource* operator &() { return &self; } + LDKEntropySource* operator ->() { return &self; } + const LDKEntropySource* operator &() const { return &self; } + const LDKEntropySource* operator ->() const { return &self; } + /** + * Gets a unique, cryptographically-secure, random 32-byte value. This method must return a + * different value each time it is called. + */ + inline LDKThirtyTwoBytes get_secure_random_bytes(); +}; +class NodeSigner { private: - LDKKeysInterface self; + LDKNodeSigner self; public: - KeysInterface(const KeysInterface&) = delete; - KeysInterface(KeysInterface&& o) : self(o.self) { memset(&o, 0, sizeof(KeysInterface)); } - KeysInterface(LDKKeysInterface&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKKeysInterface)); } - operator LDKKeysInterface() && { LDKKeysInterface res = self; memset(&self, 0, sizeof(LDKKeysInterface)); return res; } - ~KeysInterface() { KeysInterface_free(self); } - KeysInterface& operator=(KeysInterface&& o) { KeysInterface_free(self); self = o.self; memset(&o, 0, sizeof(KeysInterface)); return *this; } - LDKKeysInterface* operator &() { return &self; } - LDKKeysInterface* operator ->() { return &self; } - const LDKKeysInterface* operator &() const { return &self; } - const LDKKeysInterface* operator ->() const { return &self; } + NodeSigner(const NodeSigner&) = delete; + NodeSigner(NodeSigner&& o) : self(o.self) { memset(&o, 0, sizeof(NodeSigner)); } + NodeSigner(LDKNodeSigner&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKNodeSigner)); } + operator LDKNodeSigner() && { LDKNodeSigner res = self; memset(&self, 0, sizeof(LDKNodeSigner)); return res; } + ~NodeSigner() { NodeSigner_free(self); } + NodeSigner& operator=(NodeSigner&& o) { NodeSigner_free(self); self = o.self; memset(&o, 0, sizeof(NodeSigner)); return *this; } + LDKNodeSigner* operator &() { return &self; } + LDKNodeSigner* operator ->() { return &self; } + const LDKNodeSigner* operator &() const { return &self; } + const LDKNodeSigner* operator ->() const { return &self; } /** - * Get node secret key based on the provided [`Recipient`]. + * Get secret key material as bytes for use in encrypting and decrypting inbound payment data. * - * The `node_id`/`network_key` is the public key that corresponds to this secret key. + * If the implementor of this trait supports [phantom node payments], then every node that is + * intended to be included in the phantom invoice route hints must return the same value from + * this method. * - * This method must return the same value each time it is called with a given [`Recipient`] - * parameter. + * This method must return the same value each time it is called. * - * Errors if the [`Recipient`] variant is not supported by the implementation. + * [phantom node payments]: PhantomKeysManager */ - inline LDK::CResult_SecretKeyNoneZ get_node_secret(enum LDKRecipient recipient); + inline LDKThirtyTwoBytes get_inbound_payment_key_material(); /** - * Get node id based on the provided [`Recipient`]. This public key corresponds to the secret in - * [`get_node_secret`]. + * Get node id based on the provided [`Recipient`]. * * This method must return the same value each time it is called with a given [`Recipient`] * parameter. * * Errors if the [`Recipient`] variant is not supported by the implementation. - * - * [`get_node_secret`]: Self::get_node_secret */ inline LDK::CResult_PublicKeyNoneZ get_node_id(enum LDKRecipient recipient); /** - * Gets the ECDH shared secret of our [`node secret`] and `other_key`, multiplying by `tweak` if + * Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if * one is provided. Note that this tweak can be applied to `other_key` instead of our node * secret, though this is less efficient. * - * Errors if the [`Recipient`] variant is not supported by the implementation. + * Note that if this fails while attempting to forward an HTLC, LDK will panic. The error + * should be resolved to allow LDK to resume forwarding HTLCs. * - * [`node secret`]: Self::get_node_secret + * Errors if the [`Recipient`] variant is not supported by the implementation. */ inline LDK::CResult_SharedSecretNoneZ ecdh(enum LDKRecipient recipient, struct LDKPublicKey other_key, struct LDKCOption_ScalarZ tweak); /** - * Get a script pubkey which we send funds to when claiming on-chain contestable outputs. + * Sign an invoice. * - * This method should return a different value each time it is called, to avoid linking - * on-chain funds across channels as controlled to the same user. + * By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of + * this trait to parse the invoice and make sure they're signing what they expect, rather than + * blindly signing the hash. + * + * The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32. + * + * The secret key used to sign the invoice is dependent on the [`Recipient`]. + * + * Errors if the [`Recipient`] variant is not supported by the implementation. */ - inline LDK::CVec_u8Z get_destination_script(); + inline LDK::CResult_RecoverableSignatureNoneZ sign_invoice(struct LDKu8slice hrp_bytes, struct LDKCVec_U5Z invoice_data, enum LDKRecipient recipient); /** - * Get a script pubkey which we will send funds to when closing a channel. + * Sign a gossip message. * - * This method should return a different value each time it is called, to avoid linking - * on-chain funds across channels as controlled to the same user. + * Note that if this fails, LDK may panic and the message will not be broadcast to the network + * or a possible channel counterparty. If LDK panics, the error should be resolved to allow the + * message to be broadcast, as otherwise it may prevent one from receiving funds over the + * corresponding channel. */ - inline LDK::ShutdownScript get_shutdown_scriptpubkey(); + inline LDK::CResult_SignatureNoneZ sign_gossip_message(struct LDKUnsignedGossipMessage msg); +}; +class SignerProvider { +private: + LDKSignerProvider self; +public: + SignerProvider(const SignerProvider&) = delete; + SignerProvider(SignerProvider&& o) : self(o.self) { memset(&o, 0, sizeof(SignerProvider)); } + SignerProvider(LDKSignerProvider&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKSignerProvider)); } + operator LDKSignerProvider() && { LDKSignerProvider res = self; memset(&self, 0, sizeof(LDKSignerProvider)); return res; } + ~SignerProvider() { SignerProvider_free(self); } + SignerProvider& operator=(SignerProvider&& o) { SignerProvider_free(self); self = o.self; memset(&o, 0, sizeof(SignerProvider)); return *this; } + LDKSignerProvider* operator &() { return &self; } + LDKSignerProvider* operator ->() { return &self; } + const LDKSignerProvider* operator &() const { return &self; } + const LDKSignerProvider* operator ->() const { return &self; } /** - * Get a new set of [`Sign`] for per-channel secrets. These MUST be unique even if you - * restarted with some stale data! + * Generates a unique `channel_keys_id` that can be used to obtain a [`Self::Signer`] through + * [`SignerProvider::derive_channel_signer`]. The `user_channel_id` is provided to allow + * implementations of [`SignerProvider`] to maintain a mapping between itself and the generated + * `channel_keys_id`. * * This method must return a different value each time it is called. */ @@ -2241,23 +2361,15 @@ public: * Derives the private key material backing a `Signer`. * * To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through - * [`KeysInterface::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be + * [`SignerProvider::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be * re-derived from its `channel_keys_id`, which can be obtained through its trait method - * [`BaseSign::channel_keys_id`]. + * [`ChannelSigner::channel_keys_id`]. */ - inline LDK::Sign derive_channel_signer(uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id); + inline LDK::WriteableEcdsaChannelSigner derive_channel_signer(uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id); /** - * Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting - * onion packets and for temporary channel IDs. There is no requirement that these be - * persisted anywhere, though they must be unique across restarts. - * - * This method must return a different value each time it is called. - */ - inline LDKThirtyTwoBytes get_secure_random_bytes(); - /** - * Reads a [`Signer`] for this [`KeysInterface`] from the given input stream. + * Reads a [`Signer`] for this [`SignerProvider`] from the given input stream. * This is only called during deserialization of other objects which contain - * [`Sign`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s). + * [`WriteableEcdsaChannelSigner`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s). * The bytes are exactly those which `::write()` writes, and * contain no versioning scheme. You may wish to include your own version prefix and ensure * you've read all of the provided bytes to ensure no corruption occurred. @@ -2269,31 +2381,21 @@ public: * [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor * [`ChannelManager`]: crate::ln::channelmanager::ChannelManager */ - inline LDK::CResult_SignDecodeErrorZ read_chan_signer(struct LDKu8slice reader); + inline LDK::CResult_WriteableEcdsaChannelSignerDecodeErrorZ read_chan_signer(struct LDKu8slice reader); /** - * Sign an invoice. - * By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of - * this trait to parse the invoice and make sure they're signing what they expect, rather than - * blindly signing the hash. - * The `hrp` is ASCII bytes, while the invoice data is base32-encoded. - * - * The secret key used to sign the invoice is dependent on the [`Recipient`]. + * Get a script pubkey which we send funds to when claiming on-chain contestable outputs. * - * Errors if the [`Recipient`] variant is not supported by the implementation. + * This method should return a different value each time it is called, to avoid linking + * on-chain funds across channels as controlled to the same user. */ - inline LDK::CResult_RecoverableSignatureNoneZ sign_invoice(struct LDKu8slice hrp_bytes, struct LDKCVec_U5Z invoice_data, enum LDKRecipient receipient); + inline LDK::CVec_u8Z get_destination_script(); /** - * Get secret key material as bytes for use in encrypting and decrypting inbound payment data. - * - * If the implementor of this trait supports [phantom node payments], then every node that is - * intended to be included in the phantom invoice route hints must return the same value from - * this method. - * - * This method must return the same value each time it is called. + * Get a script pubkey which we will send funds to when closing a channel. * - * [phantom node payments]: PhantomKeysManager + * This method should return a different value each time it is called, to avoid linking + * on-chain funds across channels as controlled to the same user. */ - inline LDKThirtyTwoBytes get_inbound_payment_key_material(); + inline LDK::ShutdownScript get_shutdown_scriptpubkey(); }; class InMemorySigner { private: @@ -2355,6 +2457,20 @@ public: const LDKFilesystemPersister* operator &() const { return &self; } const LDKFilesystemPersister* operator ->() const { return &self; } }; +class FailureCode { +private: + LDKFailureCode self; +public: + FailureCode(const FailureCode&) = delete; + FailureCode(FailureCode&& o) : self(o.self) { memset(&o, 0, sizeof(FailureCode)); } + FailureCode(LDKFailureCode&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKFailureCode)); } + operator LDKFailureCode() && { LDKFailureCode res = self; memset(&self, 0, sizeof(LDKFailureCode)); return res; } + FailureCode& operator=(FailureCode&& o) { self = o.self; memset(&o, 0, sizeof(FailureCode)); return *this; } + LDKFailureCode* operator &() { return &self; } + LDKFailureCode* operator ->() { return &self; } + const LDKFailureCode* operator &() const { return &self; } + const LDKFailureCode* operator ->() const { return &self; } +}; class ChannelManager { private: LDKChannelManager self; @@ -2430,20 +2546,20 @@ public: const LDKChannelDetails* operator &() const { return &self; } const LDKChannelDetails* operator ->() const { return &self; } }; -class PaymentSendFailure { +class RecentPaymentDetails { private: - LDKPaymentSendFailure self; + LDKRecentPaymentDetails self; public: - PaymentSendFailure(const PaymentSendFailure&) = delete; - PaymentSendFailure(PaymentSendFailure&& o) : self(o.self) { memset(&o, 0, sizeof(PaymentSendFailure)); } - PaymentSendFailure(LDKPaymentSendFailure&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPaymentSendFailure)); } - operator LDKPaymentSendFailure() && { LDKPaymentSendFailure res = self; memset(&self, 0, sizeof(LDKPaymentSendFailure)); return res; } - ~PaymentSendFailure() { PaymentSendFailure_free(self); } - PaymentSendFailure& operator=(PaymentSendFailure&& o) { PaymentSendFailure_free(self); self = o.self; memset(&o, 0, sizeof(PaymentSendFailure)); return *this; } - LDKPaymentSendFailure* operator &() { return &self; } - LDKPaymentSendFailure* operator ->() { return &self; } - const LDKPaymentSendFailure* operator &() const { return &self; } - const LDKPaymentSendFailure* operator ->() const { return &self; } + RecentPaymentDetails(const RecentPaymentDetails&) = delete; + RecentPaymentDetails(RecentPaymentDetails&& o) : self(o.self) { memset(&o, 0, sizeof(RecentPaymentDetails)); } + RecentPaymentDetails(LDKRecentPaymentDetails&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRecentPaymentDetails)); } + operator LDKRecentPaymentDetails() && { LDKRecentPaymentDetails res = self; memset(&self, 0, sizeof(LDKRecentPaymentDetails)); return res; } + ~RecentPaymentDetails() { RecentPaymentDetails_free(self); } + RecentPaymentDetails& operator=(RecentPaymentDetails&& o) { RecentPaymentDetails_free(self); self = o.self; memset(&o, 0, sizeof(RecentPaymentDetails)); return *this; } + LDKRecentPaymentDetails* operator &() { return &self; } + LDKRecentPaymentDetails* operator ->() { return &self; } + const LDKRecentPaymentDetails* operator &() const { return &self; } + const LDKRecentPaymentDetails* operator ->() const { return &self; } }; class PhantomRouteHints { private: @@ -2655,82 +2771,6 @@ public: */ inline LDK::Str debug_str(); }; -class InvoicePayer { -private: - LDKInvoicePayer self; -public: - InvoicePayer(const InvoicePayer&) = delete; - InvoicePayer(InvoicePayer&& o) : self(o.self) { memset(&o, 0, sizeof(InvoicePayer)); } - InvoicePayer(LDKInvoicePayer&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKInvoicePayer)); } - operator LDKInvoicePayer() && { LDKInvoicePayer res = self; memset(&self, 0, sizeof(LDKInvoicePayer)); return res; } - ~InvoicePayer() { InvoicePayer_free(self); } - InvoicePayer& operator=(InvoicePayer&& o) { InvoicePayer_free(self); self = o.self; memset(&o, 0, sizeof(InvoicePayer)); return *this; } - LDKInvoicePayer* operator &() { return &self; } - LDKInvoicePayer* operator ->() { return &self; } - const LDKInvoicePayer* operator &() const { return &self; } - const LDKInvoicePayer* operator ->() const { return &self; } -}; -class Payer { -private: - LDKPayer self; -public: - Payer(const Payer&) = delete; - Payer(Payer&& o) : self(o.self) { memset(&o, 0, sizeof(Payer)); } - Payer(LDKPayer&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKPayer)); } - operator LDKPayer() && { LDKPayer res = self; memset(&self, 0, sizeof(LDKPayer)); return res; } - ~Payer() { Payer_free(self); } - Payer& operator=(Payer&& o) { Payer_free(self); self = o.self; memset(&o, 0, sizeof(Payer)); return *this; } - LDKPayer* operator &() { return &self; } - LDKPayer* operator ->() { return &self; } - const LDKPayer* operator &() const { return &self; } - const LDKPayer* operator ->() const { return &self; } - /** - * Returns the payer's node id. - */ - inline LDKPublicKey node_id(); - /** - * Returns the payer's channels. - */ - inline LDK::CVec_ChannelDetailsZ first_hops(); - /** - * Sends a payment over the Lightning Network using the given [`Route`]. - * - * Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None - */ - inline LDK::CResult_NonePaymentSendFailureZ send_payment(const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_hash, struct LDKThirtyTwoBytes payment_secret, struct LDKThirtyTwoBytes payment_id); - /** - * Sends a spontaneous payment over the Lightning Network using the given [`Route`]. - */ - inline LDK::CResult_NonePaymentSendFailureZ send_spontaneous_payment(const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_preimage, struct LDKThirtyTwoBytes payment_id); - /** - * Retries a failed payment path for the [`PaymentId`] using the given [`Route`]. - */ - inline LDK::CResult_NonePaymentSendFailureZ retry_payment(const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_id); - /** - * Signals that no further retries for the given payment will occur. - */ - inline void abandon_payment(struct LDKThirtyTwoBytes payment_id); - /** - * Construct an [`InFlightHtlcs`] containing information about currently used up liquidity - * across payments. - */ - inline LDK::InFlightHtlcs inflight_htlcs(); -}; -class Retry { -private: - LDKRetry self; -public: - Retry(const Retry&) = delete; - Retry(Retry&& o) : self(o.self) { memset(&o, 0, sizeof(Retry)); } - Retry(LDKRetry&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKRetry)); } - operator LDKRetry() && { LDKRetry res = self; memset(&self, 0, sizeof(LDKRetry)); return res; } - ~Retry() { Retry_free(self); } - Retry& operator=(Retry&& o) { Retry_free(self); self = o.self; memset(&o, 0, sizeof(Retry)); return *this; } - LDKRetry* operator &() { return &self; } - LDKRetry* operator ->() { return &self; } - const LDKRetry* operator &() const { return &self; } - const LDKRetry* operator ->() const { return &self; } -}; class PaymentError { private: LDKPaymentError self; @@ -2851,15 +2891,15 @@ public: const LDKCustomMessageHandler* operator &() const { return &self; } const LDKCustomMessageHandler* operator ->() const { return &self; } /** - * Called with the message type that was received and the buffer to be read. - * Can return a `MessageHandlingError` if the message could not be handled. + * Handles the given message sent from `sender_node_id`, possibly producing messages for + * [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`] + * to send. */ inline LDK::CResult_NoneLightningErrorZ handle_custom_message(struct LDKType msg, struct LDKPublicKey sender_node_id); /** - * Gets the list of pending messages which were generated by the custom message - * handler, clearing the list in the process. The first tuple element must - * correspond to the intended recipients node ids. If no connection to one of the - * specified node does not exist, the message is simply not sent to it. + * Returns the list of pending messages that were generated by the handler, clearing the list + * in the process. Each message is paired with the node id of the intended recipient. If no + * connection to the node exists, then the message is simply not sent. */ inline LDK::CVec_C2Tuple_PublicKeyTypeZZ get_and_clear_pending_msg(); }; @@ -2987,6 +3027,73 @@ public: const LDKPeerManager* operator &() const { return &self; } const LDKPeerManager* operator ->() const { return &self; } }; +class UtxoLookupError { +private: + LDKUtxoLookupError self; +public: + UtxoLookupError(const UtxoLookupError&) = delete; + UtxoLookupError(UtxoLookupError&& o) : self(o.self) { memset(&o, 0, sizeof(UtxoLookupError)); } + UtxoLookupError(LDKUtxoLookupError&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUtxoLookupError)); } + operator LDKUtxoLookupError() && { LDKUtxoLookupError res = self; memset(&self, 0, sizeof(LDKUtxoLookupError)); return res; } + UtxoLookupError& operator=(UtxoLookupError&& o) { self = o.self; memset(&o, 0, sizeof(UtxoLookupError)); return *this; } + LDKUtxoLookupError* operator &() { return &self; } + LDKUtxoLookupError* operator ->() { return &self; } + const LDKUtxoLookupError* operator &() const { return &self; } + const LDKUtxoLookupError* operator ->() const { return &self; } +}; +class UtxoResult { +private: + LDKUtxoResult self; +public: + UtxoResult(const UtxoResult&) = delete; + UtxoResult(UtxoResult&& o) : self(o.self) { memset(&o, 0, sizeof(UtxoResult)); } + UtxoResult(LDKUtxoResult&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUtxoResult)); } + operator LDKUtxoResult() && { LDKUtxoResult res = self; memset(&self, 0, sizeof(LDKUtxoResult)); return res; } + ~UtxoResult() { UtxoResult_free(self); } + UtxoResult& operator=(UtxoResult&& o) { UtxoResult_free(self); self = o.self; memset(&o, 0, sizeof(UtxoResult)); return *this; } + LDKUtxoResult* operator &() { return &self; } + LDKUtxoResult* operator ->() { return &self; } + const LDKUtxoResult* operator &() const { return &self; } + const LDKUtxoResult* operator ->() const { return &self; } +}; +class UtxoLookup { +private: + LDKUtxoLookup self; +public: + UtxoLookup(const UtxoLookup&) = delete; + UtxoLookup(UtxoLookup&& o) : self(o.self) { memset(&o, 0, sizeof(UtxoLookup)); } + UtxoLookup(LDKUtxoLookup&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUtxoLookup)); } + operator LDKUtxoLookup() && { LDKUtxoLookup res = self; memset(&self, 0, sizeof(LDKUtxoLookup)); return res; } + ~UtxoLookup() { UtxoLookup_free(self); } + UtxoLookup& operator=(UtxoLookup&& o) { UtxoLookup_free(self); self = o.self; memset(&o, 0, sizeof(UtxoLookup)); return *this; } + LDKUtxoLookup* operator &() { return &self; } + LDKUtxoLookup* operator ->() { return &self; } + const LDKUtxoLookup* operator &() const { return &self; } + const LDKUtxoLookup* operator ->() const { return &self; } + /** + * Returns the transaction output of a funding transaction encoded by [`short_channel_id`]. + * Returns an error if `genesis_hash` is for a different chain or if such a transaction output + * is unknown. + * + * [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id + */ + inline LDK::UtxoResult get_utxo(const uint8_t (*genesis_hash)[32], uint64_t short_channel_id); +}; +class UtxoFuture { +private: + LDKUtxoFuture self; +public: + UtxoFuture(const UtxoFuture&) = delete; + UtxoFuture(UtxoFuture&& o) : self(o.self) { memset(&o, 0, sizeof(UtxoFuture)); } + UtxoFuture(LDKUtxoFuture&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUtxoFuture)); } + operator LDKUtxoFuture() && { LDKUtxoFuture res = self; memset(&self, 0, sizeof(LDKUtxoFuture)); return res; } + ~UtxoFuture() { UtxoFuture_free(self); } + UtxoFuture& operator=(UtxoFuture&& o) { UtxoFuture_free(self); self = o.self; memset(&o, 0, sizeof(UtxoFuture)); return *this; } + LDKUtxoFuture* operator &() { return &self; } + LDKUtxoFuture* operator ->() { return &self; } + const LDKUtxoFuture* operator &() const { return &self; } + const LDKUtxoFuture* operator ->() const { return &self; } +}; class OnionMessenger { private: LDKOnionMessenger self; @@ -3249,20 +3356,20 @@ public: const LDKExpiryTime* operator &() const { return &self; } const LDKExpiryTime* operator ->() const { return &self; } }; -class MinFinalCltvExpiry { +class MinFinalCltvExpiryDelta { private: - LDKMinFinalCltvExpiry self; + LDKMinFinalCltvExpiryDelta self; public: - MinFinalCltvExpiry(const MinFinalCltvExpiry&) = delete; - MinFinalCltvExpiry(MinFinalCltvExpiry&& o) : self(o.self) { memset(&o, 0, sizeof(MinFinalCltvExpiry)); } - MinFinalCltvExpiry(LDKMinFinalCltvExpiry&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMinFinalCltvExpiry)); } - operator LDKMinFinalCltvExpiry() && { LDKMinFinalCltvExpiry res = self; memset(&self, 0, sizeof(LDKMinFinalCltvExpiry)); return res; } - ~MinFinalCltvExpiry() { MinFinalCltvExpiry_free(self); } - MinFinalCltvExpiry& operator=(MinFinalCltvExpiry&& o) { MinFinalCltvExpiry_free(self); self = o.self; memset(&o, 0, sizeof(MinFinalCltvExpiry)); return *this; } - LDKMinFinalCltvExpiry* operator &() { return &self; } - LDKMinFinalCltvExpiry* operator ->() { return &self; } - const LDKMinFinalCltvExpiry* operator &() const { return &self; } - const LDKMinFinalCltvExpiry* operator ->() const { return &self; } + MinFinalCltvExpiryDelta(const MinFinalCltvExpiryDelta&) = delete; + MinFinalCltvExpiryDelta(MinFinalCltvExpiryDelta&& o) : self(o.self) { memset(&o, 0, sizeof(MinFinalCltvExpiryDelta)); } + MinFinalCltvExpiryDelta(LDKMinFinalCltvExpiryDelta&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKMinFinalCltvExpiryDelta)); } + operator LDKMinFinalCltvExpiryDelta() && { LDKMinFinalCltvExpiryDelta res = self; memset(&self, 0, sizeof(LDKMinFinalCltvExpiryDelta)); return res; } + ~MinFinalCltvExpiryDelta() { MinFinalCltvExpiryDelta_free(self); } + MinFinalCltvExpiryDelta& operator=(MinFinalCltvExpiryDelta&& o) { MinFinalCltvExpiryDelta_free(self); self = o.self; memset(&o, 0, sizeof(MinFinalCltvExpiryDelta)); return *this; } + LDKMinFinalCltvExpiryDelta* operator &() { return &self; } + LDKMinFinalCltvExpiryDelta* operator ->() { return &self; } + const LDKMinFinalCltvExpiryDelta* operator &() const { return &self; } + const LDKMinFinalCltvExpiryDelta* operator ->() const { return &self; } }; class Fallback { private: @@ -3784,6 +3891,21 @@ public: const LDKNetAddress* operator &() const { return &self; } const LDKNetAddress* operator ->() const { return &self; } }; +class UnsignedGossipMessage { +private: + LDKUnsignedGossipMessage self; +public: + UnsignedGossipMessage(const UnsignedGossipMessage&) = delete; + UnsignedGossipMessage(UnsignedGossipMessage&& o) : self(o.self) { memset(&o, 0, sizeof(UnsignedGossipMessage)); } + UnsignedGossipMessage(LDKUnsignedGossipMessage&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKUnsignedGossipMessage)); } + operator LDKUnsignedGossipMessage() && { LDKUnsignedGossipMessage res = self; memset(&self, 0, sizeof(LDKUnsignedGossipMessage)); return res; } + ~UnsignedGossipMessage() { UnsignedGossipMessage_free(self); } + UnsignedGossipMessage& operator=(UnsignedGossipMessage&& o) { UnsignedGossipMessage_free(self); self = o.self; memset(&o, 0, sizeof(UnsignedGossipMessage)); return *this; } + LDKUnsignedGossipMessage* operator &() { return &self; } + LDKUnsignedGossipMessage* operator ->() { return &self; } + const LDKUnsignedGossipMessage* operator &() const { return &self; } + const LDKUnsignedGossipMessage* operator ->() const { return &self; } +}; class UnsignedNodeAnnouncement { private: LDKUnsignedNodeAnnouncement self; @@ -4009,93 +4131,87 @@ public: const LDKChannelMessageHandler* operator &() const { return &self; } const LDKChannelMessageHandler* operator ->() const { return &self; } /** - * Handle an incoming open_channel message from the given peer. + * Handle an incoming `open_channel` message from the given peer. */ - inline void handle_open_channel(struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKOpenChannel *NONNULL_PTR msg); + inline void handle_open_channel(struct LDKPublicKey their_node_id, const struct LDKOpenChannel *NONNULL_PTR msg); /** - * Handle an incoming accept_channel message from the given peer. + * Handle an incoming `accept_channel` message from the given peer. */ - inline void handle_accept_channel(struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKAcceptChannel *NONNULL_PTR msg); + inline void handle_accept_channel(struct LDKPublicKey their_node_id, const struct LDKAcceptChannel *NONNULL_PTR msg); /** - * Handle an incoming funding_created message from the given peer. + * Handle an incoming `funding_created` message from the given peer. */ inline void handle_funding_created(struct LDKPublicKey their_node_id, const struct LDKFundingCreated *NONNULL_PTR msg); /** - * Handle an incoming funding_signed message from the given peer. + * Handle an incoming `funding_signed` message from the given peer. */ inline void handle_funding_signed(struct LDKPublicKey their_node_id, const struct LDKFundingSigned *NONNULL_PTR msg); /** - * Handle an incoming channel_ready message from the given peer. + * Handle an incoming `channel_ready` message from the given peer. */ inline void handle_channel_ready(struct LDKPublicKey their_node_id, const struct LDKChannelReady *NONNULL_PTR msg); /** - * Handle an incoming shutdown message from the given peer. + * Handle an incoming `shutdown` message from the given peer. */ - inline void handle_shutdown(struct LDKPublicKey their_node_id, const struct LDKInitFeatures *NONNULL_PTR their_features, const struct LDKShutdown *NONNULL_PTR msg); + inline void handle_shutdown(struct LDKPublicKey their_node_id, const struct LDKShutdown *NONNULL_PTR msg); /** - * Handle an incoming closing_signed message from the given peer. + * Handle an incoming `closing_signed` message from the given peer. */ inline void handle_closing_signed(struct LDKPublicKey their_node_id, const struct LDKClosingSigned *NONNULL_PTR msg); /** - * Handle an incoming update_add_htlc message from the given peer. + * Handle an incoming `update_add_htlc` message from the given peer. */ inline void handle_update_add_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateAddHTLC *NONNULL_PTR msg); /** - * Handle an incoming update_fulfill_htlc message from the given peer. + * Handle an incoming `update_fulfill_htlc` message from the given peer. */ inline void handle_update_fulfill_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateFulfillHTLC *NONNULL_PTR msg); /** - * Handle an incoming update_fail_htlc message from the given peer. + * Handle an incoming `update_fail_htlc` message from the given peer. */ inline void handle_update_fail_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateFailHTLC *NONNULL_PTR msg); /** - * Handle an incoming update_fail_malformed_htlc message from the given peer. + * Handle an incoming `update_fail_malformed_htlc` message from the given peer. */ inline void handle_update_fail_malformed_htlc(struct LDKPublicKey their_node_id, const struct LDKUpdateFailMalformedHTLC *NONNULL_PTR msg); /** - * Handle an incoming commitment_signed message from the given peer. + * Handle an incoming `commitment_signed` message from the given peer. */ inline void handle_commitment_signed(struct LDKPublicKey their_node_id, const struct LDKCommitmentSigned *NONNULL_PTR msg); /** - * Handle an incoming revoke_and_ack message from the given peer. + * Handle an incoming `revoke_and_ack` message from the given peer. */ inline void handle_revoke_and_ack(struct LDKPublicKey their_node_id, const struct LDKRevokeAndACK *NONNULL_PTR msg); /** - * Handle an incoming update_fee message from the given peer. + * Handle an incoming `update_fee` message from the given peer. */ inline void handle_update_fee(struct LDKPublicKey their_node_id, const struct LDKUpdateFee *NONNULL_PTR msg); /** - * Handle an incoming announcement_signatures message from the given peer. + * Handle an incoming `announcement_signatures` message from the given peer. */ inline void handle_announcement_signatures(struct LDKPublicKey their_node_id, const struct LDKAnnouncementSignatures *NONNULL_PTR msg); /** - * Indicates a connection to the peer failed/an existing connection was lost. If no connection - * is believed to be possible in the future (eg they're sending us messages we don't - * understand or indicate they require unknown feature bits), no_connection_possible is set - * and any outstanding channels should be failed. - * - * Note that in some rare cases this may be called without a corresponding - * [`Self::peer_connected`]. + * Indicates a connection to the peer failed/an existing connection was lost. */ - inline void peer_disconnected(struct LDKPublicKey their_node_id, bool no_connection_possible); + inline void peer_disconnected(struct LDKPublicKey their_node_id); /** - * Handle a peer reconnecting, possibly generating channel_reestablish message(s). + * Handle a peer reconnecting, possibly generating `channel_reestablish` message(s). * * May return an `Err(())` if the features the peer supports are not sufficient to communicate * with us. Implementors should be somewhat conservative about doing so, however, as other * message handlers may still wish to communicate with this peer. */ - inline LDK::CResult_NoneNoneZ peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR msg); + inline LDK::CResult_NoneNoneZ peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR msg, bool inbound); /** - * Handle an incoming channel_reestablish message from the given peer. + * Handle an incoming `channel_reestablish` message from the given peer. */ inline void handle_channel_reestablish(struct LDKPublicKey their_node_id, const struct LDKChannelReestablish *NONNULL_PTR msg); /** - * Handle an incoming channel update from the given peer. + * Handle an incoming `channel_update` message from the given peer. */ inline void handle_channel_update(struct LDKPublicKey their_node_id, const struct LDKChannelUpdate *NONNULL_PTR msg); /** - * Handle an incoming error message from the given peer. + * Handle an incoming `error` message from the given peer. */ inline void handle_error(struct LDKPublicKey their_node_id, const struct LDKErrorMessage *NONNULL_PTR msg); /** @@ -4128,36 +4244,36 @@ public: const LDKRoutingMessageHandler* operator &() const { return &self; } const LDKRoutingMessageHandler* operator ->() const { return &self; } /** - * Handle an incoming node_announcement message, returning true if it should be forwarded on, - * false or returning an Err otherwise. + * Handle an incoming `node_announcement` message, returning `true` if it should be forwarded on, + * `false` or returning an `Err` otherwise. */ inline LDK::CResult_boolLightningErrorZ handle_node_announcement(const struct LDKNodeAnnouncement *NONNULL_PTR msg); /** - * Handle a channel_announcement message, returning true if it should be forwarded on, false - * or returning an Err otherwise. + * Handle a `channel_announcement` message, returning `true` if it should be forwarded on, `false` + * or returning an `Err` otherwise. */ inline LDK::CResult_boolLightningErrorZ handle_channel_announcement(const struct LDKChannelAnnouncement *NONNULL_PTR msg); /** - * Handle an incoming channel_update message, returning true if it should be forwarded on, - * false or returning an Err otherwise. + * Handle an incoming `channel_update` message, returning true if it should be forwarded on, + * `false` or returning an `Err` otherwise. */ inline LDK::CResult_boolLightningErrorZ handle_channel_update(const struct LDKChannelUpdate *NONNULL_PTR msg); /** * Gets channel announcements and updates required to dump our routing table to a remote node, - * starting at the short_channel_id indicated by starting_point and including announcements + * starting at the `short_channel_id` indicated by `starting_point` and including announcements * for a single channel. */ inline LDK::COption_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ get_next_channel_announcement(uint64_t starting_point); /** * Gets a node announcement required to dump our routing table to a remote node, starting at * the node *after* the provided pubkey and including up to one announcement immediately - * higher (as defined by ::cmp) than starting_point. - * If None is provided for starting_point, we start at the first node. + * higher (as defined by `::cmp`) than `starting_point`. + * If `None` is provided for `starting_point`, we start at the first node. * * Note that starting_point (or a relevant inner pointer) may be NULL or all-0s to represent None * Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None */ - inline LDK::NodeAnnouncement get_next_node_announcement(struct LDKPublicKey starting_point); + inline LDK::NodeAnnouncement get_next_node_announcement(struct LDKNodeId starting_point); /** * Called when a connection is established with a peer. This can be used to * perform routing table synchronization using a strategy defined by the @@ -4167,7 +4283,7 @@ public: * with us. Implementors should be somewhat conservative about doing so, however, as other * message handlers may still wish to communicate with this peer. */ - inline LDK::CResult_NoneNoneZ peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init); + inline LDK::CResult_NoneNoneZ peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init, bool inbound); /** * Handles the reply of a query we initiated to learn about channels * for a given range of blocks. We can expect to receive one or more @@ -4182,15 +4298,22 @@ public: */ inline LDK::CResult_NoneLightningErrorZ handle_reply_short_channel_ids_end(struct LDKPublicKey their_node_id, struct LDKReplyShortChannelIdsEnd msg); /** - * Handles when a peer asks us to send a list of short_channel_ids + * Handles when a peer asks us to send a list of `short_channel_id`s * for the requested range of blocks. */ inline LDK::CResult_NoneLightningErrorZ handle_query_channel_range(struct LDKPublicKey their_node_id, struct LDKQueryChannelRange msg); /** * Handles when a peer asks us to send routing gossip messages for a - * list of short_channel_ids. + * list of `short_channel_id`s. */ inline LDK::CResult_NoneLightningErrorZ handle_query_short_channel_ids(struct LDKPublicKey their_node_id, struct LDKQueryShortChannelIds msg); + /** + * Indicates that there are a large number of [`ChannelAnnouncement`] (or other) messages + * pending some async action. While there is no guarantee of the rate of future messages, the + * caller should seek to reduce the rate of new gossip messages handled, especially + * [`ChannelAnnouncement`]s. + */ + inline bool processing_queue_high(); /** * Gets the node feature flags which this handler itself supports. All available handlers are * queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`] @@ -4221,7 +4344,7 @@ public: const LDKOnionMessageHandler* operator &() const { return &self; } const LDKOnionMessageHandler* operator ->() const { return &self; } /** - * Handle an incoming onion_message message from the given peer. + * Handle an incoming `onion_message` message from the given peer. */ inline void handle_onion_message(struct LDKPublicKey peer_node_id, const struct LDKOnionMessage *NONNULL_PTR msg); /** @@ -4232,15 +4355,12 @@ public: * with us. Implementors should be somewhat conservative about doing so, however, as other * message handlers may still wish to communicate with this peer. */ - inline LDK::CResult_NoneNoneZ peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init); + inline LDK::CResult_NoneNoneZ peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init, bool inbound); /** * Indicates a connection to the peer failed/an existing connection was lost. Allows handlers to * drop and refuse to forward onion messages to this peer. - * - * Note that in some rare cases this may be called without a corresponding - * [`Self::peer_connected`]. */ - inline void peer_disconnected(struct LDKPublicKey their_node_id, bool no_connection_possible); + inline void peer_disconnected(struct LDKPublicKey their_node_id); /** * Gets the node feature flags which this handler itself supports. All available handlers are * queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`] @@ -4437,7 +4557,7 @@ public: * * Note that update (or a relevant inner pointer) may be NULL or all-0s to represent None */ - inline LDK::ChannelMonitorUpdateStatus update_persisted_channel(struct LDKOutPoint channel_id, const struct LDKChannelMonitorUpdate *NONNULL_PTR update, const struct LDKChannelMonitor *NONNULL_PTR data, struct LDKMonitorUpdateId update_id); + inline LDK::ChannelMonitorUpdateStatus update_persisted_channel(struct LDKOutPoint channel_id, struct LDKChannelMonitorUpdate update, const struct LDKChannelMonitor *NONNULL_PTR data, struct LDKMonitorUpdateId update_id); }; class LockedChannelMonitor { private: @@ -4709,20 +4829,20 @@ public: const LDKCOption_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator &() const { return &self; } const LDKCOption_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ* operator ->() const { return &self; } }; -class CResult_CommitmentSignedDecodeErrorZ { +class CResult_COption_APIErrorZDecodeErrorZ { private: - LDKCResult_CommitmentSignedDecodeErrorZ self; + LDKCResult_COption_APIErrorZDecodeErrorZ self; public: - CResult_CommitmentSignedDecodeErrorZ(const CResult_CommitmentSignedDecodeErrorZ&) = delete; - CResult_CommitmentSignedDecodeErrorZ(CResult_CommitmentSignedDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CommitmentSignedDecodeErrorZ)); } - CResult_CommitmentSignedDecodeErrorZ(LDKCResult_CommitmentSignedDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CommitmentSignedDecodeErrorZ)); } - operator LDKCResult_CommitmentSignedDecodeErrorZ() && { LDKCResult_CommitmentSignedDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CommitmentSignedDecodeErrorZ)); return res; } - ~CResult_CommitmentSignedDecodeErrorZ() { CResult_CommitmentSignedDecodeErrorZ_free(self); } - CResult_CommitmentSignedDecodeErrorZ& operator=(CResult_CommitmentSignedDecodeErrorZ&& o) { CResult_CommitmentSignedDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CommitmentSignedDecodeErrorZ)); return *this; } - LDKCResult_CommitmentSignedDecodeErrorZ* operator &() { return &self; } - LDKCResult_CommitmentSignedDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_CommitmentSignedDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_CommitmentSignedDecodeErrorZ* operator ->() const { return &self; } + CResult_COption_APIErrorZDecodeErrorZ(const CResult_COption_APIErrorZDecodeErrorZ&) = delete; + CResult_COption_APIErrorZDecodeErrorZ(CResult_COption_APIErrorZDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_COption_APIErrorZDecodeErrorZ)); } + CResult_COption_APIErrorZDecodeErrorZ(LDKCResult_COption_APIErrorZDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_COption_APIErrorZDecodeErrorZ)); } + operator LDKCResult_COption_APIErrorZDecodeErrorZ() && { LDKCResult_COption_APIErrorZDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_COption_APIErrorZDecodeErrorZ)); return res; } + ~CResult_COption_APIErrorZDecodeErrorZ() { CResult_COption_APIErrorZDecodeErrorZ_free(self); } + CResult_COption_APIErrorZDecodeErrorZ& operator=(CResult_COption_APIErrorZDecodeErrorZ&& o) { CResult_COption_APIErrorZDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_COption_APIErrorZDecodeErrorZ)); return *this; } + LDKCResult_COption_APIErrorZDecodeErrorZ* operator &() { return &self; } + LDKCResult_COption_APIErrorZDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_COption_APIErrorZDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_COption_APIErrorZDecodeErrorZ* operator ->() const { return &self; } }; class CVec_UpdateAddHTLCZ { private: @@ -4739,6 +4859,21 @@ public: const LDKCVec_UpdateAddHTLCZ* operator &() const { return &self; } const LDKCVec_UpdateAddHTLCZ* operator ->() const { return &self; } }; +class CResult_CommitmentSignedDecodeErrorZ { +private: + LDKCResult_CommitmentSignedDecodeErrorZ self; +public: + CResult_CommitmentSignedDecodeErrorZ(const CResult_CommitmentSignedDecodeErrorZ&) = delete; + CResult_CommitmentSignedDecodeErrorZ(CResult_CommitmentSignedDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CommitmentSignedDecodeErrorZ)); } + CResult_CommitmentSignedDecodeErrorZ(LDKCResult_CommitmentSignedDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CommitmentSignedDecodeErrorZ)); } + operator LDKCResult_CommitmentSignedDecodeErrorZ() && { LDKCResult_CommitmentSignedDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CommitmentSignedDecodeErrorZ)); return res; } + ~CResult_CommitmentSignedDecodeErrorZ() { CResult_CommitmentSignedDecodeErrorZ_free(self); } + CResult_CommitmentSignedDecodeErrorZ& operator=(CResult_CommitmentSignedDecodeErrorZ&& o) { CResult_CommitmentSignedDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CommitmentSignedDecodeErrorZ)); return *this; } + LDKCResult_CommitmentSignedDecodeErrorZ* operator &() { return &self; } + LDKCResult_CommitmentSignedDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_CommitmentSignedDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_CommitmentSignedDecodeErrorZ* operator ->() const { return &self; } +}; class COption_u32Z { private: LDKCOption_u32Z self; @@ -4859,6 +4994,21 @@ public: const LDKCResult_OpenChannelDecodeErrorZ* operator &() const { return &self; } const LDKCResult_OpenChannelDecodeErrorZ* operator ->() const { return &self; } }; +class COption_APIErrorZ { +private: + LDKCOption_APIErrorZ self; +public: + COption_APIErrorZ(const COption_APIErrorZ&) = delete; + COption_APIErrorZ(COption_APIErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(COption_APIErrorZ)); } + COption_APIErrorZ(LDKCOption_APIErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCOption_APIErrorZ)); } + operator LDKCOption_APIErrorZ() && { LDKCOption_APIErrorZ res = self; memset(&self, 0, sizeof(LDKCOption_APIErrorZ)); return res; } + ~COption_APIErrorZ() { COption_APIErrorZ_free(self); } + COption_APIErrorZ& operator=(COption_APIErrorZ&& o) { COption_APIErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(COption_APIErrorZ)); return *this; } + LDKCOption_APIErrorZ* operator &() { return &self; } + LDKCOption_APIErrorZ* operator ->() { return &self; } + const LDKCOption_APIErrorZ* operator &() const { return &self; } + const LDKCOption_APIErrorZ* operator ->() const { return &self; } +}; class CResult_QueryChannelRangeDecodeErrorZ { private: LDKCResult_QueryChannelRangeDecodeErrorZ self; @@ -5069,6 +5219,21 @@ public: const LDKCResult_COption_NetworkUpdateZDecodeErrorZ* operator &() const { return &self; } const LDKCResult_COption_NetworkUpdateZDecodeErrorZ* operator ->() const { return &self; } }; +class CResult_NoneRetryableSendFailureZ { +private: + LDKCResult_NoneRetryableSendFailureZ self; +public: + CResult_NoneRetryableSendFailureZ(const CResult_NoneRetryableSendFailureZ&) = delete; + CResult_NoneRetryableSendFailureZ(CResult_NoneRetryableSendFailureZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NoneRetryableSendFailureZ)); } + CResult_NoneRetryableSendFailureZ(LDKCResult_NoneRetryableSendFailureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NoneRetryableSendFailureZ)); } + operator LDKCResult_NoneRetryableSendFailureZ() && { LDKCResult_NoneRetryableSendFailureZ res = self; memset(&self, 0, sizeof(LDKCResult_NoneRetryableSendFailureZ)); return res; } + ~CResult_NoneRetryableSendFailureZ() { CResult_NoneRetryableSendFailureZ_free(self); } + CResult_NoneRetryableSendFailureZ& operator=(CResult_NoneRetryableSendFailureZ&& o) { CResult_NoneRetryableSendFailureZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NoneRetryableSendFailureZ)); return *this; } + LDKCResult_NoneRetryableSendFailureZ* operator &() { return &self; } + LDKCResult_NoneRetryableSendFailureZ* operator ->() { return &self; } + const LDKCResult_NoneRetryableSendFailureZ* operator &() const { return &self; } + const LDKCResult_NoneRetryableSendFailureZ* operator ->() const { return &self; } +}; class CVec_UpdateFailMalformedHTLCZ { private: LDKCVec_UpdateFailMalformedHTLCZ self; @@ -5099,6 +5264,21 @@ public: const LDKCVec_C2Tuple_OutPointCVec_MonitorUpdateIdZZZ* operator &() const { return &self; } const LDKCVec_C2Tuple_OutPointCVec_MonitorUpdateIdZZZ* operator ->() const { return &self; } }; +class CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ { +private: + LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ self; +public: + CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ(const CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ&) = delete; + CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ(CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ)); } + CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ(LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ)); } + operator LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ() && { LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ res = self; memset(&self, 0, sizeof(LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ)); return res; } + ~CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ() { CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ_free(self); } + CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ& operator=(CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ&& o) { CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ)); return *this; } + LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ* operator &() { return &self; } + LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ* operator ->() { return &self; } + const LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ* operator &() const { return &self; } + const LDKCVec_C2Tuple_PublicKeyCOption_NetAddressZZZ* operator ->() const { return &self; } +}; class CVec_RouteHopZ { private: LDKCVec_RouteHopZ self; @@ -5219,6 +5399,21 @@ public: const LDKCResult_CounterpartyCommitmentSecretsDecodeErrorZ* operator &() const { return &self; } const LDKCResult_CounterpartyCommitmentSecretsDecodeErrorZ* operator ->() const { return &self; } }; +class CVec_RecentPaymentDetailsZ { +private: + LDKCVec_RecentPaymentDetailsZ self; +public: + CVec_RecentPaymentDetailsZ(const CVec_RecentPaymentDetailsZ&) = delete; + CVec_RecentPaymentDetailsZ(CVec_RecentPaymentDetailsZ&& o) : self(o.self) { memset(&o, 0, sizeof(CVec_RecentPaymentDetailsZ)); } + CVec_RecentPaymentDetailsZ(LDKCVec_RecentPaymentDetailsZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCVec_RecentPaymentDetailsZ)); } + operator LDKCVec_RecentPaymentDetailsZ() && { LDKCVec_RecentPaymentDetailsZ res = self; memset(&self, 0, sizeof(LDKCVec_RecentPaymentDetailsZ)); return res; } + ~CVec_RecentPaymentDetailsZ() { CVec_RecentPaymentDetailsZ_free(self); } + CVec_RecentPaymentDetailsZ& operator=(CVec_RecentPaymentDetailsZ&& o) { CVec_RecentPaymentDetailsZ_free(self); self = o.self; memset(&o, 0, sizeof(CVec_RecentPaymentDetailsZ)); return *this; } + LDKCVec_RecentPaymentDetailsZ* operator &() { return &self; } + LDKCVec_RecentPaymentDetailsZ* operator ->() { return &self; } + const LDKCVec_RecentPaymentDetailsZ* operator &() const { return &self; } + const LDKCVec_RecentPaymentDetailsZ* operator ->() const { return &self; } +}; class CResult_C2Tuple_PaymentHashPaymentSecretZNoneZ { private: LDKCResult_C2Tuple_PaymentHashPaymentSecretZNoneZ self; @@ -5279,50 +5474,20 @@ public: const LDKCVec_U5Z* operator &() const { return &self; } const LDKCVec_U5Z* operator ->() const { return &self; } }; -class CResult_SignDecodeErrorZ { -private: - LDKCResult_SignDecodeErrorZ self; -public: - CResult_SignDecodeErrorZ(const CResult_SignDecodeErrorZ&) = delete; - CResult_SignDecodeErrorZ(CResult_SignDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SignDecodeErrorZ)); } - CResult_SignDecodeErrorZ(LDKCResult_SignDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SignDecodeErrorZ)); } - operator LDKCResult_SignDecodeErrorZ() && { LDKCResult_SignDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_SignDecodeErrorZ)); return res; } - ~CResult_SignDecodeErrorZ() { CResult_SignDecodeErrorZ_free(self); } - CResult_SignDecodeErrorZ& operator=(CResult_SignDecodeErrorZ&& o) { CResult_SignDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_SignDecodeErrorZ)); return *this; } - LDKCResult_SignDecodeErrorZ* operator &() { return &self; } - LDKCResult_SignDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_SignDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_SignDecodeErrorZ* operator ->() const { return &self; } -}; -class CResult_UnsignedChannelAnnouncementDecodeErrorZ { -private: - LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ self; -public: - CResult_UnsignedChannelAnnouncementDecodeErrorZ(const CResult_UnsignedChannelAnnouncementDecodeErrorZ&) = delete; - CResult_UnsignedChannelAnnouncementDecodeErrorZ(CResult_UnsignedChannelAnnouncementDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UnsignedChannelAnnouncementDecodeErrorZ)); } - CResult_UnsignedChannelAnnouncementDecodeErrorZ(LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ)); } - operator LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ() && { LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ)); return res; } - ~CResult_UnsignedChannelAnnouncementDecodeErrorZ() { CResult_UnsignedChannelAnnouncementDecodeErrorZ_free(self); } - CResult_UnsignedChannelAnnouncementDecodeErrorZ& operator=(CResult_UnsignedChannelAnnouncementDecodeErrorZ&& o) { CResult_UnsignedChannelAnnouncementDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UnsignedChannelAnnouncementDecodeErrorZ)); return *this; } - LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator &() { return &self; } - LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator ->() const { return &self; } -}; -class COption_AccessZ { +class COption_UtxoLookupZ { private: - LDKCOption_AccessZ self; + LDKCOption_UtxoLookupZ self; public: - COption_AccessZ(const COption_AccessZ&) = delete; - COption_AccessZ(COption_AccessZ&& o) : self(o.self) { memset(&o, 0, sizeof(COption_AccessZ)); } - COption_AccessZ(LDKCOption_AccessZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCOption_AccessZ)); } - operator LDKCOption_AccessZ() && { LDKCOption_AccessZ res = self; memset(&self, 0, sizeof(LDKCOption_AccessZ)); return res; } - ~COption_AccessZ() { COption_AccessZ_free(self); } - COption_AccessZ& operator=(COption_AccessZ&& o) { COption_AccessZ_free(self); self = o.self; memset(&o, 0, sizeof(COption_AccessZ)); return *this; } - LDKCOption_AccessZ* operator &() { return &self; } - LDKCOption_AccessZ* operator ->() { return &self; } - const LDKCOption_AccessZ* operator &() const { return &self; } - const LDKCOption_AccessZ* operator ->() const { return &self; } + COption_UtxoLookupZ(const COption_UtxoLookupZ&) = delete; + COption_UtxoLookupZ(COption_UtxoLookupZ&& o) : self(o.self) { memset(&o, 0, sizeof(COption_UtxoLookupZ)); } + COption_UtxoLookupZ(LDKCOption_UtxoLookupZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCOption_UtxoLookupZ)); } + operator LDKCOption_UtxoLookupZ() && { LDKCOption_UtxoLookupZ res = self; memset(&self, 0, sizeof(LDKCOption_UtxoLookupZ)); return res; } + ~COption_UtxoLookupZ() { COption_UtxoLookupZ_free(self); } + COption_UtxoLookupZ& operator=(COption_UtxoLookupZ&& o) { COption_UtxoLookupZ_free(self); self = o.self; memset(&o, 0, sizeof(COption_UtxoLookupZ)); return *this; } + LDKCOption_UtxoLookupZ* operator &() { return &self; } + LDKCOption_UtxoLookupZ* operator ->() { return &self; } + const LDKCOption_UtxoLookupZ* operator &() const { return &self; } + const LDKCOption_UtxoLookupZ* operator ->() const { return &self; } }; class CResult_PongDecodeErrorZ { private: @@ -5339,6 +5504,21 @@ public: const LDKCResult_PongDecodeErrorZ* operator &() const { return &self; } const LDKCResult_PongDecodeErrorZ* operator ->() const { return &self; } }; +class CResult_UnsignedChannelAnnouncementDecodeErrorZ { +private: + LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ self; +public: + CResult_UnsignedChannelAnnouncementDecodeErrorZ(const CResult_UnsignedChannelAnnouncementDecodeErrorZ&) = delete; + CResult_UnsignedChannelAnnouncementDecodeErrorZ(CResult_UnsignedChannelAnnouncementDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_UnsignedChannelAnnouncementDecodeErrorZ)); } + CResult_UnsignedChannelAnnouncementDecodeErrorZ(LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ)); } + operator LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ() && { LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ)); return res; } + ~CResult_UnsignedChannelAnnouncementDecodeErrorZ() { CResult_UnsignedChannelAnnouncementDecodeErrorZ_free(self); } + CResult_UnsignedChannelAnnouncementDecodeErrorZ& operator=(CResult_UnsignedChannelAnnouncementDecodeErrorZ&& o) { CResult_UnsignedChannelAnnouncementDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_UnsignedChannelAnnouncementDecodeErrorZ)); return *this; } + LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator &() { return &self; } + LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_UnsignedChannelAnnouncementDecodeErrorZ* operator ->() const { return &self; } +}; class C2Tuple_OutPointCVec_MonitorUpdateIdZZ { private: LDKC2Tuple_OutPointCVec_MonitorUpdateIdZZ self; @@ -5369,21 +5549,6 @@ public: const LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ* operator &() const { return &self; } const LDKCResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ* operator ->() const { return &self; } }; -class C2Tuple_SignatureSignatureZ { -private: - LDKC2Tuple_SignatureSignatureZ self; -public: - C2Tuple_SignatureSignatureZ(const C2Tuple_SignatureSignatureZ&) = delete; - C2Tuple_SignatureSignatureZ(C2Tuple_SignatureSignatureZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_SignatureSignatureZ)); } - C2Tuple_SignatureSignatureZ(LDKC2Tuple_SignatureSignatureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_SignatureSignatureZ)); } - operator LDKC2Tuple_SignatureSignatureZ() && { LDKC2Tuple_SignatureSignatureZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_SignatureSignatureZ)); return res; } - ~C2Tuple_SignatureSignatureZ() { C2Tuple_SignatureSignatureZ_free(self); } - C2Tuple_SignatureSignatureZ& operator=(C2Tuple_SignatureSignatureZ&& o) { C2Tuple_SignatureSignatureZ_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_SignatureSignatureZ)); return *this; } - LDKC2Tuple_SignatureSignatureZ* operator &() { return &self; } - LDKC2Tuple_SignatureSignatureZ* operator ->() { return &self; } - const LDKC2Tuple_SignatureSignatureZ* operator &() const { return &self; } - const LDKC2Tuple_SignatureSignatureZ* operator ->() const { return &self; } -}; class C2Tuple_BlockHashChannelManagerZ { private: LDKC2Tuple_BlockHashChannelManagerZ self; @@ -5414,6 +5579,21 @@ public: const LDKCResult_ChannelTransactionParametersDecodeErrorZ* operator &() const { return &self; } const LDKCResult_ChannelTransactionParametersDecodeErrorZ* operator ->() const { return &self; } }; +class CResult_WriteableEcdsaChannelSignerDecodeErrorZ { +private: + LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ self; +public: + CResult_WriteableEcdsaChannelSignerDecodeErrorZ(const CResult_WriteableEcdsaChannelSignerDecodeErrorZ&) = delete; + CResult_WriteableEcdsaChannelSignerDecodeErrorZ(CResult_WriteableEcdsaChannelSignerDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_WriteableEcdsaChannelSignerDecodeErrorZ)); } + CResult_WriteableEcdsaChannelSignerDecodeErrorZ(LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ)); } + operator LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ() && { LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ)); return res; } + ~CResult_WriteableEcdsaChannelSignerDecodeErrorZ() { CResult_WriteableEcdsaChannelSignerDecodeErrorZ_free(self); } + CResult_WriteableEcdsaChannelSignerDecodeErrorZ& operator=(CResult_WriteableEcdsaChannelSignerDecodeErrorZ&& o) { CResult_WriteableEcdsaChannelSignerDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_WriteableEcdsaChannelSignerDecodeErrorZ)); return *this; } + LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ* operator &() { return &self; } + LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_WriteableEcdsaChannelSignerDecodeErrorZ* operator ->() const { return &self; } +}; class CResult_DelayedPaymentOutputDescriptorDecodeErrorZ { private: LDKCResult_DelayedPaymentOutputDescriptorDecodeErrorZ self; @@ -5579,20 +5759,35 @@ public: const LDKCResult_NoneLightningErrorZ* operator &() const { return &self; } const LDKCResult_NoneLightningErrorZ* operator ->() const { return &self; } }; -class CResult_NonePeerHandleErrorZ { +class CResult_PaymentHashRetryableSendFailureZ { private: - LDKCResult_NonePeerHandleErrorZ self; + LDKCResult_PaymentHashRetryableSendFailureZ self; public: - CResult_NonePeerHandleErrorZ(const CResult_NonePeerHandleErrorZ&) = delete; - CResult_NonePeerHandleErrorZ(CResult_NonePeerHandleErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NonePeerHandleErrorZ)); } - CResult_NonePeerHandleErrorZ(LDKCResult_NonePeerHandleErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NonePeerHandleErrorZ)); } - operator LDKCResult_NonePeerHandleErrorZ() && { LDKCResult_NonePeerHandleErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NonePeerHandleErrorZ)); return res; } - ~CResult_NonePeerHandleErrorZ() { CResult_NonePeerHandleErrorZ_free(self); } - CResult_NonePeerHandleErrorZ& operator=(CResult_NonePeerHandleErrorZ&& o) { CResult_NonePeerHandleErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NonePeerHandleErrorZ)); return *this; } - LDKCResult_NonePeerHandleErrorZ* operator &() { return &self; } - LDKCResult_NonePeerHandleErrorZ* operator ->() { return &self; } - const LDKCResult_NonePeerHandleErrorZ* operator &() const { return &self; } - const LDKCResult_NonePeerHandleErrorZ* operator ->() const { return &self; } + CResult_PaymentHashRetryableSendFailureZ(const CResult_PaymentHashRetryableSendFailureZ&) = delete; + CResult_PaymentHashRetryableSendFailureZ(CResult_PaymentHashRetryableSendFailureZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_PaymentHashRetryableSendFailureZ)); } + CResult_PaymentHashRetryableSendFailureZ(LDKCResult_PaymentHashRetryableSendFailureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_PaymentHashRetryableSendFailureZ)); } + operator LDKCResult_PaymentHashRetryableSendFailureZ() && { LDKCResult_PaymentHashRetryableSendFailureZ res = self; memset(&self, 0, sizeof(LDKCResult_PaymentHashRetryableSendFailureZ)); return res; } + ~CResult_PaymentHashRetryableSendFailureZ() { CResult_PaymentHashRetryableSendFailureZ_free(self); } + CResult_PaymentHashRetryableSendFailureZ& operator=(CResult_PaymentHashRetryableSendFailureZ&& o) { CResult_PaymentHashRetryableSendFailureZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_PaymentHashRetryableSendFailureZ)); return *this; } + LDKCResult_PaymentHashRetryableSendFailureZ* operator &() { return &self; } + LDKCResult_PaymentHashRetryableSendFailureZ* operator ->() { return &self; } + const LDKCResult_PaymentHashRetryableSendFailureZ* operator &() const { return &self; } + const LDKCResult_PaymentHashRetryableSendFailureZ* operator ->() const { return &self; } +}; +class C2Tuple_PublicKeyCOption_NetAddressZZ { +private: + LDKC2Tuple_PublicKeyCOption_NetAddressZZ self; +public: + C2Tuple_PublicKeyCOption_NetAddressZZ(const C2Tuple_PublicKeyCOption_NetAddressZZ&) = delete; + C2Tuple_PublicKeyCOption_NetAddressZZ(C2Tuple_PublicKeyCOption_NetAddressZZ&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_PublicKeyCOption_NetAddressZZ)); } + C2Tuple_PublicKeyCOption_NetAddressZZ(LDKC2Tuple_PublicKeyCOption_NetAddressZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_PublicKeyCOption_NetAddressZZ)); } + operator LDKC2Tuple_PublicKeyCOption_NetAddressZZ() && { LDKC2Tuple_PublicKeyCOption_NetAddressZZ res = self; memset(&self, 0, sizeof(LDKC2Tuple_PublicKeyCOption_NetAddressZZ)); return res; } + ~C2Tuple_PublicKeyCOption_NetAddressZZ() { C2Tuple_PublicKeyCOption_NetAddressZZ_free(self); } + C2Tuple_PublicKeyCOption_NetAddressZZ& operator=(C2Tuple_PublicKeyCOption_NetAddressZZ&& o) { C2Tuple_PublicKeyCOption_NetAddressZZ_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_PublicKeyCOption_NetAddressZZ)); return *this; } + LDKC2Tuple_PublicKeyCOption_NetAddressZZ* operator &() { return &self; } + LDKC2Tuple_PublicKeyCOption_NetAddressZZ* operator ->() { return &self; } + const LDKC2Tuple_PublicKeyCOption_NetAddressZZ* operator &() const { return &self; } + const LDKC2Tuple_PublicKeyCOption_NetAddressZZ* operator ->() const { return &self; } }; class CResult_COption_EventZDecodeErrorZ { private: @@ -5639,6 +5834,21 @@ public: const LDKCOption_CVec_NetAddressZZ* operator &() const { return &self; } const LDKCOption_CVec_NetAddressZZ* operator ->() const { return &self; } }; +class CResult_NonePeerHandleErrorZ { +private: + LDKCResult_NonePeerHandleErrorZ self; +public: + CResult_NonePeerHandleErrorZ(const CResult_NonePeerHandleErrorZ&) = delete; + CResult_NonePeerHandleErrorZ(CResult_NonePeerHandleErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_NonePeerHandleErrorZ)); } + CResult_NonePeerHandleErrorZ(LDKCResult_NonePeerHandleErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_NonePeerHandleErrorZ)); } + operator LDKCResult_NonePeerHandleErrorZ() && { LDKCResult_NonePeerHandleErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_NonePeerHandleErrorZ)); return res; } + ~CResult_NonePeerHandleErrorZ() { CResult_NonePeerHandleErrorZ_free(self); } + CResult_NonePeerHandleErrorZ& operator=(CResult_NonePeerHandleErrorZ&& o) { CResult_NonePeerHandleErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_NonePeerHandleErrorZ)); return *this; } + LDKCResult_NonePeerHandleErrorZ* operator &() { return &self; } + LDKCResult_NonePeerHandleErrorZ* operator ->() { return &self; } + const LDKCResult_NonePeerHandleErrorZ* operator &() const { return &self; } + const LDKCResult_NonePeerHandleErrorZ* operator ->() const { return &self; } +}; class CResult__u832APIErrorZ { private: LDKCResult__u832APIErrorZ self; @@ -5819,6 +6029,21 @@ public: const LDKCResult_COption_TypeZDecodeErrorZ* operator &() const { return &self; } const LDKCResult_COption_TypeZDecodeErrorZ* operator ->() const { return &self; } }; +class CResult_COption_PathFailureZDecodeErrorZ { +private: + LDKCResult_COption_PathFailureZDecodeErrorZ self; +public: + CResult_COption_PathFailureZDecodeErrorZ(const CResult_COption_PathFailureZDecodeErrorZ&) = delete; + CResult_COption_PathFailureZDecodeErrorZ(CResult_COption_PathFailureZDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_COption_PathFailureZDecodeErrorZ)); } + CResult_COption_PathFailureZDecodeErrorZ(LDKCResult_COption_PathFailureZDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_COption_PathFailureZDecodeErrorZ)); } + operator LDKCResult_COption_PathFailureZDecodeErrorZ() && { LDKCResult_COption_PathFailureZDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_COption_PathFailureZDecodeErrorZ)); return res; } + ~CResult_COption_PathFailureZDecodeErrorZ() { CResult_COption_PathFailureZDecodeErrorZ_free(self); } + CResult_COption_PathFailureZDecodeErrorZ& operator=(CResult_COption_PathFailureZDecodeErrorZ&& o) { CResult_COption_PathFailureZDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_COption_PathFailureZDecodeErrorZ)); return *this; } + LDKCResult_COption_PathFailureZDecodeErrorZ* operator &() { return &self; } + LDKCResult_COption_PathFailureZDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_COption_PathFailureZDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_COption_PathFailureZDecodeErrorZ* operator ->() const { return &self; } +}; class CResult_UpdateFailHTLCDecodeErrorZ { private: LDKCResult_UpdateFailHTLCDecodeErrorZ self; @@ -6119,6 +6344,21 @@ public: const LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ* operator &() const { return &self; } const LDKCResult_ReplyShortChannelIdsEndDecodeErrorZ* operator ->() const { return &self; } }; +class COption_PathFailureZ { +private: + LDKCOption_PathFailureZ self; +public: + COption_PathFailureZ(const COption_PathFailureZ&) = delete; + COption_PathFailureZ(COption_PathFailureZ&& o) : self(o.self) { memset(&o, 0, sizeof(COption_PathFailureZ)); } + COption_PathFailureZ(LDKCOption_PathFailureZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCOption_PathFailureZ)); } + operator LDKCOption_PathFailureZ() && { LDKCOption_PathFailureZ res = self; memset(&self, 0, sizeof(LDKCOption_PathFailureZ)); return res; } + ~COption_PathFailureZ() { COption_PathFailureZ_free(self); } + COption_PathFailureZ& operator=(COption_PathFailureZ&& o) { COption_PathFailureZ_free(self); self = o.self; memset(&o, 0, sizeof(COption_PathFailureZ)); return *this; } + LDKCOption_PathFailureZ* operator &() { return &self; } + LDKCOption_PathFailureZ* operator ->() { return &self; } + const LDKCOption_PathFailureZ* operator &() const { return &self; } + const LDKCOption_PathFailureZ* operator ->() const { return &self; } +}; class COption_ScalarZ { private: LDKCOption_ScalarZ self; @@ -6254,20 +6494,20 @@ public: const LDKCResult_ChannelAnnouncementDecodeErrorZ* operator &() const { return &self; } const LDKCResult_ChannelAnnouncementDecodeErrorZ* operator ->() const { return &self; } }; -class CResult_OfferFeaturesDecodeErrorZ { +class CResult_HTLCUpdateDecodeErrorZ { private: - LDKCResult_OfferFeaturesDecodeErrorZ self; + LDKCResult_HTLCUpdateDecodeErrorZ self; public: - CResult_OfferFeaturesDecodeErrorZ(const CResult_OfferFeaturesDecodeErrorZ&) = delete; - CResult_OfferFeaturesDecodeErrorZ(CResult_OfferFeaturesDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_OfferFeaturesDecodeErrorZ)); } - CResult_OfferFeaturesDecodeErrorZ(LDKCResult_OfferFeaturesDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_OfferFeaturesDecodeErrorZ)); } - operator LDKCResult_OfferFeaturesDecodeErrorZ() && { LDKCResult_OfferFeaturesDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_OfferFeaturesDecodeErrorZ)); return res; } - ~CResult_OfferFeaturesDecodeErrorZ() { CResult_OfferFeaturesDecodeErrorZ_free(self); } - CResult_OfferFeaturesDecodeErrorZ& operator=(CResult_OfferFeaturesDecodeErrorZ&& o) { CResult_OfferFeaturesDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_OfferFeaturesDecodeErrorZ)); return *this; } - LDKCResult_OfferFeaturesDecodeErrorZ* operator &() { return &self; } - LDKCResult_OfferFeaturesDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_OfferFeaturesDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_OfferFeaturesDecodeErrorZ* operator ->() const { return &self; } + CResult_HTLCUpdateDecodeErrorZ(const CResult_HTLCUpdateDecodeErrorZ&) = delete; + CResult_HTLCUpdateDecodeErrorZ(CResult_HTLCUpdateDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_HTLCUpdateDecodeErrorZ)); } + CResult_HTLCUpdateDecodeErrorZ(LDKCResult_HTLCUpdateDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_HTLCUpdateDecodeErrorZ)); } + operator LDKCResult_HTLCUpdateDecodeErrorZ() && { LDKCResult_HTLCUpdateDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_HTLCUpdateDecodeErrorZ)); return res; } + ~CResult_HTLCUpdateDecodeErrorZ() { CResult_HTLCUpdateDecodeErrorZ_free(self); } + CResult_HTLCUpdateDecodeErrorZ& operator=(CResult_HTLCUpdateDecodeErrorZ&& o) { CResult_HTLCUpdateDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_HTLCUpdateDecodeErrorZ)); return *this; } + LDKCResult_HTLCUpdateDecodeErrorZ* operator &() { return &self; } + LDKCResult_HTLCUpdateDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_HTLCUpdateDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_HTLCUpdateDecodeErrorZ* operator ->() const { return &self; } }; class C2Tuple_SignatureCVec_SignatureZZ { private: @@ -6284,21 +6524,6 @@ public: const LDKC2Tuple_SignatureCVec_SignatureZZ* operator &() const { return &self; } const LDKC2Tuple_SignatureCVec_SignatureZZ* operator ->() const { return &self; } }; -class CResult_HTLCUpdateDecodeErrorZ { -private: - LDKCResult_HTLCUpdateDecodeErrorZ self; -public: - CResult_HTLCUpdateDecodeErrorZ(const CResult_HTLCUpdateDecodeErrorZ&) = delete; - CResult_HTLCUpdateDecodeErrorZ(CResult_HTLCUpdateDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_HTLCUpdateDecodeErrorZ)); } - CResult_HTLCUpdateDecodeErrorZ(LDKCResult_HTLCUpdateDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_HTLCUpdateDecodeErrorZ)); } - operator LDKCResult_HTLCUpdateDecodeErrorZ() && { LDKCResult_HTLCUpdateDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_HTLCUpdateDecodeErrorZ)); return res; } - ~CResult_HTLCUpdateDecodeErrorZ() { CResult_HTLCUpdateDecodeErrorZ_free(self); } - CResult_HTLCUpdateDecodeErrorZ& operator=(CResult_HTLCUpdateDecodeErrorZ&& o) { CResult_HTLCUpdateDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_HTLCUpdateDecodeErrorZ)); return *this; } - LDKCResult_HTLCUpdateDecodeErrorZ* operator &() { return &self; } - LDKCResult_HTLCUpdateDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_HTLCUpdateDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_HTLCUpdateDecodeErrorZ* operator ->() const { return &self; } -}; class CVec_OutPointZ { private: LDKCVec_OutPointZ self; @@ -6344,6 +6569,21 @@ public: const LDKCResult_PositiveTimestampCreationErrorZ* operator &() const { return &self; } const LDKCResult_PositiveTimestampCreationErrorZ* operator ->() const { return &self; } }; +class C2Tuple__u168_u168Z { +private: + LDKC2Tuple__u168_u168Z self; +public: + C2Tuple__u168_u168Z(const C2Tuple__u168_u168Z&) = delete; + C2Tuple__u168_u168Z(C2Tuple__u168_u168Z&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple__u168_u168Z)); } + C2Tuple__u168_u168Z(LDKC2Tuple__u168_u168Z&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple__u168_u168Z)); } + operator LDKC2Tuple__u168_u168Z() && { LDKC2Tuple__u168_u168Z res = self; memset(&self, 0, sizeof(LDKC2Tuple__u168_u168Z)); return res; } + ~C2Tuple__u168_u168Z() { C2Tuple__u168_u168Z_free(self); } + C2Tuple__u168_u168Z& operator=(C2Tuple__u168_u168Z&& o) { C2Tuple__u168_u168Z_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple__u168_u168Z)); return *this; } + LDKC2Tuple__u168_u168Z* operator &() { return &self; } + LDKC2Tuple__u168_u168Z* operator ->() { return &self; } + const LDKC2Tuple__u168_u168Z* operator &() const { return &self; } + const LDKC2Tuple__u168_u168Z* operator ->() const { return &self; } +}; class CResult_InvoiceFeaturesDecodeErrorZ { private: LDKCResult_InvoiceFeaturesDecodeErrorZ self; @@ -6389,20 +6629,20 @@ public: const LDKCResult_ReplyChannelRangeDecodeErrorZ* operator &() const { return &self; } const LDKCResult_ReplyChannelRangeDecodeErrorZ* operator ->() const { return &self; } }; -class CResult_TxOutAccessErrorZ { +class CResult_InvoiceSignOrCreationErrorZ { private: - LDKCResult_TxOutAccessErrorZ self; + LDKCResult_InvoiceSignOrCreationErrorZ self; public: - CResult_TxOutAccessErrorZ(const CResult_TxOutAccessErrorZ&) = delete; - CResult_TxOutAccessErrorZ(CResult_TxOutAccessErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_TxOutAccessErrorZ)); } - CResult_TxOutAccessErrorZ(LDKCResult_TxOutAccessErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_TxOutAccessErrorZ)); } - operator LDKCResult_TxOutAccessErrorZ() && { LDKCResult_TxOutAccessErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_TxOutAccessErrorZ)); return res; } - ~CResult_TxOutAccessErrorZ() { CResult_TxOutAccessErrorZ_free(self); } - CResult_TxOutAccessErrorZ& operator=(CResult_TxOutAccessErrorZ&& o) { CResult_TxOutAccessErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_TxOutAccessErrorZ)); return *this; } - LDKCResult_TxOutAccessErrorZ* operator &() { return &self; } - LDKCResult_TxOutAccessErrorZ* operator ->() { return &self; } - const LDKCResult_TxOutAccessErrorZ* operator &() const { return &self; } - const LDKCResult_TxOutAccessErrorZ* operator ->() const { return &self; } + CResult_InvoiceSignOrCreationErrorZ(const CResult_InvoiceSignOrCreationErrorZ&) = delete; + CResult_InvoiceSignOrCreationErrorZ(CResult_InvoiceSignOrCreationErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InvoiceSignOrCreationErrorZ)); } + CResult_InvoiceSignOrCreationErrorZ(LDKCResult_InvoiceSignOrCreationErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InvoiceSignOrCreationErrorZ)); } + operator LDKCResult_InvoiceSignOrCreationErrorZ() && { LDKCResult_InvoiceSignOrCreationErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InvoiceSignOrCreationErrorZ)); return res; } + ~CResult_InvoiceSignOrCreationErrorZ() { CResult_InvoiceSignOrCreationErrorZ_free(self); } + CResult_InvoiceSignOrCreationErrorZ& operator=(CResult_InvoiceSignOrCreationErrorZ&& o) { CResult_InvoiceSignOrCreationErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InvoiceSignOrCreationErrorZ)); return *this; } + LDKCResult_InvoiceSignOrCreationErrorZ* operator &() { return &self; } + LDKCResult_InvoiceSignOrCreationErrorZ* operator ->() { return &self; } + const LDKCResult_InvoiceSignOrCreationErrorZ* operator &() const { return &self; } + const LDKCResult_InvoiceSignOrCreationErrorZ* operator ->() const { return &self; } }; class CResult_TrustedClosingTransactionNoneZ { private: @@ -6494,21 +6734,6 @@ public: const LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ* operator &() const { return &self; } const LDKCResult_UnsignedNodeAnnouncementDecodeErrorZ* operator ->() const { return &self; } }; -class CResult_InvoiceSignOrCreationErrorZ { -private: - LDKCResult_InvoiceSignOrCreationErrorZ self; -public: - CResult_InvoiceSignOrCreationErrorZ(const CResult_InvoiceSignOrCreationErrorZ&) = delete; - CResult_InvoiceSignOrCreationErrorZ(CResult_InvoiceSignOrCreationErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InvoiceSignOrCreationErrorZ)); } - CResult_InvoiceSignOrCreationErrorZ(LDKCResult_InvoiceSignOrCreationErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InvoiceSignOrCreationErrorZ)); } - operator LDKCResult_InvoiceSignOrCreationErrorZ() && { LDKCResult_InvoiceSignOrCreationErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InvoiceSignOrCreationErrorZ)); return res; } - ~CResult_InvoiceSignOrCreationErrorZ() { CResult_InvoiceSignOrCreationErrorZ_free(self); } - CResult_InvoiceSignOrCreationErrorZ& operator=(CResult_InvoiceSignOrCreationErrorZ&& o) { CResult_InvoiceSignOrCreationErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InvoiceSignOrCreationErrorZ)); return *this; } - LDKCResult_InvoiceSignOrCreationErrorZ* operator &() { return &self; } - LDKCResult_InvoiceSignOrCreationErrorZ* operator ->() { return &self; } - const LDKCResult_InvoiceSignOrCreationErrorZ* operator &() const { return &self; } - const LDKCResult_InvoiceSignOrCreationErrorZ* operator ->() const { return &self; } -}; class CResult_InitFeaturesDecodeErrorZ { private: LDKCResult_InitFeaturesDecodeErrorZ self; @@ -6554,6 +6779,21 @@ public: const LDKCResult_PingDecodeErrorZ* operator &() const { return &self; } const LDKCResult_PingDecodeErrorZ* operator ->() const { return &self; } }; +class CResult_BlindedHopFeaturesDecodeErrorZ { +private: + LDKCResult_BlindedHopFeaturesDecodeErrorZ self; +public: + CResult_BlindedHopFeaturesDecodeErrorZ(const CResult_BlindedHopFeaturesDecodeErrorZ&) = delete; + CResult_BlindedHopFeaturesDecodeErrorZ(CResult_BlindedHopFeaturesDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_BlindedHopFeaturesDecodeErrorZ)); } + CResult_BlindedHopFeaturesDecodeErrorZ(LDKCResult_BlindedHopFeaturesDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_BlindedHopFeaturesDecodeErrorZ)); } + operator LDKCResult_BlindedHopFeaturesDecodeErrorZ() && { LDKCResult_BlindedHopFeaturesDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_BlindedHopFeaturesDecodeErrorZ)); return res; } + ~CResult_BlindedHopFeaturesDecodeErrorZ() { CResult_BlindedHopFeaturesDecodeErrorZ_free(self); } + CResult_BlindedHopFeaturesDecodeErrorZ& operator=(CResult_BlindedHopFeaturesDecodeErrorZ&& o) { CResult_BlindedHopFeaturesDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_BlindedHopFeaturesDecodeErrorZ)); return *this; } + LDKCResult_BlindedHopFeaturesDecodeErrorZ* operator &() { return &self; } + LDKCResult_BlindedHopFeaturesDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_BlindedHopFeaturesDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_BlindedHopFeaturesDecodeErrorZ* operator ->() const { return &self; } +}; class CVec_TransactionOutputsZ { private: LDKCVec_TransactionOutputsZ self; @@ -6779,6 +7019,21 @@ public: const LDKCResult_RecoverableSignatureNoneZ* operator &() const { return &self; } const LDKCResult_RecoverableSignatureNoneZ* operator ->() const { return &self; } }; +class C2Tuple_Z { +private: + LDKC2Tuple_Z self; +public: + C2Tuple_Z(const C2Tuple_Z&) = delete; + C2Tuple_Z(C2Tuple_Z&& o) : self(o.self) { memset(&o, 0, sizeof(C2Tuple_Z)); } + C2Tuple_Z(LDKC2Tuple_Z&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKC2Tuple_Z)); } + operator LDKC2Tuple_Z() && { LDKC2Tuple_Z res = self; memset(&self, 0, sizeof(LDKC2Tuple_Z)); return res; } + ~C2Tuple_Z() { C2Tuple_Z_free(self); } + C2Tuple_Z& operator=(C2Tuple_Z&& o) { C2Tuple_Z_free(self); self = o.self; memset(&o, 0, sizeof(C2Tuple_Z)); return *this; } + LDKC2Tuple_Z* operator &() { return &self; } + LDKC2Tuple_Z* operator ->() { return &self; } + const LDKC2Tuple_Z* operator &() const { return &self; } + const LDKC2Tuple_Z* operator ->() const { return &self; } +}; class C3Tuple_RawInvoice_u832InvoiceSignatureZ { private: LDKC3Tuple_RawInvoice_u832InvoiceSignatureZ self; @@ -6974,21 +7229,6 @@ public: const LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator &() const { return &self; } const LDKC2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ* operator ->() const { return &self; } }; -class CResult_SecretKeyNoneZ { -private: - LDKCResult_SecretKeyNoneZ self; -public: - CResult_SecretKeyNoneZ(const CResult_SecretKeyNoneZ&) = delete; - CResult_SecretKeyNoneZ(CResult_SecretKeyNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_SecretKeyNoneZ)); } - CResult_SecretKeyNoneZ(LDKCResult_SecretKeyNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_SecretKeyNoneZ)); } - operator LDKCResult_SecretKeyNoneZ() && { LDKCResult_SecretKeyNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_SecretKeyNoneZ)); return res; } - ~CResult_SecretKeyNoneZ() { CResult_SecretKeyNoneZ_free(self); } - CResult_SecretKeyNoneZ& operator=(CResult_SecretKeyNoneZ&& o) { CResult_SecretKeyNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_SecretKeyNoneZ)); return *this; } - LDKCResult_SecretKeyNoneZ* operator &() { return &self; } - LDKCResult_SecretKeyNoneZ* operator ->() { return &self; } - const LDKCResult_SecretKeyNoneZ* operator &() const { return &self; } - const LDKCResult_SecretKeyNoneZ* operator ->() const { return &self; } -}; class CResult_InitDecodeErrorZ { private: LDKCResult_InitDecodeErrorZ self; @@ -7124,21 +7364,6 @@ public: const LDKCResult_RouteHintHopDecodeErrorZ* operator &() const { return &self; } const LDKCResult_RouteHintHopDecodeErrorZ* operator ->() const { return &self; } }; -class CResult_C2Tuple_SignatureSignatureZNoneZ { -private: - LDKCResult_C2Tuple_SignatureSignatureZNoneZ self; -public: - CResult_C2Tuple_SignatureSignatureZNoneZ(const CResult_C2Tuple_SignatureSignatureZNoneZ&) = delete; - CResult_C2Tuple_SignatureSignatureZNoneZ(CResult_C2Tuple_SignatureSignatureZNoneZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_C2Tuple_SignatureSignatureZNoneZ)); } - CResult_C2Tuple_SignatureSignatureZNoneZ(LDKCResult_C2Tuple_SignatureSignatureZNoneZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_C2Tuple_SignatureSignatureZNoneZ)); } - operator LDKCResult_C2Tuple_SignatureSignatureZNoneZ() && { LDKCResult_C2Tuple_SignatureSignatureZNoneZ res = self; memset(&self, 0, sizeof(LDKCResult_C2Tuple_SignatureSignatureZNoneZ)); return res; } - ~CResult_C2Tuple_SignatureSignatureZNoneZ() { CResult_C2Tuple_SignatureSignatureZNoneZ_free(self); } - CResult_C2Tuple_SignatureSignatureZNoneZ& operator=(CResult_C2Tuple_SignatureSignatureZNoneZ&& o) { CResult_C2Tuple_SignatureSignatureZNoneZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_C2Tuple_SignatureSignatureZNoneZ)); return *this; } - LDKCResult_C2Tuple_SignatureSignatureZNoneZ* operator &() { return &self; } - LDKCResult_C2Tuple_SignatureSignatureZNoneZ* operator ->() { return &self; } - const LDKCResult_C2Tuple_SignatureSignatureZNoneZ* operator &() const { return &self; } - const LDKCResult_C2Tuple_SignatureSignatureZNoneZ* operator ->() const { return &self; } -}; class CResult_UpdateFailMalformedHTLCDecodeErrorZ { private: LDKCResult_UpdateFailMalformedHTLCDecodeErrorZ self; @@ -7424,21 +7649,6 @@ public: const LDKCResult_u32GraphSyncErrorZ* operator &() const { return &self; } const LDKCResult_u32GraphSyncErrorZ* operator ->() const { return &self; } }; -class CResult_InvoiceRequestFeaturesDecodeErrorZ { -private: - LDKCResult_InvoiceRequestFeaturesDecodeErrorZ self; -public: - CResult_InvoiceRequestFeaturesDecodeErrorZ(const CResult_InvoiceRequestFeaturesDecodeErrorZ&) = delete; - CResult_InvoiceRequestFeaturesDecodeErrorZ(CResult_InvoiceRequestFeaturesDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_InvoiceRequestFeaturesDecodeErrorZ)); } - CResult_InvoiceRequestFeaturesDecodeErrorZ(LDKCResult_InvoiceRequestFeaturesDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_InvoiceRequestFeaturesDecodeErrorZ)); } - operator LDKCResult_InvoiceRequestFeaturesDecodeErrorZ() && { LDKCResult_InvoiceRequestFeaturesDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_InvoiceRequestFeaturesDecodeErrorZ)); return res; } - ~CResult_InvoiceRequestFeaturesDecodeErrorZ() { CResult_InvoiceRequestFeaturesDecodeErrorZ_free(self); } - CResult_InvoiceRequestFeaturesDecodeErrorZ& operator=(CResult_InvoiceRequestFeaturesDecodeErrorZ&& o) { CResult_InvoiceRequestFeaturesDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_InvoiceRequestFeaturesDecodeErrorZ)); return *this; } - LDKCResult_InvoiceRequestFeaturesDecodeErrorZ* operator &() { return &self; } - LDKCResult_InvoiceRequestFeaturesDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_InvoiceRequestFeaturesDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_InvoiceRequestFeaturesDecodeErrorZ* operator ->() const { return &self; } -}; class CVec_PhantomRouteHintsZ { private: LDKCVec_PhantomRouteHintsZ self; @@ -7454,21 +7664,6 @@ public: const LDKCVec_PhantomRouteHintsZ* operator &() const { return &self; } const LDKCVec_PhantomRouteHintsZ* operator ->() const { return &self; } }; -class CResult_CounterpartyChannelTransactionParametersDecodeErrorZ { -private: - LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ self; -public: - CResult_CounterpartyChannelTransactionParametersDecodeErrorZ(const CResult_CounterpartyChannelTransactionParametersDecodeErrorZ&) = delete; - CResult_CounterpartyChannelTransactionParametersDecodeErrorZ(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); } - CResult_CounterpartyChannelTransactionParametersDecodeErrorZ(LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); } - operator LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ() && { LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); return res; } - ~CResult_CounterpartyChannelTransactionParametersDecodeErrorZ() { CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_free(self); } - CResult_CounterpartyChannelTransactionParametersDecodeErrorZ& operator=(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ&& o) { CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); return *this; } - LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator &() { return &self; } - LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator ->() { return &self; } - const LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator &() const { return &self; } - const LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator ->() const { return &self; } -}; class CResult_NoneAPIErrorZ { private: LDKCResult_NoneAPIErrorZ self; @@ -7484,6 +7679,21 @@ public: const LDKCResult_NoneAPIErrorZ* operator &() const { return &self; } const LDKCResult_NoneAPIErrorZ* operator ->() const { return &self; } }; +class CResult_CounterpartyChannelTransactionParametersDecodeErrorZ { +private: + LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ self; +public: + CResult_CounterpartyChannelTransactionParametersDecodeErrorZ(const CResult_CounterpartyChannelTransactionParametersDecodeErrorZ&) = delete; + CResult_CounterpartyChannelTransactionParametersDecodeErrorZ(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); } + CResult_CounterpartyChannelTransactionParametersDecodeErrorZ(LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); } + operator LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ() && { LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); return res; } + ~CResult_CounterpartyChannelTransactionParametersDecodeErrorZ() { CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_free(self); } + CResult_CounterpartyChannelTransactionParametersDecodeErrorZ& operator=(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ&& o) { CResult_CounterpartyChannelTransactionParametersDecodeErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_CounterpartyChannelTransactionParametersDecodeErrorZ)); return *this; } + LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator &() { return &self; } + LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator ->() { return &self; } + const LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator &() const { return &self; } + const LDKCResult_CounterpartyChannelTransactionParametersDecodeErrorZ* operator ->() const { return &self; } +}; class CVec_NetAddressZ { private: LDKCVec_NetAddressZ self; @@ -7649,6 +7859,21 @@ public: const LDKCResult_ShutdownDecodeErrorZ* operator &() const { return &self; } const LDKCResult_ShutdownDecodeErrorZ* operator ->() const { return &self; } }; +class CResult_TxOutUtxoLookupErrorZ { +private: + LDKCResult_TxOutUtxoLookupErrorZ self; +public: + CResult_TxOutUtxoLookupErrorZ(const CResult_TxOutUtxoLookupErrorZ&) = delete; + CResult_TxOutUtxoLookupErrorZ(CResult_TxOutUtxoLookupErrorZ&& o) : self(o.self) { memset(&o, 0, sizeof(CResult_TxOutUtxoLookupErrorZ)); } + CResult_TxOutUtxoLookupErrorZ(LDKCResult_TxOutUtxoLookupErrorZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCResult_TxOutUtxoLookupErrorZ)); } + operator LDKCResult_TxOutUtxoLookupErrorZ() && { LDKCResult_TxOutUtxoLookupErrorZ res = self; memset(&self, 0, sizeof(LDKCResult_TxOutUtxoLookupErrorZ)); return res; } + ~CResult_TxOutUtxoLookupErrorZ() { CResult_TxOutUtxoLookupErrorZ_free(self); } + CResult_TxOutUtxoLookupErrorZ& operator=(CResult_TxOutUtxoLookupErrorZ&& o) { CResult_TxOutUtxoLookupErrorZ_free(self); self = o.self; memset(&o, 0, sizeof(CResult_TxOutUtxoLookupErrorZ)); return *this; } + LDKCResult_TxOutUtxoLookupErrorZ* operator &() { return &self; } + LDKCResult_TxOutUtxoLookupErrorZ* operator ->() { return &self; } + const LDKCResult_TxOutUtxoLookupErrorZ* operator &() const { return &self; } + const LDKCResult_TxOutUtxoLookupErrorZ* operator ->() const { return &self; } +}; class CVec_MonitorEventZ { private: LDKCVec_MonitorEventZ self; @@ -7859,6 +8084,21 @@ public: const LDKCResult_SignedRawInvoiceParseErrorZ* operator &() const { return &self; } const LDKCResult_SignedRawInvoiceParseErrorZ* operator ->() const { return &self; } }; +class COption_C2Tuple_EightU16sEightU16sZZ { +private: + LDKCOption_C2Tuple_EightU16sEightU16sZZ self; +public: + COption_C2Tuple_EightU16sEightU16sZZ(const COption_C2Tuple_EightU16sEightU16sZZ&) = delete; + COption_C2Tuple_EightU16sEightU16sZZ(COption_C2Tuple_EightU16sEightU16sZZ&& o) : self(o.self) { memset(&o, 0, sizeof(COption_C2Tuple_EightU16sEightU16sZZ)); } + COption_C2Tuple_EightU16sEightU16sZZ(LDKCOption_C2Tuple_EightU16sEightU16sZZ&& m_self) : self(m_self) { memset(&m_self, 0, sizeof(LDKCOption_C2Tuple_EightU16sEightU16sZZ)); } + operator LDKCOption_C2Tuple_EightU16sEightU16sZZ() && { LDKCOption_C2Tuple_EightU16sEightU16sZZ res = self; memset(&self, 0, sizeof(LDKCOption_C2Tuple_EightU16sEightU16sZZ)); return res; } + ~COption_C2Tuple_EightU16sEightU16sZZ() { COption_C2Tuple_EightU16sEightU16sZZ_free(self); } + COption_C2Tuple_EightU16sEightU16sZZ& operator=(COption_C2Tuple_EightU16sEightU16sZZ&& o) { COption_C2Tuple_EightU16sEightU16sZZ_free(self); self = o.self; memset(&o, 0, sizeof(COption_C2Tuple_EightU16sEightU16sZZ)); return *this; } + LDKCOption_C2Tuple_EightU16sEightU16sZZ* operator &() { return &self; } + LDKCOption_C2Tuple_EightU16sEightU16sZZ* operator ->() { return &self; } + const LDKCOption_C2Tuple_EightU16sEightU16sZZ* operator &() const { return &self; } + const LDKCOption_C2Tuple_EightU16sEightU16sZZ* operator ->() const { return &self; } +}; class CResult_RouteDecodeErrorZ { private: LDKCResult_RouteDecodeErrorZ self; @@ -7890,26 +8130,14 @@ public: const LDKCOption_NoneZ* operator ->() const { return &self; } }; -inline LDK::CResult_RouteLightningErrorZ Router::find_route(struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, struct LDKInFlightHtlcs inflight_htlcs) { +inline LDK::CResult_RouteLightningErrorZ Router::find_route(struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, const struct LDKInFlightHtlcs *NONNULL_PTR inflight_htlcs) { LDK::CResult_RouteLightningErrorZ ret = (self.find_route)(self.this_arg, payer, route_params, first_hops, inflight_htlcs); return ret; } -inline LDK::CResult_RouteLightningErrorZ Router::find_route_with_id(struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, struct LDKInFlightHtlcs inflight_htlcs, struct LDKThirtyTwoBytes _payment_hash, struct LDKThirtyTwoBytes _payment_id) { +inline LDK::CResult_RouteLightningErrorZ Router::find_route_with_id(struct LDKPublicKey payer, const struct LDKRouteParameters *NONNULL_PTR route_params, struct LDKCVec_ChannelDetailsZ *first_hops, const struct LDKInFlightHtlcs *NONNULL_PTR inflight_htlcs, struct LDKThirtyTwoBytes _payment_hash, struct LDKThirtyTwoBytes _payment_id) { LDK::CResult_RouteLightningErrorZ ret = (self.find_route_with_id)(self.this_arg, payer, route_params, first_hops, inflight_htlcs, _payment_hash, _payment_id); return ret; } -inline void Router::notify_payment_path_failed(struct LDKCVec_RouteHopZ path, uint64_t short_channel_id) { - (self.notify_payment_path_failed)(self.this_arg, path, short_channel_id); -} -inline void Router::notify_payment_path_successful(struct LDKCVec_RouteHopZ path) { - (self.notify_payment_path_successful)(self.this_arg, path); -} -inline void Router::notify_payment_probe_successful(struct LDKCVec_RouteHopZ path) { - (self.notify_payment_probe_successful)(self.this_arg, path); -} -inline void Router::notify_payment_probe_failed(struct LDKCVec_RouteHopZ path, uint64_t short_channel_id) { - (self.notify_payment_probe_failed)(self.this_arg, path, short_channel_id); -} inline void BroadcasterInterface::broadcast_transaction(struct LDKTransaction tx) { (self.broadcast_transaction)(self.this_arg, tx); } @@ -7931,10 +8159,6 @@ inline void EventsProvider::process_pending_events(struct LDKEventHandler handle inline void EventHandler::handle_event(struct LDKEvent event) { (self.handle_event)(self.this_arg, event); } -inline LDK::CResult_TxOutAccessErrorZ Access::get_utxo(const uint8_t (*genesis_hash)[32], uint64_t short_channel_id) { - LDK::CResult_TxOutAccessErrorZ ret = (self.get_utxo)(self.this_arg, genesis_hash, short_channel_id); - return ret; -} inline void Listen::filtered_block_connected(const uint8_t (*header)[80], struct LDKCVec_C2Tuple_usizeTransactionZZ txdata, uint32_t height) { (self.filtered_block_connected)(self.this_arg, header, txdata, height); } @@ -7961,7 +8185,7 @@ inline LDK::ChannelMonitorUpdateStatus Watch::watch_channel(struct LDKOutPoint f LDK::ChannelMonitorUpdateStatus ret = (self.watch_channel)(self.this_arg, funding_txo, monitor); return ret; } -inline LDK::ChannelMonitorUpdateStatus Watch::update_channel(struct LDKOutPoint funding_txo, struct LDKChannelMonitorUpdate update) { +inline LDK::ChannelMonitorUpdateStatus Watch::update_channel(struct LDKOutPoint funding_txo, const struct LDKChannelMonitorUpdate *NONNULL_PTR update) { LDK::ChannelMonitorUpdateStatus ret = (self.update_channel)(self.this_arg, funding_txo, update); return ret; } @@ -7999,103 +8223,103 @@ inline uint64_t CustomOnionMessageContents::tlv_type() { uint64_t ret = (self.tlv_type)(self.this_arg); return ret; } -inline LDKPublicKey BaseSign::get_per_commitment_point(uint64_t idx) { +inline LDKPublicKey ChannelSigner::get_per_commitment_point(uint64_t idx) { LDKPublicKey ret = (self.get_per_commitment_point)(self.this_arg, idx); return ret; } -inline LDKThirtyTwoBytes BaseSign::release_commitment_secret(uint64_t idx) { +inline LDKThirtyTwoBytes ChannelSigner::release_commitment_secret(uint64_t idx) { LDKThirtyTwoBytes ret = (self.release_commitment_secret)(self.this_arg, idx); return ret; } -inline LDK::CResult_NoneNoneZ BaseSign::validate_holder_commitment(const struct LDKHolderCommitmentTransaction *NONNULL_PTR holder_tx, struct LDKCVec_PaymentPreimageZ preimages) { +inline LDK::CResult_NoneNoneZ ChannelSigner::validate_holder_commitment(const struct LDKHolderCommitmentTransaction *NONNULL_PTR holder_tx, struct LDKCVec_PaymentPreimageZ preimages) { LDK::CResult_NoneNoneZ ret = (self.validate_holder_commitment)(self.this_arg, holder_tx, preimages); return ret; } -inline LDKThirtyTwoBytes BaseSign::channel_keys_id() { +inline LDKThirtyTwoBytes ChannelSigner::channel_keys_id() { LDKThirtyTwoBytes ret = (self.channel_keys_id)(self.this_arg); return ret; } -inline LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ BaseSign::sign_counterparty_commitment(const struct LDKCommitmentTransaction *NONNULL_PTR commitment_tx, struct LDKCVec_PaymentPreimageZ preimages) { +inline void ChannelSigner::provide_channel_parameters(const struct LDKChannelTransactionParameters *NONNULL_PTR channel_parameters) { + (self.provide_channel_parameters)(self.this_arg, channel_parameters); +} +inline LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ EcdsaChannelSigner::sign_counterparty_commitment(const struct LDKCommitmentTransaction *NONNULL_PTR commitment_tx, struct LDKCVec_PaymentPreimageZ preimages) { LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ ret = (self.sign_counterparty_commitment)(self.this_arg, commitment_tx, preimages); return ret; } -inline LDK::CResult_NoneNoneZ BaseSign::validate_counterparty_revocation(uint64_t idx, const uint8_t (*secret)[32]) { +inline LDK::CResult_NoneNoneZ EcdsaChannelSigner::validate_counterparty_revocation(uint64_t idx, const uint8_t (*secret)[32]) { LDK::CResult_NoneNoneZ ret = (self.validate_counterparty_revocation)(self.this_arg, idx, secret); return ret; } -inline LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ BaseSign::sign_holder_commitment_and_htlcs(const struct LDKHolderCommitmentTransaction *NONNULL_PTR commitment_tx) { +inline LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ EcdsaChannelSigner::sign_holder_commitment_and_htlcs(const struct LDKHolderCommitmentTransaction *NONNULL_PTR commitment_tx) { LDK::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ ret = (self.sign_holder_commitment_and_htlcs)(self.this_arg, commitment_tx); return ret; } -inline LDK::CResult_SignatureNoneZ BaseSign::sign_justice_revoked_output(struct LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32]) { +inline LDK::CResult_SignatureNoneZ EcdsaChannelSigner::sign_justice_revoked_output(struct LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32]) { LDK::CResult_SignatureNoneZ ret = (self.sign_justice_revoked_output)(self.this_arg, justice_tx, input, amount, per_commitment_key); return ret; } -inline LDK::CResult_SignatureNoneZ BaseSign::sign_justice_revoked_htlc(struct LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32], const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc) { +inline LDK::CResult_SignatureNoneZ EcdsaChannelSigner::sign_justice_revoked_htlc(struct LDKTransaction justice_tx, uintptr_t input, uint64_t amount, const uint8_t (*per_commitment_key)[32], const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc) { LDK::CResult_SignatureNoneZ ret = (self.sign_justice_revoked_htlc)(self.this_arg, justice_tx, input, amount, per_commitment_key, htlc); return ret; } -inline LDK::CResult_SignatureNoneZ BaseSign::sign_counterparty_htlc_transaction(struct LDKTransaction htlc_tx, uintptr_t input, uint64_t amount, struct LDKPublicKey per_commitment_point, const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc) { +inline LDK::CResult_SignatureNoneZ EcdsaChannelSigner::sign_counterparty_htlc_transaction(struct LDKTransaction htlc_tx, uintptr_t input, uint64_t amount, struct LDKPublicKey per_commitment_point, const struct LDKHTLCOutputInCommitment *NONNULL_PTR htlc) { LDK::CResult_SignatureNoneZ ret = (self.sign_counterparty_htlc_transaction)(self.this_arg, htlc_tx, input, amount, per_commitment_point, htlc); return ret; } -inline LDK::CResult_SignatureNoneZ BaseSign::sign_closing_transaction(const struct LDKClosingTransaction *NONNULL_PTR closing_tx) { +inline LDK::CResult_SignatureNoneZ EcdsaChannelSigner::sign_closing_transaction(const struct LDKClosingTransaction *NONNULL_PTR closing_tx) { LDK::CResult_SignatureNoneZ ret = (self.sign_closing_transaction)(self.this_arg, closing_tx); return ret; } -inline LDK::CResult_SignatureNoneZ BaseSign::sign_holder_anchor_input(struct LDKTransaction anchor_tx, uintptr_t input) { +inline LDK::CResult_SignatureNoneZ EcdsaChannelSigner::sign_holder_anchor_input(struct LDKTransaction anchor_tx, uintptr_t input) { LDK::CResult_SignatureNoneZ ret = (self.sign_holder_anchor_input)(self.this_arg, anchor_tx, input); return ret; } -inline LDK::CResult_C2Tuple_SignatureSignatureZNoneZ BaseSign::sign_channel_announcement(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg) { - LDK::CResult_C2Tuple_SignatureSignatureZNoneZ ret = (self.sign_channel_announcement)(self.this_arg, msg); +inline LDK::CResult_SignatureNoneZ EcdsaChannelSigner::sign_channel_announcement_with_funding_key(const struct LDKUnsignedChannelAnnouncement *NONNULL_PTR msg) { + LDK::CResult_SignatureNoneZ ret = (self.sign_channel_announcement_with_funding_key)(self.this_arg, msg); return ret; } -inline void BaseSign::provide_channel_parameters(const struct LDKChannelTransactionParameters *NONNULL_PTR channel_parameters) { - (self.provide_channel_parameters)(self.this_arg, channel_parameters); +inline LDKThirtyTwoBytes EntropySource::get_secure_random_bytes() { + LDKThirtyTwoBytes ret = (self.get_secure_random_bytes)(self.this_arg); + return ret; } -inline LDK::CResult_SecretKeyNoneZ KeysInterface::get_node_secret(enum LDKRecipient recipient) { - LDK::CResult_SecretKeyNoneZ ret = (self.get_node_secret)(self.this_arg, recipient); +inline LDKThirtyTwoBytes NodeSigner::get_inbound_payment_key_material() { + LDKThirtyTwoBytes ret = (self.get_inbound_payment_key_material)(self.this_arg); return ret; } -inline LDK::CResult_PublicKeyNoneZ KeysInterface::get_node_id(enum LDKRecipient recipient) { +inline LDK::CResult_PublicKeyNoneZ NodeSigner::get_node_id(enum LDKRecipient recipient) { LDK::CResult_PublicKeyNoneZ ret = (self.get_node_id)(self.this_arg, recipient); return ret; } -inline LDK::CResult_SharedSecretNoneZ KeysInterface::ecdh(enum LDKRecipient recipient, struct LDKPublicKey other_key, struct LDKCOption_ScalarZ tweak) { +inline LDK::CResult_SharedSecretNoneZ NodeSigner::ecdh(enum LDKRecipient recipient, struct LDKPublicKey other_key, struct LDKCOption_ScalarZ tweak) { LDK::CResult_SharedSecretNoneZ ret = (self.ecdh)(self.this_arg, recipient, other_key, tweak); return ret; } -inline LDK::CVec_u8Z KeysInterface::get_destination_script() { - LDK::CVec_u8Z ret = (self.get_destination_script)(self.this_arg); +inline LDK::CResult_RecoverableSignatureNoneZ NodeSigner::sign_invoice(struct LDKu8slice hrp_bytes, struct LDKCVec_U5Z invoice_data, enum LDKRecipient recipient) { + LDK::CResult_RecoverableSignatureNoneZ ret = (self.sign_invoice)(self.this_arg, hrp_bytes, invoice_data, recipient); return ret; } -inline LDK::ShutdownScript KeysInterface::get_shutdown_scriptpubkey() { - LDK::ShutdownScript ret = (self.get_shutdown_scriptpubkey)(self.this_arg); +inline LDK::CResult_SignatureNoneZ NodeSigner::sign_gossip_message(struct LDKUnsignedGossipMessage msg) { + LDK::CResult_SignatureNoneZ ret = (self.sign_gossip_message)(self.this_arg, msg); return ret; } -inline LDKThirtyTwoBytes KeysInterface::generate_channel_keys_id(bool inbound, uint64_t channel_value_satoshis, struct LDKU128 user_channel_id) { +inline LDKThirtyTwoBytes SignerProvider::generate_channel_keys_id(bool inbound, uint64_t channel_value_satoshis, struct LDKU128 user_channel_id) { LDKThirtyTwoBytes ret = (self.generate_channel_keys_id)(self.this_arg, inbound, channel_value_satoshis, user_channel_id); return ret; } -inline LDK::Sign KeysInterface::derive_channel_signer(uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id) { - LDK::Sign ret = (self.derive_channel_signer)(self.this_arg, channel_value_satoshis, channel_keys_id); +inline LDK::WriteableEcdsaChannelSigner SignerProvider::derive_channel_signer(uint64_t channel_value_satoshis, struct LDKThirtyTwoBytes channel_keys_id) { + LDK::WriteableEcdsaChannelSigner ret = (self.derive_channel_signer)(self.this_arg, channel_value_satoshis, channel_keys_id); return ret; } -inline LDKThirtyTwoBytes KeysInterface::get_secure_random_bytes() { - LDKThirtyTwoBytes ret = (self.get_secure_random_bytes)(self.this_arg); +inline LDK::CResult_WriteableEcdsaChannelSignerDecodeErrorZ SignerProvider::read_chan_signer(struct LDKu8slice reader) { + LDK::CResult_WriteableEcdsaChannelSignerDecodeErrorZ ret = (self.read_chan_signer)(self.this_arg, reader); return ret; } -inline LDK::CResult_SignDecodeErrorZ KeysInterface::read_chan_signer(struct LDKu8slice reader) { - LDK::CResult_SignDecodeErrorZ ret = (self.read_chan_signer)(self.this_arg, reader); - return ret; -} -inline LDK::CResult_RecoverableSignatureNoneZ KeysInterface::sign_invoice(struct LDKu8slice hrp_bytes, struct LDKCVec_U5Z invoice_data, enum LDKRecipient receipient) { - LDK::CResult_RecoverableSignatureNoneZ ret = (self.sign_invoice)(self.this_arg, hrp_bytes, invoice_data, receipient); +inline LDK::CVec_u8Z SignerProvider::get_destination_script() { + LDK::CVec_u8Z ret = (self.get_destination_script)(self.this_arg); return ret; } -inline LDKThirtyTwoBytes KeysInterface::get_inbound_payment_key_material() { - LDKThirtyTwoBytes ret = (self.get_inbound_payment_key_material)(self.this_arg); +inline LDK::ShutdownScript SignerProvider::get_shutdown_scriptpubkey() { + LDK::ShutdownScript ret = (self.get_shutdown_scriptpubkey)(self.this_arg); return ret; } inline LDK::CResult_COption_TypeZDecodeErrorZ CustomMessageReader::read(uint16_t message_type, struct LDKu8slice buffer) { @@ -8110,33 +8334,6 @@ inline LDK::Str Type::debug_str() { LDK::Str ret = (self.debug_str)(self.this_arg); return ret; } -inline LDKPublicKey Payer::node_id() { - LDKPublicKey ret = (self.node_id)(self.this_arg); - return ret; -} -inline LDK::CVec_ChannelDetailsZ Payer::first_hops() { - LDK::CVec_ChannelDetailsZ ret = (self.first_hops)(self.this_arg); - return ret; -} -inline LDK::CResult_NonePaymentSendFailureZ Payer::send_payment(const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_hash, struct LDKThirtyTwoBytes payment_secret, struct LDKThirtyTwoBytes payment_id) { - LDK::CResult_NonePaymentSendFailureZ ret = (self.send_payment)(self.this_arg, route, payment_hash, payment_secret, payment_id); - return ret; -} -inline LDK::CResult_NonePaymentSendFailureZ Payer::send_spontaneous_payment(const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_preimage, struct LDKThirtyTwoBytes payment_id) { - LDK::CResult_NonePaymentSendFailureZ ret = (self.send_spontaneous_payment)(self.this_arg, route, payment_preimage, payment_id); - return ret; -} -inline LDK::CResult_NonePaymentSendFailureZ Payer::retry_payment(const struct LDKRoute *NONNULL_PTR route, struct LDKThirtyTwoBytes payment_id) { - LDK::CResult_NonePaymentSendFailureZ ret = (self.retry_payment)(self.this_arg, route, payment_id); - return ret; -} -inline void Payer::abandon_payment(struct LDKThirtyTwoBytes payment_id) { - (self.abandon_payment)(self.this_arg, payment_id); -} -inline LDK::InFlightHtlcs Payer::inflight_htlcs() { - LDK::InFlightHtlcs ret = (self.inflight_htlcs)(self.this_arg); - return ret; -} inline LDK::CResult_NoneLightningErrorZ CustomMessageHandler::handle_custom_message(struct LDKType msg, struct LDKPublicKey sender_node_id) { LDK::CResult_NoneLightningErrorZ ret = (self.handle_custom_message)(self.this_arg, msg, sender_node_id); return ret; @@ -8160,6 +8357,10 @@ inline uint64_t SocketDescriptor::hash() { uint64_t ret = (self.hash)(self.this_arg); return ret; } +inline LDK::UtxoResult UtxoLookup::get_utxo(const uint8_t (*genesis_hash)[32], uint64_t short_channel_id) { + LDK::UtxoResult ret = (self.get_utxo)(self.this_arg, genesis_hash, short_channel_id); + return ret; +} inline void CustomOnionMessageHandler::handle_custom_message(struct LDKCustomOnionMessageContents msg) { (self.handle_custom_message)(self.this_arg, msg); } @@ -8179,11 +8380,11 @@ inline LDK::CResult_NoneErrorZ Persister::persist_scorer(const struct LDKWriteab LDK::CResult_NoneErrorZ ret = (self.persist_scorer)(self.this_arg, scorer); return ret; } -inline void ChannelMessageHandler::handle_open_channel(struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKOpenChannel *NONNULL_PTR msg) { - (self.handle_open_channel)(self.this_arg, their_node_id, their_features, msg); +inline void ChannelMessageHandler::handle_open_channel(struct LDKPublicKey their_node_id, const struct LDKOpenChannel *NONNULL_PTR msg) { + (self.handle_open_channel)(self.this_arg, their_node_id, msg); } -inline void ChannelMessageHandler::handle_accept_channel(struct LDKPublicKey their_node_id, struct LDKInitFeatures their_features, const struct LDKAcceptChannel *NONNULL_PTR msg) { - (self.handle_accept_channel)(self.this_arg, their_node_id, their_features, msg); +inline void ChannelMessageHandler::handle_accept_channel(struct LDKPublicKey their_node_id, const struct LDKAcceptChannel *NONNULL_PTR msg) { + (self.handle_accept_channel)(self.this_arg, their_node_id, msg); } inline void ChannelMessageHandler::handle_funding_created(struct LDKPublicKey their_node_id, const struct LDKFundingCreated *NONNULL_PTR msg) { (self.handle_funding_created)(self.this_arg, their_node_id, msg); @@ -8194,8 +8395,8 @@ inline void ChannelMessageHandler::handle_funding_signed(struct LDKPublicKey the inline void ChannelMessageHandler::handle_channel_ready(struct LDKPublicKey their_node_id, const struct LDKChannelReady *NONNULL_PTR msg) { (self.handle_channel_ready)(self.this_arg, their_node_id, msg); } -inline void ChannelMessageHandler::handle_shutdown(struct LDKPublicKey their_node_id, const struct LDKInitFeatures *NONNULL_PTR their_features, const struct LDKShutdown *NONNULL_PTR msg) { - (self.handle_shutdown)(self.this_arg, their_node_id, their_features, msg); +inline void ChannelMessageHandler::handle_shutdown(struct LDKPublicKey their_node_id, const struct LDKShutdown *NONNULL_PTR msg) { + (self.handle_shutdown)(self.this_arg, their_node_id, msg); } inline void ChannelMessageHandler::handle_closing_signed(struct LDKPublicKey their_node_id, const struct LDKClosingSigned *NONNULL_PTR msg) { (self.handle_closing_signed)(self.this_arg, their_node_id, msg); @@ -8224,11 +8425,11 @@ inline void ChannelMessageHandler::handle_update_fee(struct LDKPublicKey their_n inline void ChannelMessageHandler::handle_announcement_signatures(struct LDKPublicKey their_node_id, const struct LDKAnnouncementSignatures *NONNULL_PTR msg) { (self.handle_announcement_signatures)(self.this_arg, their_node_id, msg); } -inline void ChannelMessageHandler::peer_disconnected(struct LDKPublicKey their_node_id, bool no_connection_possible) { - (self.peer_disconnected)(self.this_arg, their_node_id, no_connection_possible); +inline void ChannelMessageHandler::peer_disconnected(struct LDKPublicKey their_node_id) { + (self.peer_disconnected)(self.this_arg, their_node_id); } -inline LDK::CResult_NoneNoneZ ChannelMessageHandler::peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR msg) { - LDK::CResult_NoneNoneZ ret = (self.peer_connected)(self.this_arg, their_node_id, msg); +inline LDK::CResult_NoneNoneZ ChannelMessageHandler::peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR msg, bool inbound) { + LDK::CResult_NoneNoneZ ret = (self.peer_connected)(self.this_arg, their_node_id, msg, inbound); return ret; } inline void ChannelMessageHandler::handle_channel_reestablish(struct LDKPublicKey their_node_id, const struct LDKChannelReestablish *NONNULL_PTR msg) { @@ -8264,12 +8465,12 @@ inline LDK::COption_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ Rout LDK::COption_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ ret = (self.get_next_channel_announcement)(self.this_arg, starting_point); return ret; } -inline LDK::NodeAnnouncement RoutingMessageHandler::get_next_node_announcement(struct LDKPublicKey starting_point) { +inline LDK::NodeAnnouncement RoutingMessageHandler::get_next_node_announcement(struct LDKNodeId starting_point) { LDK::NodeAnnouncement ret = (self.get_next_node_announcement)(self.this_arg, starting_point); return ret; } -inline LDK::CResult_NoneNoneZ RoutingMessageHandler::peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init) { - LDK::CResult_NoneNoneZ ret = (self.peer_connected)(self.this_arg, their_node_id, init); +inline LDK::CResult_NoneNoneZ RoutingMessageHandler::peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init, bool inbound) { + LDK::CResult_NoneNoneZ ret = (self.peer_connected)(self.this_arg, their_node_id, init, inbound); return ret; } inline LDK::CResult_NoneLightningErrorZ RoutingMessageHandler::handle_reply_channel_range(struct LDKPublicKey their_node_id, struct LDKReplyChannelRange msg) { @@ -8288,6 +8489,10 @@ inline LDK::CResult_NoneLightningErrorZ RoutingMessageHandler::handle_query_shor LDK::CResult_NoneLightningErrorZ ret = (self.handle_query_short_channel_ids)(self.this_arg, their_node_id, msg); return ret; } +inline bool RoutingMessageHandler::processing_queue_high() { + bool ret = (self.processing_queue_high)(self.this_arg); + return ret; +} inline LDK::NodeFeatures RoutingMessageHandler::provided_node_features() { LDK::NodeFeatures ret = (self.provided_node_features)(self.this_arg); return ret; @@ -8299,12 +8504,12 @@ inline LDK::InitFeatures RoutingMessageHandler::provided_init_features(struct LD inline void OnionMessageHandler::handle_onion_message(struct LDKPublicKey peer_node_id, const struct LDKOnionMessage *NONNULL_PTR msg) { (self.handle_onion_message)(self.this_arg, peer_node_id, msg); } -inline LDK::CResult_NoneNoneZ OnionMessageHandler::peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init) { - LDK::CResult_NoneNoneZ ret = (self.peer_connected)(self.this_arg, their_node_id, init); +inline LDK::CResult_NoneNoneZ OnionMessageHandler::peer_connected(struct LDKPublicKey their_node_id, const struct LDKInit *NONNULL_PTR init, bool inbound) { + LDK::CResult_NoneNoneZ ret = (self.peer_connected)(self.this_arg, their_node_id, init, inbound); return ret; } -inline void OnionMessageHandler::peer_disconnected(struct LDKPublicKey their_node_id, bool no_connection_possible) { - (self.peer_disconnected)(self.this_arg, their_node_id, no_connection_possible); +inline void OnionMessageHandler::peer_disconnected(struct LDKPublicKey their_node_id) { + (self.peer_disconnected)(self.this_arg, their_node_id); } inline LDK::NodeFeatures OnionMessageHandler::provided_node_features() { LDK::NodeFeatures ret = (self.provided_node_features)(self.this_arg); @@ -8324,7 +8529,7 @@ inline LDK::ChannelMonitorUpdateStatus Persist::persist_new_channel(struct LDKOu LDK::ChannelMonitorUpdateStatus ret = (self.persist_new_channel)(self.this_arg, channel_id, data, update_id); return ret; } -inline LDK::ChannelMonitorUpdateStatus Persist::update_persisted_channel(struct LDKOutPoint channel_id, const struct LDKChannelMonitorUpdate *NONNULL_PTR update, const struct LDKChannelMonitor *NONNULL_PTR data, struct LDKMonitorUpdateId update_id) { +inline LDK::ChannelMonitorUpdateStatus Persist::update_persisted_channel(struct LDKOutPoint channel_id, struct LDKChannelMonitorUpdate update, const struct LDKChannelMonitor *NONNULL_PTR data, struct LDKMonitorUpdateId update_id) { LDK::ChannelMonitorUpdateStatus ret = (self.update_persisted_channel)(self.this_arg, channel_id, update, data, update_id); return ret; } diff --git a/lightning-c-bindings/src/c_types/derived.rs b/lightning-c-bindings/src/c_types/derived.rs index eb681f4..f763965 100644 --- a/lightning-c-bindings/src/c_types/derived.rs +++ b/lightning-c-bindings/src/c_types/derived.rs @@ -7,6 +7,190 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; +#[repr(C)] +/// The contents of CResult_NoneAPIErrorZ +pub union CResult_NoneAPIErrorZPtr { + /// Note that this value is always NULL, as there are no contents in the OK variant + pub result: *mut core::ffi::c_void, + /// A pointer to the contents in the error state. + /// Reading from this pointer when `result_ok` is set is undefined. + pub err: *mut crate::lightning::util::errors::APIError, +} +#[repr(C)] +/// A CResult_NoneAPIErrorZ represents the result of a fallible operation, +/// containing a () on success and a crate::lightning::util::errors::APIError on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_NoneAPIErrorZ { + /// The contents of this CResult_NoneAPIErrorZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_NoneAPIErrorZPtr, + /// Whether this CResult_NoneAPIErrorZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_NoneAPIErrorZ in the success state. +pub extern "C" fn CResult_NoneAPIErrorZ_ok() -> CResult_NoneAPIErrorZ { + CResult_NoneAPIErrorZ { + contents: CResult_NoneAPIErrorZPtr { + result: core::ptr::null_mut(), + }, + result_ok: true, + } +} +#[no_mangle] +/// Creates a new CResult_NoneAPIErrorZ in the error state. +pub extern "C" fn CResult_NoneAPIErrorZ_err(e: crate::lightning::util::errors::APIError) -> CResult_NoneAPIErrorZ { + CResult_NoneAPIErrorZ { + contents: CResult_NoneAPIErrorZPtr { + err: Box::into_raw(Box::new(e)), + }, + result_ok: false, + } +} +/// Checks if the given object is currently in the success state +#[no_mangle] +pub extern "C" fn CResult_NoneAPIErrorZ_is_ok(o: &CResult_NoneAPIErrorZ) -> bool { + o.result_ok +} +#[no_mangle] +/// Frees any resources used by the CResult_NoneAPIErrorZ. +pub extern "C" fn CResult_NoneAPIErrorZ_free(_res: CResult_NoneAPIErrorZ) { } +impl Drop for CResult_NoneAPIErrorZ { + fn drop(&mut self) { + if self.result_ok { + } else { + if unsafe { !(self.contents.err as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.err) }; + } + } + } +} +impl From> for CResult_NoneAPIErrorZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::util::errors::APIError>) -> Self { + let contents = if o.result_ok { + let _ = unsafe { Box::from_raw(o.contents.result) }; + o.contents.result = core::ptr::null_mut(); + CResult_NoneAPIErrorZPtr { result: core::ptr::null_mut() } + } else { + let err = unsafe { o.contents.err }; + unsafe { o.contents.err = core::ptr::null_mut(); } + CResult_NoneAPIErrorZPtr { err } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_NoneAPIErrorZ { + fn clone(&self) -> Self { + if self.result_ok { + Self { result_ok: true, contents: CResult_NoneAPIErrorZPtr { + result: core::ptr::null_mut() + } } + } else { + Self { result_ok: false, contents: CResult_NoneAPIErrorZPtr { + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + } } + } + } +} +#[no_mangle] +/// Creates a new CResult_NoneAPIErrorZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_NoneAPIErrorZ_clone(orig: &CResult_NoneAPIErrorZ) -> CResult_NoneAPIErrorZ { Clone::clone(&orig) } +#[repr(C)] +/// A dynamically-allocated array of crate::c_types::derived::CResult_NoneAPIErrorZs of arbitrary size. +/// This corresponds to std::vector in C++ +pub struct CVec_CResult_NoneAPIErrorZZ { + /// The elements in the array. + /// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). + pub data: *mut crate::c_types::derived::CResult_NoneAPIErrorZ, + /// The number of elements pointed to by `data`. + pub datalen: usize +} +impl CVec_CResult_NoneAPIErrorZZ { + #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { + if self.datalen == 0 { return Vec::new(); } + let ret = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }.into(); + self.data = core::ptr::null_mut(); + self.datalen = 0; + ret + } + #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::CResult_NoneAPIErrorZ] { + unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) } + } +} +impl From> for CVec_CResult_NoneAPIErrorZZ { + fn from(v: Vec) -> Self { + let datalen = v.len(); + let data = Box::into_raw(v.into_boxed_slice()); + Self { datalen, data: unsafe { (*data).as_mut_ptr() } } + } +} +#[no_mangle] +/// Frees the buffer pointed to by `data` if `datalen` is non-0. +pub extern "C" fn CVec_CResult_NoneAPIErrorZZ_free(_res: CVec_CResult_NoneAPIErrorZZ) { } +impl Drop for CVec_CResult_NoneAPIErrorZZ { + fn drop(&mut self) { + if self.datalen == 0 { return; } + let _ = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }; + } +} +impl Clone for CVec_CResult_NoneAPIErrorZZ { + fn clone(&self) -> Self { + let mut res = Vec::new(); + if self.datalen == 0 { return Self::from(res); } + res.extend_from_slice(unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) }); + Self::from(res) + } +} +#[repr(C)] +/// A dynamically-allocated array of crate::lightning::util::errors::APIErrors of arbitrary size. +/// This corresponds to std::vector in C++ +pub struct CVec_APIErrorZ { + /// The elements in the array. + /// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). + pub data: *mut crate::lightning::util::errors::APIError, + /// The number of elements pointed to by `data`. + pub datalen: usize +} +impl CVec_APIErrorZ { + #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { + if self.datalen == 0 { return Vec::new(); } + let ret = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }.into(); + self.data = core::ptr::null_mut(); + self.datalen = 0; + ret + } + #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::lightning::util::errors::APIError] { + unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) } + } +} +impl From> for CVec_APIErrorZ { + fn from(v: Vec) -> Self { + let datalen = v.len(); + let data = Box::into_raw(v.into_boxed_slice()); + Self { datalen, data: unsafe { (*data).as_mut_ptr() } } + } +} +#[no_mangle] +/// Frees the buffer pointed to by `data` if `datalen` is non-0. +pub extern "C" fn CVec_APIErrorZ_free(_res: CVec_APIErrorZ) { } +impl Drop for CVec_APIErrorZ { + fn drop(&mut self) { + if self.datalen == 0 { return; } + let _ = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }; + } +} +impl Clone for CVec_APIErrorZ { + fn clone(&self) -> Self { + let mut res = Vec::new(); + if self.datalen == 0 { return Self::from(res); } + res.extend_from_slice(unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) }); + Self::from(res) + } +} #[repr(C)] /// An enum which can either contain a crate::lightning::ln::chan_utils::HTLCClaim or not pub enum COption_HTLCClaimZ { @@ -3170,77 +3354,114 @@ impl Clone for CResult_PaymentPurposeDecodeErrorZ { pub extern "C" fn CResult_PaymentPurposeDecodeErrorZ_clone(orig: &CResult_PaymentPurposeDecodeErrorZ) -> CResult_PaymentPurposeDecodeErrorZ { Clone::clone(&orig) } #[repr(C)] #[derive(Clone)] -/// An enum which can either contain a crate::lightning::util::events::ClosureReason or not -pub enum COption_ClosureReasonZ { - /// When we're in this state, this COption_ClosureReasonZ contains a crate::lightning::util::events::ClosureReason - Some(crate::lightning::util::events::ClosureReason), - /// When we're in this state, this COption_ClosureReasonZ contains nothing +/// An enum which can either contain a crate::lightning::routing::gossip::NetworkUpdate or not +pub enum COption_NetworkUpdateZ { + /// When we're in this state, this COption_NetworkUpdateZ contains a crate::lightning::routing::gossip::NetworkUpdate + Some(crate::lightning::routing::gossip::NetworkUpdate), + /// When we're in this state, this COption_NetworkUpdateZ contains nothing None } -impl COption_ClosureReasonZ { +impl COption_NetworkUpdateZ { #[allow(unused)] pub(crate) fn is_some(&self) -> bool { if let Self::None = self { false } else { true } } #[allow(unused)] pub(crate) fn is_none(&self) -> bool { !self.is_some() } - #[allow(unused)] pub(crate) fn take(mut self) -> crate::lightning::util::events::ClosureReason { + #[allow(unused)] pub(crate) fn take(mut self) -> crate::lightning::routing::gossip::NetworkUpdate { if let Self::Some(v) = self { v } else { unreachable!() } } } #[no_mangle] -/// Constructs a new COption_ClosureReasonZ containing a crate::lightning::util::events::ClosureReason -pub extern "C" fn COption_ClosureReasonZ_some(o: crate::lightning::util::events::ClosureReason) -> COption_ClosureReasonZ { - COption_ClosureReasonZ::Some(o) +/// Constructs a new COption_NetworkUpdateZ containing a crate::lightning::routing::gossip::NetworkUpdate +pub extern "C" fn COption_NetworkUpdateZ_some(o: crate::lightning::routing::gossip::NetworkUpdate) -> COption_NetworkUpdateZ { + COption_NetworkUpdateZ::Some(o) } #[no_mangle] -/// Constructs a new COption_ClosureReasonZ containing nothing -pub extern "C" fn COption_ClosureReasonZ_none() -> COption_ClosureReasonZ { - COption_ClosureReasonZ::None +/// Constructs a new COption_NetworkUpdateZ containing nothing +pub extern "C" fn COption_NetworkUpdateZ_none() -> COption_NetworkUpdateZ { + COption_NetworkUpdateZ::None } #[no_mangle] -/// Frees any resources associated with the crate::lightning::util::events::ClosureReason, if we are in the Some state -pub extern "C" fn COption_ClosureReasonZ_free(_res: COption_ClosureReasonZ) { } +/// Frees any resources associated with the crate::lightning::routing::gossip::NetworkUpdate, if we are in the Some state +pub extern "C" fn COption_NetworkUpdateZ_free(_res: COption_NetworkUpdateZ) { } #[no_mangle] -/// Creates a new COption_ClosureReasonZ which has the same data as `orig` +/// Creates a new COption_NetworkUpdateZ which has the same data as `orig` /// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn COption_ClosureReasonZ_clone(orig: &COption_ClosureReasonZ) -> COption_ClosureReasonZ { Clone::clone(&orig) } +pub extern "C" fn COption_NetworkUpdateZ_clone(orig: &COption_NetworkUpdateZ) -> COption_NetworkUpdateZ { Clone::clone(&orig) } #[repr(C)] -/// The contents of CResult_COption_ClosureReasonZDecodeErrorZ -pub union CResult_COption_ClosureReasonZDecodeErrorZPtr { +#[derive(Clone)] +/// An enum which can either contain a crate::lightning::util::events::PathFailure or not +pub enum COption_PathFailureZ { + /// When we're in this state, this COption_PathFailureZ contains a crate::lightning::util::events::PathFailure + Some(crate::lightning::util::events::PathFailure), + /// When we're in this state, this COption_PathFailureZ contains nothing + None +} +impl COption_PathFailureZ { + #[allow(unused)] pub(crate) fn is_some(&self) -> bool { + if let Self::None = self { false } else { true } + } + #[allow(unused)] pub(crate) fn is_none(&self) -> bool { + !self.is_some() + } + #[allow(unused)] pub(crate) fn take(mut self) -> crate::lightning::util::events::PathFailure { + if let Self::Some(v) = self { v } else { unreachable!() } + } +} +#[no_mangle] +/// Constructs a new COption_PathFailureZ containing a crate::lightning::util::events::PathFailure +pub extern "C" fn COption_PathFailureZ_some(o: crate::lightning::util::events::PathFailure) -> COption_PathFailureZ { + COption_PathFailureZ::Some(o) +} +#[no_mangle] +/// Constructs a new COption_PathFailureZ containing nothing +pub extern "C" fn COption_PathFailureZ_none() -> COption_PathFailureZ { + COption_PathFailureZ::None +} +#[no_mangle] +/// Frees any resources associated with the crate::lightning::util::events::PathFailure, if we are in the Some state +pub extern "C" fn COption_PathFailureZ_free(_res: COption_PathFailureZ) { } +#[no_mangle] +/// Creates a new COption_PathFailureZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn COption_PathFailureZ_clone(orig: &COption_PathFailureZ) -> COption_PathFailureZ { Clone::clone(&orig) } +#[repr(C)] +/// The contents of CResult_COption_PathFailureZDecodeErrorZ +pub union CResult_COption_PathFailureZDecodeErrorZPtr { /// A pointer to the contents in the success state. /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::c_types::derived::COption_ClosureReasonZ, + pub result: *mut crate::c_types::derived::COption_PathFailureZ, /// A pointer to the contents in the error state. /// Reading from this pointer when `result_ok` is set is undefined. pub err: *mut crate::lightning::ln::msgs::DecodeError, } #[repr(C)] -/// A CResult_COption_ClosureReasonZDecodeErrorZ represents the result of a fallible operation, -/// containing a crate::c_types::derived::COption_ClosureReasonZ on success and a crate::lightning::ln::msgs::DecodeError on failure. +/// A CResult_COption_PathFailureZDecodeErrorZ represents the result of a fallible operation, +/// containing a crate::c_types::derived::COption_PathFailureZ on success and a crate::lightning::ln::msgs::DecodeError on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_COption_ClosureReasonZDecodeErrorZ { - /// The contents of this CResult_COption_ClosureReasonZDecodeErrorZ, accessible via either +pub struct CResult_COption_PathFailureZDecodeErrorZ { + /// The contents of this CResult_COption_PathFailureZDecodeErrorZ, accessible via either /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_COption_ClosureReasonZDecodeErrorZPtr, - /// Whether this CResult_COption_ClosureReasonZDecodeErrorZ represents a success state. + pub contents: CResult_COption_PathFailureZDecodeErrorZPtr, + /// Whether this CResult_COption_PathFailureZDecodeErrorZ represents a success state. pub result_ok: bool, } #[no_mangle] -/// Creates a new CResult_COption_ClosureReasonZDecodeErrorZ in the success state. -pub extern "C" fn CResult_COption_ClosureReasonZDecodeErrorZ_ok(o: crate::c_types::derived::COption_ClosureReasonZ) -> CResult_COption_ClosureReasonZDecodeErrorZ { - CResult_COption_ClosureReasonZDecodeErrorZ { - contents: CResult_COption_ClosureReasonZDecodeErrorZPtr { +/// Creates a new CResult_COption_PathFailureZDecodeErrorZ in the success state. +pub extern "C" fn CResult_COption_PathFailureZDecodeErrorZ_ok(o: crate::c_types::derived::COption_PathFailureZ) -> CResult_COption_PathFailureZDecodeErrorZ { + CResult_COption_PathFailureZDecodeErrorZ { + contents: CResult_COption_PathFailureZDecodeErrorZPtr { result: Box::into_raw(Box::new(o)), }, result_ok: true, } } #[no_mangle] -/// Creates a new CResult_COption_ClosureReasonZDecodeErrorZ in the error state. -pub extern "C" fn CResult_COption_ClosureReasonZDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_COption_ClosureReasonZDecodeErrorZ { - CResult_COption_ClosureReasonZDecodeErrorZ { - contents: CResult_COption_ClosureReasonZDecodeErrorZPtr { +/// Creates a new CResult_COption_PathFailureZDecodeErrorZ in the error state. +pub extern "C" fn CResult_COption_PathFailureZDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_COption_PathFailureZDecodeErrorZ { + CResult_COption_PathFailureZDecodeErrorZ { + contents: CResult_COption_PathFailureZDecodeErrorZPtr { err: Box::into_raw(Box::new(e)), }, result_ok: false, @@ -3248,7 +3469,140 @@ pub extern "C" fn CResult_COption_ClosureReasonZDecodeErrorZ_err(e: crate::light } /// Checks if the given object is currently in the success state #[no_mangle] -pub extern "C" fn CResult_COption_ClosureReasonZDecodeErrorZ_is_ok(o: &CResult_COption_ClosureReasonZDecodeErrorZ) -> bool { +pub extern "C" fn CResult_COption_PathFailureZDecodeErrorZ_is_ok(o: &CResult_COption_PathFailureZDecodeErrorZ) -> bool { + o.result_ok +} +#[no_mangle] +/// Frees any resources used by the CResult_COption_PathFailureZDecodeErrorZ. +pub extern "C" fn CResult_COption_PathFailureZDecodeErrorZ_free(_res: CResult_COption_PathFailureZDecodeErrorZ) { } +impl Drop for CResult_COption_PathFailureZDecodeErrorZ { + fn drop(&mut self) { + if self.result_ok { + if unsafe { !(self.contents.result as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.result) }; + } + } else { + if unsafe { !(self.contents.err as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.err) }; + } + } + } +} +impl From> for CResult_COption_PathFailureZDecodeErrorZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { + let contents = if o.result_ok { + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = core::ptr::null_mut() }; + CResult_COption_PathFailureZDecodeErrorZPtr { result } + } else { + let err = unsafe { o.contents.err }; + unsafe { o.contents.err = core::ptr::null_mut(); } + CResult_COption_PathFailureZDecodeErrorZPtr { err } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_COption_PathFailureZDecodeErrorZ { + fn clone(&self) -> Self { + if self.result_ok { + Self { result_ok: true, contents: CResult_COption_PathFailureZDecodeErrorZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + } } + } else { + Self { result_ok: false, contents: CResult_COption_PathFailureZDecodeErrorZPtr { + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + } } + } + } +} +#[no_mangle] +/// Creates a new CResult_COption_PathFailureZDecodeErrorZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_COption_PathFailureZDecodeErrorZ_clone(orig: &CResult_COption_PathFailureZDecodeErrorZ) -> CResult_COption_PathFailureZDecodeErrorZ { Clone::clone(&orig) } +#[repr(C)] +#[derive(Clone)] +/// An enum which can either contain a crate::lightning::util::events::ClosureReason or not +pub enum COption_ClosureReasonZ { + /// When we're in this state, this COption_ClosureReasonZ contains a crate::lightning::util::events::ClosureReason + Some(crate::lightning::util::events::ClosureReason), + /// When we're in this state, this COption_ClosureReasonZ contains nothing + None +} +impl COption_ClosureReasonZ { + #[allow(unused)] pub(crate) fn is_some(&self) -> bool { + if let Self::None = self { false } else { true } + } + #[allow(unused)] pub(crate) fn is_none(&self) -> bool { + !self.is_some() + } + #[allow(unused)] pub(crate) fn take(mut self) -> crate::lightning::util::events::ClosureReason { + if let Self::Some(v) = self { v } else { unreachable!() } + } +} +#[no_mangle] +/// Constructs a new COption_ClosureReasonZ containing a crate::lightning::util::events::ClosureReason +pub extern "C" fn COption_ClosureReasonZ_some(o: crate::lightning::util::events::ClosureReason) -> COption_ClosureReasonZ { + COption_ClosureReasonZ::Some(o) +} +#[no_mangle] +/// Constructs a new COption_ClosureReasonZ containing nothing +pub extern "C" fn COption_ClosureReasonZ_none() -> COption_ClosureReasonZ { + COption_ClosureReasonZ::None +} +#[no_mangle] +/// Frees any resources associated with the crate::lightning::util::events::ClosureReason, if we are in the Some state +pub extern "C" fn COption_ClosureReasonZ_free(_res: COption_ClosureReasonZ) { } +#[no_mangle] +/// Creates a new COption_ClosureReasonZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn COption_ClosureReasonZ_clone(orig: &COption_ClosureReasonZ) -> COption_ClosureReasonZ { Clone::clone(&orig) } +#[repr(C)] +/// The contents of CResult_COption_ClosureReasonZDecodeErrorZ +pub union CResult_COption_ClosureReasonZDecodeErrorZPtr { + /// A pointer to the contents in the success state. + /// Reading from this pointer when `result_ok` is not set is undefined. + pub result: *mut crate::c_types::derived::COption_ClosureReasonZ, + /// A pointer to the contents in the error state. + /// Reading from this pointer when `result_ok` is set is undefined. + pub err: *mut crate::lightning::ln::msgs::DecodeError, +} +#[repr(C)] +/// A CResult_COption_ClosureReasonZDecodeErrorZ represents the result of a fallible operation, +/// containing a crate::c_types::derived::COption_ClosureReasonZ on success and a crate::lightning::ln::msgs::DecodeError on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_COption_ClosureReasonZDecodeErrorZ { + /// The contents of this CResult_COption_ClosureReasonZDecodeErrorZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_COption_ClosureReasonZDecodeErrorZPtr, + /// Whether this CResult_COption_ClosureReasonZDecodeErrorZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_COption_ClosureReasonZDecodeErrorZ in the success state. +pub extern "C" fn CResult_COption_ClosureReasonZDecodeErrorZ_ok(o: crate::c_types::derived::COption_ClosureReasonZ) -> CResult_COption_ClosureReasonZDecodeErrorZ { + CResult_COption_ClosureReasonZDecodeErrorZ { + contents: CResult_COption_ClosureReasonZDecodeErrorZPtr { + result: Box::into_raw(Box::new(o)), + }, + result_ok: true, + } +} +#[no_mangle] +/// Creates a new CResult_COption_ClosureReasonZDecodeErrorZ in the error state. +pub extern "C" fn CResult_COption_ClosureReasonZDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_COption_ClosureReasonZDecodeErrorZ { + CResult_COption_ClosureReasonZDecodeErrorZ { + contents: CResult_COption_ClosureReasonZDecodeErrorZPtr { + err: Box::into_raw(Box::new(e)), + }, + result_ok: false, + } +} +/// Checks if the given object is currently in the success state +#[no_mangle] +pub extern "C" fn CResult_COption_ClosureReasonZDecodeErrorZ_is_ok(o: &CResult_COption_ClosureReasonZDecodeErrorZ) -> bool { o.result_ok } #[no_mangle] @@ -3472,43 +3826,6 @@ pub extern "C" fn COption_u128Z_free(_res: COption_u128Z) { } /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn COption_u128Z_clone(orig: &COption_u128Z) -> COption_u128Z { Clone::clone(&orig) } #[repr(C)] -#[derive(Clone)] -/// An enum which can either contain a crate::lightning::routing::gossip::NetworkUpdate or not -pub enum COption_NetworkUpdateZ { - /// When we're in this state, this COption_NetworkUpdateZ contains a crate::lightning::routing::gossip::NetworkUpdate - Some(crate::lightning::routing::gossip::NetworkUpdate), - /// When we're in this state, this COption_NetworkUpdateZ contains nothing - None -} -impl COption_NetworkUpdateZ { - #[allow(unused)] pub(crate) fn is_some(&self) -> bool { - if let Self::None = self { false } else { true } - } - #[allow(unused)] pub(crate) fn is_none(&self) -> bool { - !self.is_some() - } - #[allow(unused)] pub(crate) fn take(mut self) -> crate::lightning::routing::gossip::NetworkUpdate { - if let Self::Some(v) = self { v } else { unreachable!() } - } -} -#[no_mangle] -/// Constructs a new COption_NetworkUpdateZ containing a crate::lightning::routing::gossip::NetworkUpdate -pub extern "C" fn COption_NetworkUpdateZ_some(o: crate::lightning::routing::gossip::NetworkUpdate) -> COption_NetworkUpdateZ { - COption_NetworkUpdateZ::Some(o) -} -#[no_mangle] -/// Constructs a new COption_NetworkUpdateZ containing nothing -pub extern "C" fn COption_NetworkUpdateZ_none() -> COption_NetworkUpdateZ { - COption_NetworkUpdateZ::None -} -#[no_mangle] -/// Frees any resources associated with the crate::lightning::routing::gossip::NetworkUpdate, if we are in the Some state -pub extern "C" fn COption_NetworkUpdateZ_free(_res: COption_NetworkUpdateZ) { } -#[no_mangle] -/// Creates a new COption_NetworkUpdateZ which has the same data as `orig` -/// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn COption_NetworkUpdateZ_clone(orig: &COption_NetworkUpdateZ) -> COption_NetworkUpdateZ { Clone::clone(&orig) } -#[repr(C)] /// A dynamically-allocated array of crate::lightning::chain::keysinterface::SpendableOutputDescriptors of arbitrary size. /// This corresponds to std::vector in C++ pub struct CVec_SpendableOutputDescriptorZ { @@ -3734,102 +4051,6 @@ impl Clone for CVec_MessageSendEventZ { } } #[repr(C)] -/// The contents of CResult_TxOutAccessErrorZ -pub union CResult_TxOutAccessErrorZPtr { - /// A pointer to the contents in the success state. - /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::c_types::TxOut, - /// A pointer to the contents in the error state. - /// Reading from this pointer when `result_ok` is set is undefined. - pub err: *mut crate::lightning::chain::AccessError, -} -#[repr(C)] -/// A CResult_TxOutAccessErrorZ represents the result of a fallible operation, -/// containing a crate::c_types::TxOut on success and a crate::lightning::chain::AccessError on failure. -/// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_TxOutAccessErrorZ { - /// The contents of this CResult_TxOutAccessErrorZ, accessible via either - /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_TxOutAccessErrorZPtr, - /// Whether this CResult_TxOutAccessErrorZ represents a success state. - pub result_ok: bool, -} -#[no_mangle] -/// Creates a new CResult_TxOutAccessErrorZ in the success state. -pub extern "C" fn CResult_TxOutAccessErrorZ_ok(o: crate::c_types::TxOut) -> CResult_TxOutAccessErrorZ { - CResult_TxOutAccessErrorZ { - contents: CResult_TxOutAccessErrorZPtr { - result: Box::into_raw(Box::new(o)), - }, - result_ok: true, - } -} -#[no_mangle] -/// Creates a new CResult_TxOutAccessErrorZ in the error state. -pub extern "C" fn CResult_TxOutAccessErrorZ_err(e: crate::lightning::chain::AccessError) -> CResult_TxOutAccessErrorZ { - CResult_TxOutAccessErrorZ { - contents: CResult_TxOutAccessErrorZPtr { - err: Box::into_raw(Box::new(e)), - }, - result_ok: false, - } -} -/// Checks if the given object is currently in the success state -#[no_mangle] -pub extern "C" fn CResult_TxOutAccessErrorZ_is_ok(o: &CResult_TxOutAccessErrorZ) -> bool { - o.result_ok -} -#[no_mangle] -/// Frees any resources used by the CResult_TxOutAccessErrorZ. -pub extern "C" fn CResult_TxOutAccessErrorZ_free(_res: CResult_TxOutAccessErrorZ) { } -impl Drop for CResult_TxOutAccessErrorZ { - fn drop(&mut self) { - if self.result_ok { - if unsafe { !(self.contents.result as *mut ()).is_null() } { - let _ = unsafe { Box::from_raw(self.contents.result) }; - } - } else { - if unsafe { !(self.contents.err as *mut ()).is_null() } { - let _ = unsafe { Box::from_raw(self.contents.err) }; - } - } - } -} -impl From> for CResult_TxOutAccessErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { - let contents = if o.result_ok { - let result = unsafe { o.contents.result }; - unsafe { o.contents.result = core::ptr::null_mut() }; - CResult_TxOutAccessErrorZPtr { result } - } else { - let err = unsafe { o.contents.err }; - unsafe { o.contents.err = core::ptr::null_mut(); } - CResult_TxOutAccessErrorZPtr { err } - }; - Self { - contents, - result_ok: o.result_ok, - } - } -} -impl Clone for CResult_TxOutAccessErrorZ { - fn clone(&self) -> Self { - if self.result_ok { - Self { result_ok: true, contents: CResult_TxOutAccessErrorZPtr { - result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) - } } - } else { - Self { result_ok: false, contents: CResult_TxOutAccessErrorZPtr { - err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) - } } - } - } -} -#[no_mangle] -/// Creates a new CResult_TxOutAccessErrorZ which has the same data as `orig` -/// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult_TxOutAccessErrorZ_clone(orig: &CResult_TxOutAccessErrorZ) -> CResult_TxOutAccessErrorZ { Clone::clone(&orig) } -#[repr(C)] /// A tuple of 2 elements. See the individual fields for the types contained. pub struct C2Tuple_usizeTransactionZ { /// The element at position 0 @@ -4319,37 +4540,158 @@ pub extern "C" fn COption_C2Tuple_u64u64ZZ_free(_res: COption_C2Tuple_u64u64ZZ) /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn COption_C2Tuple_u64u64ZZ_clone(orig: &COption_C2Tuple_u64u64ZZ) -> COption_C2Tuple_u64u64ZZ { Clone::clone(&orig) } #[repr(C)] -/// A dynamically-allocated array of crate::lightning::routing::gossip::NodeIds of arbitrary size. -/// This corresponds to std::vector in C++ -pub struct CVec_NodeIdZ { - /// The elements in the array. - /// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). - pub data: *mut crate::lightning::routing::gossip::NodeId, - /// The number of elements pointed to by `data`. - pub datalen: usize +/// A tuple of 2 elements. See the individual fields for the types contained. +pub struct C2Tuple_Z { + /// The element at position 0 + pub a: crate::c_types::EightU16s, + /// The element at position 1 + pub b: crate::c_types::EightU16s, } -impl CVec_NodeIdZ { - #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { - if self.datalen == 0 { return Vec::new(); } - let ret = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }.into(); - self.data = core::ptr::null_mut(); - self.datalen = 0; - ret - } - #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::lightning::routing::gossip::NodeId] { - unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) } +impl From<(crate::c_types::EightU16s, crate::c_types::EightU16s)> for C2Tuple_Z { + fn from (tup: (crate::c_types::EightU16s, crate::c_types::EightU16s)) -> Self { + Self { + a: tup.0, + b: tup.1, + } } } -impl From> for CVec_NodeIdZ { - fn from(v: Vec) -> Self { - let datalen = v.len(); - let data = Box::into_raw(v.into_boxed_slice()); - Self { datalen, data: unsafe { (*data).as_mut_ptr() } } +impl C2Tuple_Z { + #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::c_types::EightU16s, crate::c_types::EightU16s) { + (self.a, self.b) } } -#[no_mangle] -/// Frees the buffer pointed to by `data` if `datalen` is non-0. -pub extern "C" fn CVec_NodeIdZ_free(_res: CVec_NodeIdZ) { } +impl Clone for C2Tuple_Z { + fn clone(&self) -> Self { + Self { + a: Clone::clone(&self.a), + b: Clone::clone(&self.b), + } + } +} +#[no_mangle] +/// Creates a new tuple which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn C2Tuple_Z_clone(orig: &C2Tuple_Z) -> C2Tuple_Z { Clone::clone(&orig) } +/// Creates a new C2Tuple_Z from the contained elements. +#[no_mangle] +pub extern "C" fn C2Tuple_Z_new(a: crate::c_types::EightU16s, b: crate::c_types::EightU16s) -> C2Tuple_Z { + C2Tuple_Z { a, b, } +} + +#[no_mangle] +/// Frees any resources used by the C2Tuple_Z. +pub extern "C" fn C2Tuple_Z_free(_res: C2Tuple_Z) { } +#[repr(C)] +/// A tuple of 2 elements. See the individual fields for the types contained. +pub struct C2Tuple__u168_u168Z { + /// The element at position 0 + pub a: crate::c_types::EightU16s, + /// The element at position 1 + pub b: crate::c_types::EightU16s, +} +impl From<(crate::c_types::EightU16s, crate::c_types::EightU16s)> for C2Tuple__u168_u168Z { + fn from (tup: (crate::c_types::EightU16s, crate::c_types::EightU16s)) -> Self { + Self { + a: tup.0, + b: tup.1, + } + } +} +impl C2Tuple__u168_u168Z { + #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::c_types::EightU16s, crate::c_types::EightU16s) { + (self.a, self.b) + } +} +impl Clone for C2Tuple__u168_u168Z { + fn clone(&self) -> Self { + Self { + a: Clone::clone(&self.a), + b: Clone::clone(&self.b), + } + } +} +#[no_mangle] +/// Creates a new tuple which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn C2Tuple__u168_u168Z_clone(orig: &C2Tuple__u168_u168Z) -> C2Tuple__u168_u168Z { Clone::clone(&orig) } +/// Creates a new C2Tuple__u168_u168Z from the contained elements. +#[no_mangle] +pub extern "C" fn C2Tuple__u168_u168Z_new(a: crate::c_types::EightU16s, b: crate::c_types::EightU16s) -> C2Tuple__u168_u168Z { + C2Tuple__u168_u168Z { a, b, } +} + +#[no_mangle] +/// Frees any resources used by the C2Tuple__u168_u168Z. +pub extern "C" fn C2Tuple__u168_u168Z_free(_res: C2Tuple__u168_u168Z) { } +#[repr(C)] +#[derive(Clone)] +/// An enum which can either contain a crate::c_types::derived::C2Tuple__u168_u168Z or not +pub enum COption_C2Tuple_EightU16sEightU16sZZ { + /// When we're in this state, this COption_C2Tuple_EightU16sEightU16sZZ contains a crate::c_types::derived::C2Tuple__u168_u168Z + Some(crate::c_types::derived::C2Tuple__u168_u168Z), + /// When we're in this state, this COption_C2Tuple_EightU16sEightU16sZZ contains nothing + None +} +impl COption_C2Tuple_EightU16sEightU16sZZ { + #[allow(unused)] pub(crate) fn is_some(&self) -> bool { + if let Self::None = self { false } else { true } + } + #[allow(unused)] pub(crate) fn is_none(&self) -> bool { + !self.is_some() + } + #[allow(unused)] pub(crate) fn take(mut self) -> crate::c_types::derived::C2Tuple__u168_u168Z { + if let Self::Some(v) = self { v } else { unreachable!() } + } +} +#[no_mangle] +/// Constructs a new COption_C2Tuple_EightU16sEightU16sZZ containing a crate::c_types::derived::C2Tuple__u168_u168Z +pub extern "C" fn COption_C2Tuple_EightU16sEightU16sZZ_some(o: crate::c_types::derived::C2Tuple__u168_u168Z) -> COption_C2Tuple_EightU16sEightU16sZZ { + COption_C2Tuple_EightU16sEightU16sZZ::Some(o) +} +#[no_mangle] +/// Constructs a new COption_C2Tuple_EightU16sEightU16sZZ containing nothing +pub extern "C" fn COption_C2Tuple_EightU16sEightU16sZZ_none() -> COption_C2Tuple_EightU16sEightU16sZZ { + COption_C2Tuple_EightU16sEightU16sZZ::None +} +#[no_mangle] +/// Frees any resources associated with the crate::c_types::derived::C2Tuple__u168_u168Z, if we are in the Some state +pub extern "C" fn COption_C2Tuple_EightU16sEightU16sZZ_free(_res: COption_C2Tuple_EightU16sEightU16sZZ) { } +#[no_mangle] +/// Creates a new COption_C2Tuple_EightU16sEightU16sZZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn COption_C2Tuple_EightU16sEightU16sZZ_clone(orig: &COption_C2Tuple_EightU16sEightU16sZZ) -> COption_C2Tuple_EightU16sEightU16sZZ { Clone::clone(&orig) } +#[repr(C)] +/// A dynamically-allocated array of crate::lightning::routing::gossip::NodeIds of arbitrary size. +/// This corresponds to std::vector in C++ +pub struct CVec_NodeIdZ { + /// The elements in the array. + /// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). + pub data: *mut crate::lightning::routing::gossip::NodeId, + /// The number of elements pointed to by `data`. + pub datalen: usize +} +impl CVec_NodeIdZ { + #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { + if self.datalen == 0 { return Vec::new(); } + let ret = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }.into(); + self.data = core::ptr::null_mut(); + self.datalen = 0; + ret + } + #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::lightning::routing::gossip::NodeId] { + unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) } + } +} +impl From> for CVec_NodeIdZ { + fn from(v: Vec) -> Self { + let datalen = v.len(); + let data = Box::into_raw(v.into_boxed_slice()); + Self { datalen, data: unsafe { (*data).as_mut_ptr() } } + } +} +#[no_mangle] +/// Frees the buffer pointed to by `data` if `datalen` is non-0. +pub extern "C" fn CVec_NodeIdZ_free(_res: CVec_NodeIdZ) { } impl Drop for CVec_NodeIdZ { fn drop(&mut self) { if self.datalen == 0 { return; } @@ -4828,137 +5170,41 @@ impl Clone for CResult_InvoiceFeaturesDecodeErrorZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_InvoiceFeaturesDecodeErrorZ_clone(orig: &CResult_InvoiceFeaturesDecodeErrorZ) -> CResult_InvoiceFeaturesDecodeErrorZ { Clone::clone(&orig) } #[repr(C)] -/// The contents of CResult_ChannelTypeFeaturesDecodeErrorZ -pub union CResult_ChannelTypeFeaturesDecodeErrorZPtr { - /// A pointer to the contents in the success state. - /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::lightning::ln::features::ChannelTypeFeatures, - /// A pointer to the contents in the error state. - /// Reading from this pointer when `result_ok` is set is undefined. - pub err: *mut crate::lightning::ln::msgs::DecodeError, -} -#[repr(C)] -/// A CResult_ChannelTypeFeaturesDecodeErrorZ represents the result of a fallible operation, -/// containing a crate::lightning::ln::features::ChannelTypeFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. -/// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_ChannelTypeFeaturesDecodeErrorZ { - /// The contents of this CResult_ChannelTypeFeaturesDecodeErrorZ, accessible via either - /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr, - /// Whether this CResult_ChannelTypeFeaturesDecodeErrorZ represents a success state. - pub result_ok: bool, -} -#[no_mangle] -/// Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ in the success state. -pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_ok(o: crate::lightning::ln::features::ChannelTypeFeatures) -> CResult_ChannelTypeFeaturesDecodeErrorZ { - CResult_ChannelTypeFeaturesDecodeErrorZ { - contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr { - result: Box::into_raw(Box::new(o)), - }, - result_ok: true, - } -} -#[no_mangle] -/// Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ in the error state. -pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_ChannelTypeFeaturesDecodeErrorZ { - CResult_ChannelTypeFeaturesDecodeErrorZ { - contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr { - err: Box::into_raw(Box::new(e)), - }, - result_ok: false, - } -} -/// Checks if the given object is currently in the success state -#[no_mangle] -pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_is_ok(o: &CResult_ChannelTypeFeaturesDecodeErrorZ) -> bool { - o.result_ok -} -#[no_mangle] -/// Frees any resources used by the CResult_ChannelTypeFeaturesDecodeErrorZ. -pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_free(_res: CResult_ChannelTypeFeaturesDecodeErrorZ) { } -impl Drop for CResult_ChannelTypeFeaturesDecodeErrorZ { - fn drop(&mut self) { - if self.result_ok { - if unsafe { !(self.contents.result as *mut ()).is_null() } { - let _ = unsafe { Box::from_raw(self.contents.result) }; - } - } else { - if unsafe { !(self.contents.err as *mut ()).is_null() } { - let _ = unsafe { Box::from_raw(self.contents.err) }; - } - } - } -} -impl From> for CResult_ChannelTypeFeaturesDecodeErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { - let contents = if o.result_ok { - let result = unsafe { o.contents.result }; - unsafe { o.contents.result = core::ptr::null_mut() }; - CResult_ChannelTypeFeaturesDecodeErrorZPtr { result } - } else { - let err = unsafe { o.contents.err }; - unsafe { o.contents.err = core::ptr::null_mut(); } - CResult_ChannelTypeFeaturesDecodeErrorZPtr { err } - }; - Self { - contents, - result_ok: o.result_ok, - } - } -} -impl Clone for CResult_ChannelTypeFeaturesDecodeErrorZ { - fn clone(&self) -> Self { - if self.result_ok { - Self { result_ok: true, contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr { - result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) - } } - } else { - Self { result_ok: false, contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr { - err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) - } } - } - } -} -#[no_mangle] -/// Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ which has the same data as `orig` -/// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_clone(orig: &CResult_ChannelTypeFeaturesDecodeErrorZ) -> CResult_ChannelTypeFeaturesDecodeErrorZ { Clone::clone(&orig) } -#[repr(C)] -/// The contents of CResult_OfferFeaturesDecodeErrorZ -pub union CResult_OfferFeaturesDecodeErrorZPtr { +/// The contents of CResult_BlindedHopFeaturesDecodeErrorZ +pub union CResult_BlindedHopFeaturesDecodeErrorZPtr { /// A pointer to the contents in the success state. /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::lightning::ln::features::OfferFeatures, + pub result: *mut crate::lightning::ln::features::BlindedHopFeatures, /// A pointer to the contents in the error state. /// Reading from this pointer when `result_ok` is set is undefined. pub err: *mut crate::lightning::ln::msgs::DecodeError, } #[repr(C)] -/// A CResult_OfferFeaturesDecodeErrorZ represents the result of a fallible operation, -/// containing a crate::lightning::ln::features::OfferFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. +/// A CResult_BlindedHopFeaturesDecodeErrorZ represents the result of a fallible operation, +/// containing a crate::lightning::ln::features::BlindedHopFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_OfferFeaturesDecodeErrorZ { - /// The contents of this CResult_OfferFeaturesDecodeErrorZ, accessible via either +pub struct CResult_BlindedHopFeaturesDecodeErrorZ { + /// The contents of this CResult_BlindedHopFeaturesDecodeErrorZ, accessible via either /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_OfferFeaturesDecodeErrorZPtr, - /// Whether this CResult_OfferFeaturesDecodeErrorZ represents a success state. + pub contents: CResult_BlindedHopFeaturesDecodeErrorZPtr, + /// Whether this CResult_BlindedHopFeaturesDecodeErrorZ represents a success state. pub result_ok: bool, } #[no_mangle] -/// Creates a new CResult_OfferFeaturesDecodeErrorZ in the success state. -pub extern "C" fn CResult_OfferFeaturesDecodeErrorZ_ok(o: crate::lightning::ln::features::OfferFeatures) -> CResult_OfferFeaturesDecodeErrorZ { - CResult_OfferFeaturesDecodeErrorZ { - contents: CResult_OfferFeaturesDecodeErrorZPtr { +/// Creates a new CResult_BlindedHopFeaturesDecodeErrorZ in the success state. +pub extern "C" fn CResult_BlindedHopFeaturesDecodeErrorZ_ok(o: crate::lightning::ln::features::BlindedHopFeatures) -> CResult_BlindedHopFeaturesDecodeErrorZ { + CResult_BlindedHopFeaturesDecodeErrorZ { + contents: CResult_BlindedHopFeaturesDecodeErrorZPtr { result: Box::into_raw(Box::new(o)), }, result_ok: true, } } #[no_mangle] -/// Creates a new CResult_OfferFeaturesDecodeErrorZ in the error state. -pub extern "C" fn CResult_OfferFeaturesDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_OfferFeaturesDecodeErrorZ { - CResult_OfferFeaturesDecodeErrorZ { - contents: CResult_OfferFeaturesDecodeErrorZPtr { +/// Creates a new CResult_BlindedHopFeaturesDecodeErrorZ in the error state. +pub extern "C" fn CResult_BlindedHopFeaturesDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_BlindedHopFeaturesDecodeErrorZ { + CResult_BlindedHopFeaturesDecodeErrorZ { + contents: CResult_BlindedHopFeaturesDecodeErrorZPtr { err: Box::into_raw(Box::new(e)), }, result_ok: false, @@ -4966,13 +5212,13 @@ pub extern "C" fn CResult_OfferFeaturesDecodeErrorZ_err(e: crate::lightning::ln: } /// Checks if the given object is currently in the success state #[no_mangle] -pub extern "C" fn CResult_OfferFeaturesDecodeErrorZ_is_ok(o: &CResult_OfferFeaturesDecodeErrorZ) -> bool { +pub extern "C" fn CResult_BlindedHopFeaturesDecodeErrorZ_is_ok(o: &CResult_BlindedHopFeaturesDecodeErrorZ) -> bool { o.result_ok } #[no_mangle] -/// Frees any resources used by the CResult_OfferFeaturesDecodeErrorZ. -pub extern "C" fn CResult_OfferFeaturesDecodeErrorZ_free(_res: CResult_OfferFeaturesDecodeErrorZ) { } -impl Drop for CResult_OfferFeaturesDecodeErrorZ { +/// Frees any resources used by the CResult_BlindedHopFeaturesDecodeErrorZ. +pub extern "C" fn CResult_BlindedHopFeaturesDecodeErrorZ_free(_res: CResult_BlindedHopFeaturesDecodeErrorZ) { } +impl Drop for CResult_BlindedHopFeaturesDecodeErrorZ { fn drop(&mut self) { if self.result_ok { if unsafe { !(self.contents.result as *mut ()).is_null() } { @@ -4985,16 +5231,16 @@ impl Drop for CResult_OfferFeaturesDecodeErrorZ { } } } -impl From> for CResult_OfferFeaturesDecodeErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_BlindedHopFeaturesDecodeErrorZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = core::ptr::null_mut() }; - CResult_OfferFeaturesDecodeErrorZPtr { result } + CResult_BlindedHopFeaturesDecodeErrorZPtr { result } } else { let err = unsafe { o.contents.err }; unsafe { o.contents.err = core::ptr::null_mut(); } - CResult_OfferFeaturesDecodeErrorZPtr { err } + CResult_BlindedHopFeaturesDecodeErrorZPtr { err } }; Self { contents, @@ -5002,59 +5248,59 @@ impl From Self { if self.result_ok { - Self { result_ok: true, contents: CResult_OfferFeaturesDecodeErrorZPtr { - result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + Self { result_ok: true, contents: CResult_BlindedHopFeaturesDecodeErrorZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) } } } else { - Self { result_ok: false, contents: CResult_OfferFeaturesDecodeErrorZPtr { + Self { result_ok: false, contents: CResult_BlindedHopFeaturesDecodeErrorZPtr { err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) } } } } } #[no_mangle] -/// Creates a new CResult_OfferFeaturesDecodeErrorZ which has the same data as `orig` +/// Creates a new CResult_BlindedHopFeaturesDecodeErrorZ which has the same data as `orig` /// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult_OfferFeaturesDecodeErrorZ_clone(orig: &CResult_OfferFeaturesDecodeErrorZ) -> CResult_OfferFeaturesDecodeErrorZ { Clone::clone(&orig) } +pub extern "C" fn CResult_BlindedHopFeaturesDecodeErrorZ_clone(orig: &CResult_BlindedHopFeaturesDecodeErrorZ) -> CResult_BlindedHopFeaturesDecodeErrorZ { Clone::clone(&orig) } #[repr(C)] -/// The contents of CResult_InvoiceRequestFeaturesDecodeErrorZ -pub union CResult_InvoiceRequestFeaturesDecodeErrorZPtr { +/// The contents of CResult_ChannelTypeFeaturesDecodeErrorZ +pub union CResult_ChannelTypeFeaturesDecodeErrorZPtr { /// A pointer to the contents in the success state. /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::lightning::ln::features::InvoiceRequestFeatures, + pub result: *mut crate::lightning::ln::features::ChannelTypeFeatures, /// A pointer to the contents in the error state. /// Reading from this pointer when `result_ok` is set is undefined. pub err: *mut crate::lightning::ln::msgs::DecodeError, } #[repr(C)] -/// A CResult_InvoiceRequestFeaturesDecodeErrorZ represents the result of a fallible operation, -/// containing a crate::lightning::ln::features::InvoiceRequestFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. +/// A CResult_ChannelTypeFeaturesDecodeErrorZ represents the result of a fallible operation, +/// containing a crate::lightning::ln::features::ChannelTypeFeatures on success and a crate::lightning::ln::msgs::DecodeError on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_InvoiceRequestFeaturesDecodeErrorZ { - /// The contents of this CResult_InvoiceRequestFeaturesDecodeErrorZ, accessible via either +pub struct CResult_ChannelTypeFeaturesDecodeErrorZ { + /// The contents of this CResult_ChannelTypeFeaturesDecodeErrorZ, accessible via either /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_InvoiceRequestFeaturesDecodeErrorZPtr, - /// Whether this CResult_InvoiceRequestFeaturesDecodeErrorZ represents a success state. + pub contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr, + /// Whether this CResult_ChannelTypeFeaturesDecodeErrorZ represents a success state. pub result_ok: bool, } #[no_mangle] -/// Creates a new CResult_InvoiceRequestFeaturesDecodeErrorZ in the success state. -pub extern "C" fn CResult_InvoiceRequestFeaturesDecodeErrorZ_ok(o: crate::lightning::ln::features::InvoiceRequestFeatures) -> CResult_InvoiceRequestFeaturesDecodeErrorZ { - CResult_InvoiceRequestFeaturesDecodeErrorZ { - contents: CResult_InvoiceRequestFeaturesDecodeErrorZPtr { +/// Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ in the success state. +pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_ok(o: crate::lightning::ln::features::ChannelTypeFeatures) -> CResult_ChannelTypeFeaturesDecodeErrorZ { + CResult_ChannelTypeFeaturesDecodeErrorZ { + contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr { result: Box::into_raw(Box::new(o)), }, result_ok: true, } } #[no_mangle] -/// Creates a new CResult_InvoiceRequestFeaturesDecodeErrorZ in the error state. -pub extern "C" fn CResult_InvoiceRequestFeaturesDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_InvoiceRequestFeaturesDecodeErrorZ { - CResult_InvoiceRequestFeaturesDecodeErrorZ { - contents: CResult_InvoiceRequestFeaturesDecodeErrorZPtr { +/// Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ in the error state. +pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_ChannelTypeFeaturesDecodeErrorZ { + CResult_ChannelTypeFeaturesDecodeErrorZ { + contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr { err: Box::into_raw(Box::new(e)), }, result_ok: false, @@ -5062,13 +5308,13 @@ pub extern "C" fn CResult_InvoiceRequestFeaturesDecodeErrorZ_err(e: crate::light } /// Checks if the given object is currently in the success state #[no_mangle] -pub extern "C" fn CResult_InvoiceRequestFeaturesDecodeErrorZ_is_ok(o: &CResult_InvoiceRequestFeaturesDecodeErrorZ) -> bool { +pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_is_ok(o: &CResult_ChannelTypeFeaturesDecodeErrorZ) -> bool { o.result_ok } #[no_mangle] -/// Frees any resources used by the CResult_InvoiceRequestFeaturesDecodeErrorZ. -pub extern "C" fn CResult_InvoiceRequestFeaturesDecodeErrorZ_free(_res: CResult_InvoiceRequestFeaturesDecodeErrorZ) { } -impl Drop for CResult_InvoiceRequestFeaturesDecodeErrorZ { +/// Frees any resources used by the CResult_ChannelTypeFeaturesDecodeErrorZ. +pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_free(_res: CResult_ChannelTypeFeaturesDecodeErrorZ) { } +impl Drop for CResult_ChannelTypeFeaturesDecodeErrorZ { fn drop(&mut self) { if self.result_ok { if unsafe { !(self.contents.result as *mut ()).is_null() } { @@ -5081,16 +5327,16 @@ impl Drop for CResult_InvoiceRequestFeaturesDecodeErrorZ { } } } -impl From> for CResult_InvoiceRequestFeaturesDecodeErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_ChannelTypeFeaturesDecodeErrorZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = core::ptr::null_mut() }; - CResult_InvoiceRequestFeaturesDecodeErrorZPtr { result } + CResult_ChannelTypeFeaturesDecodeErrorZPtr { result } } else { let err = unsafe { o.contents.err }; unsafe { o.contents.err = core::ptr::null_mut(); } - CResult_InvoiceRequestFeaturesDecodeErrorZPtr { err } + CResult_ChannelTypeFeaturesDecodeErrorZPtr { err } }; Self { contents, @@ -5098,23 +5344,23 @@ impl From Self { if self.result_ok { - Self { result_ok: true, contents: CResult_InvoiceRequestFeaturesDecodeErrorZPtr { - result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + Self { result_ok: true, contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) } } } else { - Self { result_ok: false, contents: CResult_InvoiceRequestFeaturesDecodeErrorZPtr { + Self { result_ok: false, contents: CResult_ChannelTypeFeaturesDecodeErrorZPtr { err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) } } } } } #[no_mangle] -/// Creates a new CResult_InvoiceRequestFeaturesDecodeErrorZ which has the same data as `orig` +/// Creates a new CResult_ChannelTypeFeaturesDecodeErrorZ which has the same data as `orig` /// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult_InvoiceRequestFeaturesDecodeErrorZ_clone(orig: &CResult_InvoiceRequestFeaturesDecodeErrorZ) -> CResult_InvoiceRequestFeaturesDecodeErrorZ { Clone::clone(&orig) } +pub extern "C" fn CResult_ChannelTypeFeaturesDecodeErrorZ_clone(orig: &CResult_ChannelTypeFeaturesDecodeErrorZ) -> CResult_ChannelTypeFeaturesDecodeErrorZ { Clone::clone(&orig) } #[repr(C)] /// The contents of CResult_NodeIdDecodeErrorZ pub union CResult_NodeIdDecodeErrorZPtr { @@ -5308,37 +5554,37 @@ impl Clone for CResult_COption_NetworkUpdateZDecodeErrorZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_COption_NetworkUpdateZDecodeErrorZ_clone(orig: &CResult_COption_NetworkUpdateZDecodeErrorZ) -> CResult_COption_NetworkUpdateZDecodeErrorZ { Clone::clone(&orig) } #[repr(C)] -/// An enum which can either contain a crate::lightning::chain::Access or not -pub enum COption_AccessZ { - /// When we're in this state, this COption_AccessZ contains a crate::lightning::chain::Access - Some(crate::lightning::chain::Access), - /// When we're in this state, this COption_AccessZ contains nothing +/// An enum which can either contain a crate::lightning::routing::utxo::UtxoLookup or not +pub enum COption_UtxoLookupZ { + /// When we're in this state, this COption_UtxoLookupZ contains a crate::lightning::routing::utxo::UtxoLookup + Some(crate::lightning::routing::utxo::UtxoLookup), + /// When we're in this state, this COption_UtxoLookupZ contains nothing None } -impl COption_AccessZ { +impl COption_UtxoLookupZ { #[allow(unused)] pub(crate) fn is_some(&self) -> bool { if let Self::None = self { false } else { true } } #[allow(unused)] pub(crate) fn is_none(&self) -> bool { !self.is_some() } - #[allow(unused)] pub(crate) fn take(mut self) -> crate::lightning::chain::Access { + #[allow(unused)] pub(crate) fn take(mut self) -> crate::lightning::routing::utxo::UtxoLookup { if let Self::Some(v) = self { v } else { unreachable!() } } } #[no_mangle] -/// Constructs a new COption_AccessZ containing a crate::lightning::chain::Access -pub extern "C" fn COption_AccessZ_some(o: crate::lightning::chain::Access) -> COption_AccessZ { - COption_AccessZ::Some(o) +/// Constructs a new COption_UtxoLookupZ containing a crate::lightning::routing::utxo::UtxoLookup +pub extern "C" fn COption_UtxoLookupZ_some(o: crate::lightning::routing::utxo::UtxoLookup) -> COption_UtxoLookupZ { + COption_UtxoLookupZ::Some(o) } #[no_mangle] -/// Constructs a new COption_AccessZ containing nothing -pub extern "C" fn COption_AccessZ_none() -> COption_AccessZ { - COption_AccessZ::None +/// Constructs a new COption_UtxoLookupZ containing nothing +pub extern "C" fn COption_UtxoLookupZ_none() -> COption_UtxoLookupZ { + COption_UtxoLookupZ::None } #[no_mangle] -/// Frees any resources associated with the crate::lightning::chain::Access, if we are in the Some state -pub extern "C" fn COption_AccessZ_free(_res: COption_AccessZ) { } +/// Frees any resources associated with the crate::lightning::routing::utxo::UtxoLookup, if we are in the Some state +pub extern "C" fn COption_UtxoLookupZ_free(_res: COption_UtxoLookupZ) { } #[repr(C)] /// The contents of CResult_boolLightningErrorZ pub union CResult_boolLightningErrorZPtr { @@ -6909,243 +7155,17 @@ impl Clone for CResult_SignatureNoneZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_SignatureNoneZ_clone(orig: &CResult_SignatureNoneZ) -> CResult_SignatureNoneZ { Clone::clone(&orig) } #[repr(C)] -/// A tuple of 2 elements. See the individual fields for the types contained. -pub struct C2Tuple_SignatureSignatureZ { - /// The element at position 0 - pub a: crate::c_types::Signature, - /// The element at position 1 - pub b: crate::c_types::Signature, -} -impl From<(crate::c_types::Signature, crate::c_types::Signature)> for C2Tuple_SignatureSignatureZ { - fn from (tup: (crate::c_types::Signature, crate::c_types::Signature)) -> Self { - Self { - a: tup.0, - b: tup.1, - } - } -} -impl C2Tuple_SignatureSignatureZ { - #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::c_types::Signature, crate::c_types::Signature) { - (self.a, self.b) - } -} -impl Clone for C2Tuple_SignatureSignatureZ { - fn clone(&self) -> Self { - Self { - a: Clone::clone(&self.a), - b: Clone::clone(&self.b), - } - } -} -#[no_mangle] -/// Creates a new tuple which has the same data as `orig` -/// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn C2Tuple_SignatureSignatureZ_clone(orig: &C2Tuple_SignatureSignatureZ) -> C2Tuple_SignatureSignatureZ { Clone::clone(&orig) } -/// Creates a new C2Tuple_SignatureSignatureZ from the contained elements. -#[no_mangle] -pub extern "C" fn C2Tuple_SignatureSignatureZ_new(a: crate::c_types::Signature, b: crate::c_types::Signature) -> C2Tuple_SignatureSignatureZ { - C2Tuple_SignatureSignatureZ { a, b, } -} - -#[no_mangle] -/// Frees any resources used by the C2Tuple_SignatureSignatureZ. -pub extern "C" fn C2Tuple_SignatureSignatureZ_free(_res: C2Tuple_SignatureSignatureZ) { } -#[repr(C)] -/// The contents of CResult_C2Tuple_SignatureSignatureZNoneZ -pub union CResult_C2Tuple_SignatureSignatureZNoneZPtr { +/// The contents of CResult_PublicKeyNoneZ +pub union CResult_PublicKeyNoneZPtr { /// A pointer to the contents in the success state. /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::c_types::derived::C2Tuple_SignatureSignatureZ, + pub result: *mut crate::c_types::PublicKey, /// Note that this value is always NULL, as there are no contents in the Err variant pub err: *mut core::ffi::c_void, } #[repr(C)] -/// A CResult_C2Tuple_SignatureSignatureZNoneZ represents the result of a fallible operation, -/// containing a crate::c_types::derived::C2Tuple_SignatureSignatureZ on success and a () on failure. -/// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_C2Tuple_SignatureSignatureZNoneZ { - /// The contents of this CResult_C2Tuple_SignatureSignatureZNoneZ, accessible via either - /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_C2Tuple_SignatureSignatureZNoneZPtr, - /// Whether this CResult_C2Tuple_SignatureSignatureZNoneZ represents a success state. - pub result_ok: bool, -} -#[no_mangle] -/// Creates a new CResult_C2Tuple_SignatureSignatureZNoneZ in the success state. -pub extern "C" fn CResult_C2Tuple_SignatureSignatureZNoneZ_ok(o: crate::c_types::derived::C2Tuple_SignatureSignatureZ) -> CResult_C2Tuple_SignatureSignatureZNoneZ { - CResult_C2Tuple_SignatureSignatureZNoneZ { - contents: CResult_C2Tuple_SignatureSignatureZNoneZPtr { - result: Box::into_raw(Box::new(o)), - }, - result_ok: true, - } -} -#[no_mangle] -/// Creates a new CResult_C2Tuple_SignatureSignatureZNoneZ in the error state. -pub extern "C" fn CResult_C2Tuple_SignatureSignatureZNoneZ_err() -> CResult_C2Tuple_SignatureSignatureZNoneZ { - CResult_C2Tuple_SignatureSignatureZNoneZ { - contents: CResult_C2Tuple_SignatureSignatureZNoneZPtr { - err: core::ptr::null_mut(), - }, - result_ok: false, - } -} -/// Checks if the given object is currently in the success state -#[no_mangle] -pub extern "C" fn CResult_C2Tuple_SignatureSignatureZNoneZ_is_ok(o: &CResult_C2Tuple_SignatureSignatureZNoneZ) -> bool { - o.result_ok -} -#[no_mangle] -/// Frees any resources used by the CResult_C2Tuple_SignatureSignatureZNoneZ. -pub extern "C" fn CResult_C2Tuple_SignatureSignatureZNoneZ_free(_res: CResult_C2Tuple_SignatureSignatureZNoneZ) { } -impl Drop for CResult_C2Tuple_SignatureSignatureZNoneZ { - fn drop(&mut self) { - if self.result_ok { - if unsafe { !(self.contents.result as *mut ()).is_null() } { - let _ = unsafe { Box::from_raw(self.contents.result) }; - } - } else { - } - } -} -impl From> for CResult_C2Tuple_SignatureSignatureZNoneZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { - let contents = if o.result_ok { - let result = unsafe { o.contents.result }; - unsafe { o.contents.result = core::ptr::null_mut() }; - CResult_C2Tuple_SignatureSignatureZNoneZPtr { result } - } else { - let _ = unsafe { Box::from_raw(o.contents.err) }; - o.contents.err = core::ptr::null_mut(); - CResult_C2Tuple_SignatureSignatureZNoneZPtr { err: core::ptr::null_mut() } - }; - Self { - contents, - result_ok: o.result_ok, - } - } -} -impl Clone for CResult_C2Tuple_SignatureSignatureZNoneZ { - fn clone(&self) -> Self { - if self.result_ok { - Self { result_ok: true, contents: CResult_C2Tuple_SignatureSignatureZNoneZPtr { - result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) - } } - } else { - Self { result_ok: false, contents: CResult_C2Tuple_SignatureSignatureZNoneZPtr { - err: core::ptr::null_mut() - } } - } - } -} -#[no_mangle] -/// Creates a new CResult_C2Tuple_SignatureSignatureZNoneZ which has the same data as `orig` -/// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult_C2Tuple_SignatureSignatureZNoneZ_clone(orig: &CResult_C2Tuple_SignatureSignatureZNoneZ) -> CResult_C2Tuple_SignatureSignatureZNoneZ { Clone::clone(&orig) } -#[repr(C)] -/// The contents of CResult_SecretKeyNoneZ -pub union CResult_SecretKeyNoneZPtr { - /// A pointer to the contents in the success state. - /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::c_types::SecretKey, - /// Note that this value is always NULL, as there are no contents in the Err variant - pub err: *mut core::ffi::c_void, -} -#[repr(C)] -/// A CResult_SecretKeyNoneZ represents the result of a fallible operation, -/// containing a crate::c_types::SecretKey on success and a () on failure. -/// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_SecretKeyNoneZ { - /// The contents of this CResult_SecretKeyNoneZ, accessible via either - /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_SecretKeyNoneZPtr, - /// Whether this CResult_SecretKeyNoneZ represents a success state. - pub result_ok: bool, -} -#[no_mangle] -/// Creates a new CResult_SecretKeyNoneZ in the success state. -pub extern "C" fn CResult_SecretKeyNoneZ_ok(o: crate::c_types::SecretKey) -> CResult_SecretKeyNoneZ { - CResult_SecretKeyNoneZ { - contents: CResult_SecretKeyNoneZPtr { - result: Box::into_raw(Box::new(o)), - }, - result_ok: true, - } -} -#[no_mangle] -/// Creates a new CResult_SecretKeyNoneZ in the error state. -pub extern "C" fn CResult_SecretKeyNoneZ_err() -> CResult_SecretKeyNoneZ { - CResult_SecretKeyNoneZ { - contents: CResult_SecretKeyNoneZPtr { - err: core::ptr::null_mut(), - }, - result_ok: false, - } -} -/// Checks if the given object is currently in the success state -#[no_mangle] -pub extern "C" fn CResult_SecretKeyNoneZ_is_ok(o: &CResult_SecretKeyNoneZ) -> bool { - o.result_ok -} -#[no_mangle] -/// Frees any resources used by the CResult_SecretKeyNoneZ. -pub extern "C" fn CResult_SecretKeyNoneZ_free(_res: CResult_SecretKeyNoneZ) { } -impl Drop for CResult_SecretKeyNoneZ { - fn drop(&mut self) { - if self.result_ok { - if unsafe { !(self.contents.result as *mut ()).is_null() } { - let _ = unsafe { Box::from_raw(self.contents.result) }; - } - } else { - } - } -} -impl From> for CResult_SecretKeyNoneZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { - let contents = if o.result_ok { - let result = unsafe { o.contents.result }; - unsafe { o.contents.result = core::ptr::null_mut() }; - CResult_SecretKeyNoneZPtr { result } - } else { - let _ = unsafe { Box::from_raw(o.contents.err) }; - o.contents.err = core::ptr::null_mut(); - CResult_SecretKeyNoneZPtr { err: core::ptr::null_mut() } - }; - Self { - contents, - result_ok: o.result_ok, - } - } -} -impl Clone for CResult_SecretKeyNoneZ { - fn clone(&self) -> Self { - if self.result_ok { - Self { result_ok: true, contents: CResult_SecretKeyNoneZPtr { - result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) - } } - } else { - Self { result_ok: false, contents: CResult_SecretKeyNoneZPtr { - err: core::ptr::null_mut() - } } - } - } -} -#[no_mangle] -/// Creates a new CResult_SecretKeyNoneZ which has the same data as `orig` -/// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult_SecretKeyNoneZ_clone(orig: &CResult_SecretKeyNoneZ) -> CResult_SecretKeyNoneZ { Clone::clone(&orig) } -#[repr(C)] -/// The contents of CResult_PublicKeyNoneZ -pub union CResult_PublicKeyNoneZPtr { - /// A pointer to the contents in the success state. - /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::c_types::PublicKey, - /// Note that this value is always NULL, as there are no contents in the Err variant - pub err: *mut core::ffi::c_void, -} -#[repr(C)] -/// A CResult_PublicKeyNoneZ represents the result of a fallible operation, -/// containing a crate::c_types::PublicKey on success and a () on failure. +/// A CResult_PublicKeyNoneZ represents the result of a fallible operation, +/// containing a crate::c_types::PublicKey on success and a () on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. pub struct CResult_PublicKeyNoneZ { /// The contents of this CResult_PublicKeyNoneZ, accessible via either @@ -7351,85 +7371,6 @@ impl Clone for CResult_SharedSecretNoneZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_SharedSecretNoneZ_clone(orig: &CResult_SharedSecretNoneZ) -> CResult_SharedSecretNoneZ { Clone::clone(&orig) } #[repr(C)] -/// The contents of CResult_SignDecodeErrorZ -pub union CResult_SignDecodeErrorZPtr { - /// A pointer to the contents in the success state. - /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::lightning::chain::keysinterface::Sign, - /// A pointer to the contents in the error state. - /// Reading from this pointer when `result_ok` is set is undefined. - pub err: *mut crate::lightning::ln::msgs::DecodeError, -} -#[repr(C)] -/// A CResult_SignDecodeErrorZ represents the result of a fallible operation, -/// containing a crate::lightning::chain::keysinterface::Sign on success and a crate::lightning::ln::msgs::DecodeError on failure. -/// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_SignDecodeErrorZ { - /// The contents of this CResult_SignDecodeErrorZ, accessible via either - /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_SignDecodeErrorZPtr, - /// Whether this CResult_SignDecodeErrorZ represents a success state. - pub result_ok: bool, -} -#[no_mangle] -/// Creates a new CResult_SignDecodeErrorZ in the success state. -pub extern "C" fn CResult_SignDecodeErrorZ_ok(o: crate::lightning::chain::keysinterface::Sign) -> CResult_SignDecodeErrorZ { - CResult_SignDecodeErrorZ { - contents: CResult_SignDecodeErrorZPtr { - result: Box::into_raw(Box::new(o)), - }, - result_ok: true, - } -} -#[no_mangle] -/// Creates a new CResult_SignDecodeErrorZ in the error state. -pub extern "C" fn CResult_SignDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_SignDecodeErrorZ { - CResult_SignDecodeErrorZ { - contents: CResult_SignDecodeErrorZPtr { - err: Box::into_raw(Box::new(e)), - }, - result_ok: false, - } -} -/// Checks if the given object is currently in the success state -#[no_mangle] -pub extern "C" fn CResult_SignDecodeErrorZ_is_ok(o: &CResult_SignDecodeErrorZ) -> bool { - o.result_ok -} -#[no_mangle] -/// Frees any resources used by the CResult_SignDecodeErrorZ. -pub extern "C" fn CResult_SignDecodeErrorZ_free(_res: CResult_SignDecodeErrorZ) { } -impl Drop for CResult_SignDecodeErrorZ { - fn drop(&mut self) { - if self.result_ok { - if unsafe { !(self.contents.result as *mut ()).is_null() } { - let _ = unsafe { Box::from_raw(self.contents.result) }; - } - } else { - if unsafe { !(self.contents.err as *mut ()).is_null() } { - let _ = unsafe { Box::from_raw(self.contents.err) }; - } - } - } -} -impl From> for CResult_SignDecodeErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { - let contents = if o.result_ok { - let result = unsafe { o.contents.result }; - unsafe { o.contents.result = core::ptr::null_mut() }; - CResult_SignDecodeErrorZPtr { result } - } else { - let err = unsafe { o.contents.err }; - unsafe { o.contents.err = core::ptr::null_mut(); } - CResult_SignDecodeErrorZPtr { err } - }; - Self { - contents, - result_ok: o.result_ok, - } - } -} -#[repr(C)] /// A dynamically-allocated array of crate::c_types::U5s of arbitrary size. /// This corresponds to std::vector in C++ pub struct CVec_U5Z { @@ -7568,6 +7509,85 @@ impl Clone for CResult_RecoverableSignatureNoneZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_RecoverableSignatureNoneZ_clone(orig: &CResult_RecoverableSignatureNoneZ) -> CResult_RecoverableSignatureNoneZ { Clone::clone(&orig) } #[repr(C)] +/// The contents of CResult_WriteableEcdsaChannelSignerDecodeErrorZ +pub union CResult_WriteableEcdsaChannelSignerDecodeErrorZPtr { + /// A pointer to the contents in the success state. + /// Reading from this pointer when `result_ok` is not set is undefined. + pub result: *mut crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner, + /// A pointer to the contents in the error state. + /// Reading from this pointer when `result_ok` is set is undefined. + pub err: *mut crate::lightning::ln::msgs::DecodeError, +} +#[repr(C)] +/// A CResult_WriteableEcdsaChannelSignerDecodeErrorZ represents the result of a fallible operation, +/// containing a crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner on success and a crate::lightning::ln::msgs::DecodeError on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_WriteableEcdsaChannelSignerDecodeErrorZ { + /// The contents of this CResult_WriteableEcdsaChannelSignerDecodeErrorZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_WriteableEcdsaChannelSignerDecodeErrorZPtr, + /// Whether this CResult_WriteableEcdsaChannelSignerDecodeErrorZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_WriteableEcdsaChannelSignerDecodeErrorZ in the success state. +pub extern "C" fn CResult_WriteableEcdsaChannelSignerDecodeErrorZ_ok(o: crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner) -> CResult_WriteableEcdsaChannelSignerDecodeErrorZ { + CResult_WriteableEcdsaChannelSignerDecodeErrorZ { + contents: CResult_WriteableEcdsaChannelSignerDecodeErrorZPtr { + result: Box::into_raw(Box::new(o)), + }, + result_ok: true, + } +} +#[no_mangle] +/// Creates a new CResult_WriteableEcdsaChannelSignerDecodeErrorZ in the error state. +pub extern "C" fn CResult_WriteableEcdsaChannelSignerDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_WriteableEcdsaChannelSignerDecodeErrorZ { + CResult_WriteableEcdsaChannelSignerDecodeErrorZ { + contents: CResult_WriteableEcdsaChannelSignerDecodeErrorZPtr { + err: Box::into_raw(Box::new(e)), + }, + result_ok: false, + } +} +/// Checks if the given object is currently in the success state +#[no_mangle] +pub extern "C" fn CResult_WriteableEcdsaChannelSignerDecodeErrorZ_is_ok(o: &CResult_WriteableEcdsaChannelSignerDecodeErrorZ) -> bool { + o.result_ok +} +#[no_mangle] +/// Frees any resources used by the CResult_WriteableEcdsaChannelSignerDecodeErrorZ. +pub extern "C" fn CResult_WriteableEcdsaChannelSignerDecodeErrorZ_free(_res: CResult_WriteableEcdsaChannelSignerDecodeErrorZ) { } +impl Drop for CResult_WriteableEcdsaChannelSignerDecodeErrorZ { + fn drop(&mut self) { + if self.result_ok { + if unsafe { !(self.contents.result as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.result) }; + } + } else { + if unsafe { !(self.contents.err as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.err) }; + } + } + } +} +impl From> for CResult_WriteableEcdsaChannelSignerDecodeErrorZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { + let contents = if o.result_ok { + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = core::ptr::null_mut() }; + CResult_WriteableEcdsaChannelSignerDecodeErrorZPtr { result } + } else { + let err = unsafe { o.contents.err }; + unsafe { o.contents.err = core::ptr::null_mut(); } + CResult_WriteableEcdsaChannelSignerDecodeErrorZPtr { err } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +#[repr(C)] /// A dynamically-allocated array of u8s of arbitrary size. /// This corresponds to std::vector in C++ pub struct CVec_u8Z { @@ -8170,40 +8190,41 @@ pub extern "C" fn COption_u16Z_free(_res: COption_u16Z) { } /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn COption_u16Z_clone(orig: &COption_u16Z) -> COption_u16Z { Clone::clone(&orig) } #[repr(C)] -/// The contents of CResult_NoneAPIErrorZ -pub union CResult_NoneAPIErrorZPtr { - /// Note that this value is always NULL, as there are no contents in the OK variant - pub result: *mut core::ffi::c_void, +/// The contents of CResult__u832APIErrorZ +pub union CResult__u832APIErrorZPtr { + /// A pointer to the contents in the success state. + /// Reading from this pointer when `result_ok` is not set is undefined. + pub result: *mut crate::c_types::ThirtyTwoBytes, /// A pointer to the contents in the error state. /// Reading from this pointer when `result_ok` is set is undefined. pub err: *mut crate::lightning::util::errors::APIError, } #[repr(C)] -/// A CResult_NoneAPIErrorZ represents the result of a fallible operation, -/// containing a () on success and a crate::lightning::util::errors::APIError on failure. +/// A CResult__u832APIErrorZ represents the result of a fallible operation, +/// containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::util::errors::APIError on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_NoneAPIErrorZ { - /// The contents of this CResult_NoneAPIErrorZ, accessible via either +pub struct CResult__u832APIErrorZ { + /// The contents of this CResult__u832APIErrorZ, accessible via either /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_NoneAPIErrorZPtr, - /// Whether this CResult_NoneAPIErrorZ represents a success state. + pub contents: CResult__u832APIErrorZPtr, + /// Whether this CResult__u832APIErrorZ represents a success state. pub result_ok: bool, } #[no_mangle] -/// Creates a new CResult_NoneAPIErrorZ in the success state. -pub extern "C" fn CResult_NoneAPIErrorZ_ok() -> CResult_NoneAPIErrorZ { - CResult_NoneAPIErrorZ { - contents: CResult_NoneAPIErrorZPtr { - result: core::ptr::null_mut(), +/// Creates a new CResult__u832APIErrorZ in the success state. +pub extern "C" fn CResult__u832APIErrorZ_ok(o: crate::c_types::ThirtyTwoBytes) -> CResult__u832APIErrorZ { + CResult__u832APIErrorZ { + contents: CResult__u832APIErrorZPtr { + result: Box::into_raw(Box::new(o)), }, result_ok: true, } } #[no_mangle] -/// Creates a new CResult_NoneAPIErrorZ in the error state. -pub extern "C" fn CResult_NoneAPIErrorZ_err(e: crate::lightning::util::errors::APIError) -> CResult_NoneAPIErrorZ { - CResult_NoneAPIErrorZ { - contents: CResult_NoneAPIErrorZPtr { +/// Creates a new CResult__u832APIErrorZ in the error state. +pub extern "C" fn CResult__u832APIErrorZ_err(e: crate::lightning::util::errors::APIError) -> CResult__u832APIErrorZ { + CResult__u832APIErrorZ { + contents: CResult__u832APIErrorZPtr { err: Box::into_raw(Box::new(e)), }, result_ok: false, @@ -8211,15 +8232,18 @@ pub extern "C" fn CResult_NoneAPIErrorZ_err(e: crate::lightning::util::errors::A } /// Checks if the given object is currently in the success state #[no_mangle] -pub extern "C" fn CResult_NoneAPIErrorZ_is_ok(o: &CResult_NoneAPIErrorZ) -> bool { +pub extern "C" fn CResult__u832APIErrorZ_is_ok(o: &CResult__u832APIErrorZ) -> bool { o.result_ok } #[no_mangle] -/// Frees any resources used by the CResult_NoneAPIErrorZ. -pub extern "C" fn CResult_NoneAPIErrorZ_free(_res: CResult_NoneAPIErrorZ) { } -impl Drop for CResult_NoneAPIErrorZ { +/// Frees any resources used by the CResult__u832APIErrorZ. +pub extern "C" fn CResult__u832APIErrorZ_free(_res: CResult__u832APIErrorZ) { } +impl Drop for CResult__u832APIErrorZ { fn drop(&mut self) { if self.result_ok { + if unsafe { !(self.contents.result as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.result) }; + } } else { if unsafe { !(self.contents.err as *mut ()).is_null() } { let _ = unsafe { Box::from_raw(self.contents.err) }; @@ -8227,16 +8251,16 @@ impl Drop for CResult_NoneAPIErrorZ { } } } -impl From> for CResult_NoneAPIErrorZ { - fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::util::errors::APIError>) -> Self { +impl From> for CResult__u832APIErrorZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { - let _ = unsafe { Box::from_raw(o.contents.result) }; - o.contents.result = core::ptr::null_mut(); - CResult_NoneAPIErrorZPtr { result: core::ptr::null_mut() } + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = core::ptr::null_mut() }; + CResult__u832APIErrorZPtr { result } } else { let err = unsafe { o.contents.err }; unsafe { o.contents.err = core::ptr::null_mut(); } - CResult_NoneAPIErrorZPtr { err } + CResult__u832APIErrorZPtr { err } }; Self { contents, @@ -8244,47 +8268,47 @@ impl From Self { if self.result_ok { - Self { result_ok: true, contents: CResult_NoneAPIErrorZPtr { - result: core::ptr::null_mut() + Self { result_ok: true, contents: CResult__u832APIErrorZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) } } } else { - Self { result_ok: false, contents: CResult_NoneAPIErrorZPtr { + Self { result_ok: false, contents: CResult__u832APIErrorZPtr { err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) } } } } } #[no_mangle] -/// Creates a new CResult_NoneAPIErrorZ which has the same data as `orig` +/// Creates a new CResult__u832APIErrorZ which has the same data as `orig` /// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult_NoneAPIErrorZ_clone(orig: &CResult_NoneAPIErrorZ) -> CResult_NoneAPIErrorZ { Clone::clone(&orig) } +pub extern "C" fn CResult__u832APIErrorZ_clone(orig: &CResult__u832APIErrorZ) -> CResult__u832APIErrorZ { Clone::clone(&orig) } #[repr(C)] -/// A dynamically-allocated array of crate::c_types::derived::CResult_NoneAPIErrorZs of arbitrary size. +/// A dynamically-allocated array of crate::lightning::ln::channelmanager::RecentPaymentDetailss of arbitrary size. /// This corresponds to std::vector in C++ -pub struct CVec_CResult_NoneAPIErrorZZ { +pub struct CVec_RecentPaymentDetailsZ { /// The elements in the array. /// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). - pub data: *mut crate::c_types::derived::CResult_NoneAPIErrorZ, + pub data: *mut crate::lightning::ln::channelmanager::RecentPaymentDetails, /// The number of elements pointed to by `data`. pub datalen: usize } -impl CVec_CResult_NoneAPIErrorZZ { - #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { +impl CVec_RecentPaymentDetailsZ { + #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { if self.datalen == 0 { return Vec::new(); } let ret = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }.into(); self.data = core::ptr::null_mut(); self.datalen = 0; ret } - #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::CResult_NoneAPIErrorZ] { + #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::lightning::ln::channelmanager::RecentPaymentDetails] { unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) } } } -impl From> for CVec_CResult_NoneAPIErrorZZ { - fn from(v: Vec) -> Self { +impl From> for CVec_RecentPaymentDetailsZ { + fn from(v: Vec) -> Self { let datalen = v.len(); let data = Box::into_raw(v.into_boxed_slice()); Self { datalen, data: unsafe { (*data).as_mut_ptr() } } @@ -8292,103 +8316,140 @@ impl From> for CVec_CResult_ } #[no_mangle] /// Frees the buffer pointed to by `data` if `datalen` is non-0. -pub extern "C" fn CVec_CResult_NoneAPIErrorZZ_free(_res: CVec_CResult_NoneAPIErrorZZ) { } -impl Drop for CVec_CResult_NoneAPIErrorZZ { +pub extern "C" fn CVec_RecentPaymentDetailsZ_free(_res: CVec_RecentPaymentDetailsZ) { } +impl Drop for CVec_RecentPaymentDetailsZ { fn drop(&mut self) { if self.datalen == 0 { return; } let _ = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }; } } -impl Clone for CVec_CResult_NoneAPIErrorZZ { - fn clone(&self) -> Self { - let mut res = Vec::new(); - if self.datalen == 0 { return Self::from(res); } - res.extend_from_slice(unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) }); - Self::from(res) - } +#[repr(C)] +/// The contents of CResult_NonePaymentSendFailureZ +pub union CResult_NonePaymentSendFailureZPtr { + /// Note that this value is always NULL, as there are no contents in the OK variant + pub result: *mut core::ffi::c_void, + /// A pointer to the contents in the error state. + /// Reading from this pointer when `result_ok` is set is undefined. + pub err: *mut crate::lightning::ln::outbound_payment::PaymentSendFailure, } #[repr(C)] -/// A dynamically-allocated array of crate::lightning::util::errors::APIErrors of arbitrary size. -/// This corresponds to std::vector in C++ -pub struct CVec_APIErrorZ { - /// The elements in the array. - /// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). - pub data: *mut crate::lightning::util::errors::APIError, - /// The number of elements pointed to by `data`. - pub datalen: usize +/// A CResult_NonePaymentSendFailureZ represents the result of a fallible operation, +/// containing a () on success and a crate::lightning::ln::outbound_payment::PaymentSendFailure on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_NonePaymentSendFailureZ { + /// The contents of this CResult_NonePaymentSendFailureZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_NonePaymentSendFailureZPtr, + /// Whether this CResult_NonePaymentSendFailureZ represents a success state. + pub result_ok: bool, } -impl CVec_APIErrorZ { - #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { - if self.datalen == 0 { return Vec::new(); } - let ret = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }.into(); - self.data = core::ptr::null_mut(); - self.datalen = 0; - ret - } - #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::lightning::util::errors::APIError] { - unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) } +#[no_mangle] +/// Creates a new CResult_NonePaymentSendFailureZ in the success state. +pub extern "C" fn CResult_NonePaymentSendFailureZ_ok() -> CResult_NonePaymentSendFailureZ { + CResult_NonePaymentSendFailureZ { + contents: CResult_NonePaymentSendFailureZPtr { + result: core::ptr::null_mut(), + }, + result_ok: true, } } -impl From> for CVec_APIErrorZ { - fn from(v: Vec) -> Self { - let datalen = v.len(); - let data = Box::into_raw(v.into_boxed_slice()); - Self { datalen, data: unsafe { (*data).as_mut_ptr() } } +#[no_mangle] +/// Creates a new CResult_NonePaymentSendFailureZ in the error state. +pub extern "C" fn CResult_NonePaymentSendFailureZ_err(e: crate::lightning::ln::outbound_payment::PaymentSendFailure) -> CResult_NonePaymentSendFailureZ { + CResult_NonePaymentSendFailureZ { + contents: CResult_NonePaymentSendFailureZPtr { + err: Box::into_raw(Box::new(e)), + }, + result_ok: false, } } +/// Checks if the given object is currently in the success state #[no_mangle] -/// Frees the buffer pointed to by `data` if `datalen` is non-0. -pub extern "C" fn CVec_APIErrorZ_free(_res: CVec_APIErrorZ) { } -impl Drop for CVec_APIErrorZ { +pub extern "C" fn CResult_NonePaymentSendFailureZ_is_ok(o: &CResult_NonePaymentSendFailureZ) -> bool { + o.result_ok +} +#[no_mangle] +/// Frees any resources used by the CResult_NonePaymentSendFailureZ. +pub extern "C" fn CResult_NonePaymentSendFailureZ_free(_res: CResult_NonePaymentSendFailureZ) { } +impl Drop for CResult_NonePaymentSendFailureZ { fn drop(&mut self) { - if self.datalen == 0 { return; } - let _ = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }; + if self.result_ok { + } else { + if unsafe { !(self.contents.err as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.err) }; + } + } } } -impl Clone for CVec_APIErrorZ { +impl From> for CResult_NonePaymentSendFailureZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::ln::outbound_payment::PaymentSendFailure>) -> Self { + let contents = if o.result_ok { + let _ = unsafe { Box::from_raw(o.contents.result) }; + o.contents.result = core::ptr::null_mut(); + CResult_NonePaymentSendFailureZPtr { result: core::ptr::null_mut() } + } else { + let err = unsafe { o.contents.err }; + unsafe { o.contents.err = core::ptr::null_mut(); } + CResult_NonePaymentSendFailureZPtr { err } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_NonePaymentSendFailureZ { fn clone(&self) -> Self { - let mut res = Vec::new(); - if self.datalen == 0 { return Self::from(res); } - res.extend_from_slice(unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) }); - Self::from(res) + if self.result_ok { + Self { result_ok: true, contents: CResult_NonePaymentSendFailureZPtr { + result: core::ptr::null_mut() + } } + } else { + Self { result_ok: false, contents: CResult_NonePaymentSendFailureZPtr { + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + } } + } } } +#[no_mangle] +/// Creates a new CResult_NonePaymentSendFailureZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_NonePaymentSendFailureZ_clone(orig: &CResult_NonePaymentSendFailureZ) -> CResult_NonePaymentSendFailureZ { Clone::clone(&orig) } #[repr(C)] -/// The contents of CResult__u832APIErrorZ -pub union CResult__u832APIErrorZPtr { - /// A pointer to the contents in the success state. - /// Reading from this pointer when `result_ok` is not set is undefined. - pub result: *mut crate::c_types::ThirtyTwoBytes, +/// The contents of CResult_NoneRetryableSendFailureZ +pub union CResult_NoneRetryableSendFailureZPtr { + /// Note that this value is always NULL, as there are no contents in the OK variant + pub result: *mut core::ffi::c_void, /// A pointer to the contents in the error state. /// Reading from this pointer when `result_ok` is set is undefined. - pub err: *mut crate::lightning::util::errors::APIError, + pub err: *mut crate::lightning::ln::outbound_payment::RetryableSendFailure, } #[repr(C)] -/// A CResult__u832APIErrorZ represents the result of a fallible operation, -/// containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::util::errors::APIError on failure. +/// A CResult_NoneRetryableSendFailureZ represents the result of a fallible operation, +/// containing a () on success and a crate::lightning::ln::outbound_payment::RetryableSendFailure on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult__u832APIErrorZ { - /// The contents of this CResult__u832APIErrorZ, accessible via either +pub struct CResult_NoneRetryableSendFailureZ { + /// The contents of this CResult_NoneRetryableSendFailureZ, accessible via either /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult__u832APIErrorZPtr, - /// Whether this CResult__u832APIErrorZ represents a success state. + pub contents: CResult_NoneRetryableSendFailureZPtr, + /// Whether this CResult_NoneRetryableSendFailureZ represents a success state. pub result_ok: bool, } #[no_mangle] -/// Creates a new CResult__u832APIErrorZ in the success state. -pub extern "C" fn CResult__u832APIErrorZ_ok(o: crate::c_types::ThirtyTwoBytes) -> CResult__u832APIErrorZ { - CResult__u832APIErrorZ { - contents: CResult__u832APIErrorZPtr { - result: Box::into_raw(Box::new(o)), +/// Creates a new CResult_NoneRetryableSendFailureZ in the success state. +pub extern "C" fn CResult_NoneRetryableSendFailureZ_ok() -> CResult_NoneRetryableSendFailureZ { + CResult_NoneRetryableSendFailureZ { + contents: CResult_NoneRetryableSendFailureZPtr { + result: core::ptr::null_mut(), }, result_ok: true, } } #[no_mangle] -/// Creates a new CResult__u832APIErrorZ in the error state. -pub extern "C" fn CResult__u832APIErrorZ_err(e: crate::lightning::util::errors::APIError) -> CResult__u832APIErrorZ { - CResult__u832APIErrorZ { - contents: CResult__u832APIErrorZPtr { +/// Creates a new CResult_NoneRetryableSendFailureZ in the error state. +pub extern "C" fn CResult_NoneRetryableSendFailureZ_err(e: crate::lightning::ln::outbound_payment::RetryableSendFailure) -> CResult_NoneRetryableSendFailureZ { + CResult_NoneRetryableSendFailureZ { + contents: CResult_NoneRetryableSendFailureZPtr { err: Box::into_raw(Box::new(e)), }, result_ok: false, @@ -8396,18 +8457,15 @@ pub extern "C" fn CResult__u832APIErrorZ_err(e: crate::lightning::util::errors:: } /// Checks if the given object is currently in the success state #[no_mangle] -pub extern "C" fn CResult__u832APIErrorZ_is_ok(o: &CResult__u832APIErrorZ) -> bool { +pub extern "C" fn CResult_NoneRetryableSendFailureZ_is_ok(o: &CResult_NoneRetryableSendFailureZ) -> bool { o.result_ok } #[no_mangle] -/// Frees any resources used by the CResult__u832APIErrorZ. -pub extern "C" fn CResult__u832APIErrorZ_free(_res: CResult__u832APIErrorZ) { } -impl Drop for CResult__u832APIErrorZ { +/// Frees any resources used by the CResult_NoneRetryableSendFailureZ. +pub extern "C" fn CResult_NoneRetryableSendFailureZ_free(_res: CResult_NoneRetryableSendFailureZ) { } +impl Drop for CResult_NoneRetryableSendFailureZ { fn drop(&mut self) { if self.result_ok { - if unsafe { !(self.contents.result as *mut ()).is_null() } { - let _ = unsafe { Box::from_raw(self.contents.result) }; - } } else { if unsafe { !(self.contents.err as *mut ()).is_null() } { let _ = unsafe { Box::from_raw(self.contents.err) }; @@ -8415,16 +8473,16 @@ impl Drop for CResult__u832APIErrorZ { } } } -impl From> for CResult__u832APIErrorZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_NoneRetryableSendFailureZ { + fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::ln::outbound_payment::RetryableSendFailure>) -> Self { let contents = if o.result_ok { - let result = unsafe { o.contents.result }; - unsafe { o.contents.result = core::ptr::null_mut() }; - CResult__u832APIErrorZPtr { result } + let _ = unsafe { Box::from_raw(o.contents.result) }; + o.contents.result = core::ptr::null_mut(); + CResult_NoneRetryableSendFailureZPtr { result: core::ptr::null_mut() } } else { let err = unsafe { o.contents.err }; unsafe { o.contents.err = core::ptr::null_mut(); } - CResult__u832APIErrorZPtr { err } + CResult_NoneRetryableSendFailureZPtr { err } }; Self { contents, @@ -8432,58 +8490,59 @@ impl From Self { if self.result_ok { - Self { result_ok: true, contents: CResult__u832APIErrorZPtr { - result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + Self { result_ok: true, contents: CResult_NoneRetryableSendFailureZPtr { + result: core::ptr::null_mut() } } } else { - Self { result_ok: false, contents: CResult__u832APIErrorZPtr { - err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + Self { result_ok: false, contents: CResult_NoneRetryableSendFailureZPtr { + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) } } } } } #[no_mangle] -/// Creates a new CResult__u832APIErrorZ which has the same data as `orig` +/// Creates a new CResult_NoneRetryableSendFailureZ which has the same data as `orig` /// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult__u832APIErrorZ_clone(orig: &CResult__u832APIErrorZ) -> CResult__u832APIErrorZ { Clone::clone(&orig) } +pub extern "C" fn CResult_NoneRetryableSendFailureZ_clone(orig: &CResult_NoneRetryableSendFailureZ) -> CResult_NoneRetryableSendFailureZ { Clone::clone(&orig) } #[repr(C)] -/// The contents of CResult_NonePaymentSendFailureZ -pub union CResult_NonePaymentSendFailureZPtr { - /// Note that this value is always NULL, as there are no contents in the OK variant - pub result: *mut core::ffi::c_void, +/// The contents of CResult_PaymentHashPaymentSendFailureZ +pub union CResult_PaymentHashPaymentSendFailureZPtr { + /// A pointer to the contents in the success state. + /// Reading from this pointer when `result_ok` is not set is undefined. + pub result: *mut crate::c_types::ThirtyTwoBytes, /// A pointer to the contents in the error state. /// Reading from this pointer when `result_ok` is set is undefined. - pub err: *mut crate::lightning::ln::channelmanager::PaymentSendFailure, + pub err: *mut crate::lightning::ln::outbound_payment::PaymentSendFailure, } #[repr(C)] -/// A CResult_NonePaymentSendFailureZ represents the result of a fallible operation, -/// containing a () on success and a crate::lightning::ln::channelmanager::PaymentSendFailure on failure. +/// A CResult_PaymentHashPaymentSendFailureZ represents the result of a fallible operation, +/// containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::ln::outbound_payment::PaymentSendFailure on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_NonePaymentSendFailureZ { - /// The contents of this CResult_NonePaymentSendFailureZ, accessible via either +pub struct CResult_PaymentHashPaymentSendFailureZ { + /// The contents of this CResult_PaymentHashPaymentSendFailureZ, accessible via either /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_NonePaymentSendFailureZPtr, - /// Whether this CResult_NonePaymentSendFailureZ represents a success state. + pub contents: CResult_PaymentHashPaymentSendFailureZPtr, + /// Whether this CResult_PaymentHashPaymentSendFailureZ represents a success state. pub result_ok: bool, } #[no_mangle] -/// Creates a new CResult_NonePaymentSendFailureZ in the success state. -pub extern "C" fn CResult_NonePaymentSendFailureZ_ok() -> CResult_NonePaymentSendFailureZ { - CResult_NonePaymentSendFailureZ { - contents: CResult_NonePaymentSendFailureZPtr { - result: core::ptr::null_mut(), +/// Creates a new CResult_PaymentHashPaymentSendFailureZ in the success state. +pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_ok(o: crate::c_types::ThirtyTwoBytes) -> CResult_PaymentHashPaymentSendFailureZ { + CResult_PaymentHashPaymentSendFailureZ { + contents: CResult_PaymentHashPaymentSendFailureZPtr { + result: Box::into_raw(Box::new(o)), }, result_ok: true, } } #[no_mangle] -/// Creates a new CResult_NonePaymentSendFailureZ in the error state. -pub extern "C" fn CResult_NonePaymentSendFailureZ_err(e: crate::lightning::ln::channelmanager::PaymentSendFailure) -> CResult_NonePaymentSendFailureZ { - CResult_NonePaymentSendFailureZ { - contents: CResult_NonePaymentSendFailureZPtr { +/// Creates a new CResult_PaymentHashPaymentSendFailureZ in the error state. +pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_err(e: crate::lightning::ln::outbound_payment::PaymentSendFailure) -> CResult_PaymentHashPaymentSendFailureZ { + CResult_PaymentHashPaymentSendFailureZ { + contents: CResult_PaymentHashPaymentSendFailureZPtr { err: Box::into_raw(Box::new(e)), }, result_ok: false, @@ -8491,15 +8550,18 @@ pub extern "C" fn CResult_NonePaymentSendFailureZ_err(e: crate::lightning::ln::c } /// Checks if the given object is currently in the success state #[no_mangle] -pub extern "C" fn CResult_NonePaymentSendFailureZ_is_ok(o: &CResult_NonePaymentSendFailureZ) -> bool { +pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_is_ok(o: &CResult_PaymentHashPaymentSendFailureZ) -> bool { o.result_ok } #[no_mangle] -/// Frees any resources used by the CResult_NonePaymentSendFailureZ. -pub extern "C" fn CResult_NonePaymentSendFailureZ_free(_res: CResult_NonePaymentSendFailureZ) { } -impl Drop for CResult_NonePaymentSendFailureZ { +/// Frees any resources used by the CResult_PaymentHashPaymentSendFailureZ. +pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_free(_res: CResult_PaymentHashPaymentSendFailureZ) { } +impl Drop for CResult_PaymentHashPaymentSendFailureZ { fn drop(&mut self) { if self.result_ok { + if unsafe { !(self.contents.result as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.result) }; + } } else { if unsafe { !(self.contents.err as *mut ()).is_null() } { let _ = unsafe { Box::from_raw(self.contents.err) }; @@ -8507,16 +8569,16 @@ impl Drop for CResult_NonePaymentSendFailureZ { } } } -impl From> for CResult_NonePaymentSendFailureZ { - fn from(mut o: crate::c_types::CResultTempl<(), crate::lightning::ln::channelmanager::PaymentSendFailure>) -> Self { +impl From> for CResult_PaymentHashPaymentSendFailureZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { - let _ = unsafe { Box::from_raw(o.contents.result) }; - o.contents.result = core::ptr::null_mut(); - CResult_NonePaymentSendFailureZPtr { result: core::ptr::null_mut() } + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = core::ptr::null_mut() }; + CResult_PaymentHashPaymentSendFailureZPtr { result } } else { let err = unsafe { o.contents.err }; unsafe { o.contents.err = core::ptr::null_mut(); } - CResult_NonePaymentSendFailureZPtr { err } + CResult_PaymentHashPaymentSendFailureZPtr { err } }; Self { contents, @@ -8524,59 +8586,59 @@ impl From Self { if self.result_ok { - Self { result_ok: true, contents: CResult_NonePaymentSendFailureZPtr { - result: core::ptr::null_mut() + Self { result_ok: true, contents: CResult_PaymentHashPaymentSendFailureZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) } } } else { - Self { result_ok: false, contents: CResult_NonePaymentSendFailureZPtr { - err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + Self { result_ok: false, contents: CResult_PaymentHashPaymentSendFailureZPtr { + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) } } } } } #[no_mangle] -/// Creates a new CResult_NonePaymentSendFailureZ which has the same data as `orig` +/// Creates a new CResult_PaymentHashPaymentSendFailureZ which has the same data as `orig` /// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult_NonePaymentSendFailureZ_clone(orig: &CResult_NonePaymentSendFailureZ) -> CResult_NonePaymentSendFailureZ { Clone::clone(&orig) } +pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_clone(orig: &CResult_PaymentHashPaymentSendFailureZ) -> CResult_PaymentHashPaymentSendFailureZ { Clone::clone(&orig) } #[repr(C)] -/// The contents of CResult_PaymentHashPaymentSendFailureZ -pub union CResult_PaymentHashPaymentSendFailureZPtr { +/// The contents of CResult_PaymentHashRetryableSendFailureZ +pub union CResult_PaymentHashRetryableSendFailureZPtr { /// A pointer to the contents in the success state. /// Reading from this pointer when `result_ok` is not set is undefined. pub result: *mut crate::c_types::ThirtyTwoBytes, /// A pointer to the contents in the error state. /// Reading from this pointer when `result_ok` is set is undefined. - pub err: *mut crate::lightning::ln::channelmanager::PaymentSendFailure, + pub err: *mut crate::lightning::ln::outbound_payment::RetryableSendFailure, } #[repr(C)] -/// A CResult_PaymentHashPaymentSendFailureZ represents the result of a fallible operation, -/// containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::ln::channelmanager::PaymentSendFailure on failure. +/// A CResult_PaymentHashRetryableSendFailureZ represents the result of a fallible operation, +/// containing a crate::c_types::ThirtyTwoBytes on success and a crate::lightning::ln::outbound_payment::RetryableSendFailure on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. -pub struct CResult_PaymentHashPaymentSendFailureZ { - /// The contents of this CResult_PaymentHashPaymentSendFailureZ, accessible via either +pub struct CResult_PaymentHashRetryableSendFailureZ { + /// The contents of this CResult_PaymentHashRetryableSendFailureZ, accessible via either /// `err` or `result` depending on the state of `result_ok`. - pub contents: CResult_PaymentHashPaymentSendFailureZPtr, - /// Whether this CResult_PaymentHashPaymentSendFailureZ represents a success state. + pub contents: CResult_PaymentHashRetryableSendFailureZPtr, + /// Whether this CResult_PaymentHashRetryableSendFailureZ represents a success state. pub result_ok: bool, } #[no_mangle] -/// Creates a new CResult_PaymentHashPaymentSendFailureZ in the success state. -pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_ok(o: crate::c_types::ThirtyTwoBytes) -> CResult_PaymentHashPaymentSendFailureZ { - CResult_PaymentHashPaymentSendFailureZ { - contents: CResult_PaymentHashPaymentSendFailureZPtr { +/// Creates a new CResult_PaymentHashRetryableSendFailureZ in the success state. +pub extern "C" fn CResult_PaymentHashRetryableSendFailureZ_ok(o: crate::c_types::ThirtyTwoBytes) -> CResult_PaymentHashRetryableSendFailureZ { + CResult_PaymentHashRetryableSendFailureZ { + contents: CResult_PaymentHashRetryableSendFailureZPtr { result: Box::into_raw(Box::new(o)), }, result_ok: true, } } #[no_mangle] -/// Creates a new CResult_PaymentHashPaymentSendFailureZ in the error state. -pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_err(e: crate::lightning::ln::channelmanager::PaymentSendFailure) -> CResult_PaymentHashPaymentSendFailureZ { - CResult_PaymentHashPaymentSendFailureZ { - contents: CResult_PaymentHashPaymentSendFailureZPtr { +/// Creates a new CResult_PaymentHashRetryableSendFailureZ in the error state. +pub extern "C" fn CResult_PaymentHashRetryableSendFailureZ_err(e: crate::lightning::ln::outbound_payment::RetryableSendFailure) -> CResult_PaymentHashRetryableSendFailureZ { + CResult_PaymentHashRetryableSendFailureZ { + contents: CResult_PaymentHashRetryableSendFailureZPtr { err: Box::into_raw(Box::new(e)), }, result_ok: false, @@ -8584,13 +8646,13 @@ pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_err(e: crate::lightning } /// Checks if the given object is currently in the success state #[no_mangle] -pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_is_ok(o: &CResult_PaymentHashPaymentSendFailureZ) -> bool { +pub extern "C" fn CResult_PaymentHashRetryableSendFailureZ_is_ok(o: &CResult_PaymentHashRetryableSendFailureZ) -> bool { o.result_ok } #[no_mangle] -/// Frees any resources used by the CResult_PaymentHashPaymentSendFailureZ. -pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_free(_res: CResult_PaymentHashPaymentSendFailureZ) { } -impl Drop for CResult_PaymentHashPaymentSendFailureZ { +/// Frees any resources used by the CResult_PaymentHashRetryableSendFailureZ. +pub extern "C" fn CResult_PaymentHashRetryableSendFailureZ_free(_res: CResult_PaymentHashRetryableSendFailureZ) { } +impl Drop for CResult_PaymentHashRetryableSendFailureZ { fn drop(&mut self) { if self.result_ok { if unsafe { !(self.contents.result as *mut ()).is_null() } { @@ -8603,16 +8665,16 @@ impl Drop for CResult_PaymentHashPaymentSendFailureZ { } } } -impl From> for CResult_PaymentHashPaymentSendFailureZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_PaymentHashRetryableSendFailureZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = core::ptr::null_mut() }; - CResult_PaymentHashPaymentSendFailureZPtr { result } + CResult_PaymentHashRetryableSendFailureZPtr { result } } else { let err = unsafe { o.contents.err }; unsafe { o.contents.err = core::ptr::null_mut(); } - CResult_PaymentHashPaymentSendFailureZPtr { err } + CResult_PaymentHashRetryableSendFailureZPtr { err } }; Self { contents, @@ -8620,23 +8682,23 @@ impl From Self { if self.result_ok { - Self { result_ok: true, contents: CResult_PaymentHashPaymentSendFailureZPtr { + Self { result_ok: true, contents: CResult_PaymentHashRetryableSendFailureZPtr { result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) } } } else { - Self { result_ok: false, contents: CResult_PaymentHashPaymentSendFailureZPtr { - err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + Self { result_ok: false, contents: CResult_PaymentHashRetryableSendFailureZPtr { + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) } } } } } #[no_mangle] -/// Creates a new CResult_PaymentHashPaymentSendFailureZ which has the same data as `orig` +/// Creates a new CResult_PaymentHashRetryableSendFailureZ which has the same data as `orig` /// but with all dynamically-allocated buffers duplicated in new buffers. -pub extern "C" fn CResult_PaymentHashPaymentSendFailureZ_clone(orig: &CResult_PaymentHashPaymentSendFailureZ) -> CResult_PaymentHashPaymentSendFailureZ { Clone::clone(&orig) } +pub extern "C" fn CResult_PaymentHashRetryableSendFailureZ_clone(orig: &CResult_PaymentHashRetryableSendFailureZ) -> CResult_PaymentHashRetryableSendFailureZ { Clone::clone(&orig) } #[repr(C)] /// A tuple of 2 elements. See the individual fields for the types contained. pub struct C2Tuple_PaymentHashPaymentIdZ { @@ -8687,11 +8749,11 @@ pub union CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZPtr { pub result: *mut crate::c_types::derived::C2Tuple_PaymentHashPaymentIdZ, /// A pointer to the contents in the error state. /// Reading from this pointer when `result_ok` is set is undefined. - pub err: *mut crate::lightning::ln::channelmanager::PaymentSendFailure, + pub err: *mut crate::lightning::ln::outbound_payment::PaymentSendFailure, } #[repr(C)] /// A CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ represents the result of a fallible operation, -/// containing a crate::c_types::derived::C2Tuple_PaymentHashPaymentIdZ on success and a crate::lightning::ln::channelmanager::PaymentSendFailure on failure. +/// containing a crate::c_types::derived::C2Tuple_PaymentHashPaymentIdZ on success and a crate::lightning::ln::outbound_payment::PaymentSendFailure on failure. /// `result_ok` indicates the overall state, and the contents are provided via `contents`. pub struct CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { /// The contents of this CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ, accessible via either @@ -8712,7 +8774,7 @@ pub extern "C" fn CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ_ok(o: } #[no_mangle] /// Creates a new CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ in the error state. -pub extern "C" fn CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ_err(e: crate::lightning::ln::channelmanager::PaymentSendFailure) -> CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { +pub extern "C" fn CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ_err(e: crate::lightning::ln::outbound_payment::PaymentSendFailure) -> CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { contents: CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZPtr { err: Box::into_raw(Box::new(e)), @@ -8741,8 +8803,8 @@ impl Drop for CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { } } } -impl From> for CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { - fn from(mut o: crate::c_types::CResultTempl) -> Self { +impl From> for CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { let contents = if o.result_ok { let result = unsafe { o.contents.result }; unsafe { o.contents.result = core::ptr::null_mut() }; @@ -8766,7 +8828,7 @@ impl Clone for CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { } } } else { Self { result_ok: false, contents: CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZPtr { - err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) } } } } @@ -9963,6 +10025,139 @@ impl Clone for CResult_ChannelConfigDecodeErrorZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_ChannelConfigDecodeErrorZ_clone(orig: &CResult_ChannelConfigDecodeErrorZ) -> CResult_ChannelConfigDecodeErrorZ { Clone::clone(&orig) } #[repr(C)] +#[derive(Clone)] +/// An enum which can either contain a crate::lightning::util::errors::APIError or not +pub enum COption_APIErrorZ { + /// When we're in this state, this COption_APIErrorZ contains a crate::lightning::util::errors::APIError + Some(crate::lightning::util::errors::APIError), + /// When we're in this state, this COption_APIErrorZ contains nothing + None +} +impl COption_APIErrorZ { + #[allow(unused)] pub(crate) fn is_some(&self) -> bool { + if let Self::None = self { false } else { true } + } + #[allow(unused)] pub(crate) fn is_none(&self) -> bool { + !self.is_some() + } + #[allow(unused)] pub(crate) fn take(mut self) -> crate::lightning::util::errors::APIError { + if let Self::Some(v) = self { v } else { unreachable!() } + } +} +#[no_mangle] +/// Constructs a new COption_APIErrorZ containing a crate::lightning::util::errors::APIError +pub extern "C" fn COption_APIErrorZ_some(o: crate::lightning::util::errors::APIError) -> COption_APIErrorZ { + COption_APIErrorZ::Some(o) +} +#[no_mangle] +/// Constructs a new COption_APIErrorZ containing nothing +pub extern "C" fn COption_APIErrorZ_none() -> COption_APIErrorZ { + COption_APIErrorZ::None +} +#[no_mangle] +/// Frees any resources associated with the crate::lightning::util::errors::APIError, if we are in the Some state +pub extern "C" fn COption_APIErrorZ_free(_res: COption_APIErrorZ) { } +#[no_mangle] +/// Creates a new COption_APIErrorZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn COption_APIErrorZ_clone(orig: &COption_APIErrorZ) -> COption_APIErrorZ { Clone::clone(&orig) } +#[repr(C)] +/// The contents of CResult_COption_APIErrorZDecodeErrorZ +pub union CResult_COption_APIErrorZDecodeErrorZPtr { + /// A pointer to the contents in the success state. + /// Reading from this pointer when `result_ok` is not set is undefined. + pub result: *mut crate::c_types::derived::COption_APIErrorZ, + /// A pointer to the contents in the error state. + /// Reading from this pointer when `result_ok` is set is undefined. + pub err: *mut crate::lightning::ln::msgs::DecodeError, +} +#[repr(C)] +/// A CResult_COption_APIErrorZDecodeErrorZ represents the result of a fallible operation, +/// containing a crate::c_types::derived::COption_APIErrorZ on success and a crate::lightning::ln::msgs::DecodeError on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_COption_APIErrorZDecodeErrorZ { + /// The contents of this CResult_COption_APIErrorZDecodeErrorZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_COption_APIErrorZDecodeErrorZPtr, + /// Whether this CResult_COption_APIErrorZDecodeErrorZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_COption_APIErrorZDecodeErrorZ in the success state. +pub extern "C" fn CResult_COption_APIErrorZDecodeErrorZ_ok(o: crate::c_types::derived::COption_APIErrorZ) -> CResult_COption_APIErrorZDecodeErrorZ { + CResult_COption_APIErrorZDecodeErrorZ { + contents: CResult_COption_APIErrorZDecodeErrorZPtr { + result: Box::into_raw(Box::new(o)), + }, + result_ok: true, + } +} +#[no_mangle] +/// Creates a new CResult_COption_APIErrorZDecodeErrorZ in the error state. +pub extern "C" fn CResult_COption_APIErrorZDecodeErrorZ_err(e: crate::lightning::ln::msgs::DecodeError) -> CResult_COption_APIErrorZDecodeErrorZ { + CResult_COption_APIErrorZDecodeErrorZ { + contents: CResult_COption_APIErrorZDecodeErrorZPtr { + err: Box::into_raw(Box::new(e)), + }, + result_ok: false, + } +} +/// Checks if the given object is currently in the success state +#[no_mangle] +pub extern "C" fn CResult_COption_APIErrorZDecodeErrorZ_is_ok(o: &CResult_COption_APIErrorZDecodeErrorZ) -> bool { + o.result_ok +} +#[no_mangle] +/// Frees any resources used by the CResult_COption_APIErrorZDecodeErrorZ. +pub extern "C" fn CResult_COption_APIErrorZDecodeErrorZ_free(_res: CResult_COption_APIErrorZDecodeErrorZ) { } +impl Drop for CResult_COption_APIErrorZDecodeErrorZ { + fn drop(&mut self) { + if self.result_ok { + if unsafe { !(self.contents.result as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.result) }; + } + } else { + if unsafe { !(self.contents.err as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.err) }; + } + } + } +} +impl From> for CResult_COption_APIErrorZDecodeErrorZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { + let contents = if o.result_ok { + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = core::ptr::null_mut() }; + CResult_COption_APIErrorZDecodeErrorZPtr { result } + } else { + let err = unsafe { o.contents.err }; + unsafe { o.contents.err = core::ptr::null_mut(); } + CResult_COption_APIErrorZDecodeErrorZPtr { err } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_COption_APIErrorZDecodeErrorZ { + fn clone(&self) -> Self { + if self.result_ok { + Self { result_ok: true, contents: CResult_COption_APIErrorZDecodeErrorZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + } } + } else { + Self { result_ok: false, contents: CResult_COption_APIErrorZDecodeErrorZPtr { + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + } } + } + } +} +#[no_mangle] +/// Creates a new CResult_COption_APIErrorZDecodeErrorZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_COption_APIErrorZDecodeErrorZ_clone(orig: &CResult_COption_APIErrorZDecodeErrorZ) -> CResult_COption_APIErrorZDecodeErrorZ { Clone::clone(&orig) } +#[repr(C)] /// The contents of CResult_OutPointDecodeErrorZ pub union CResult_OutPointDecodeErrorZPtr { /// A pointer to the contents in the success state. @@ -11702,6 +11897,94 @@ pub extern "C" fn COption_NetAddressZ_free(_res: COption_NetAddressZ) { } /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn COption_NetAddressZ_clone(orig: &COption_NetAddressZ) -> COption_NetAddressZ { Clone::clone(&orig) } #[repr(C)] +/// A tuple of 2 elements. See the individual fields for the types contained. +pub struct C2Tuple_PublicKeyCOption_NetAddressZZ { + /// The element at position 0 + pub a: crate::c_types::PublicKey, + /// The element at position 1 + pub b: crate::c_types::derived::COption_NetAddressZ, +} +impl From<(crate::c_types::PublicKey, crate::c_types::derived::COption_NetAddressZ)> for C2Tuple_PublicKeyCOption_NetAddressZZ { + fn from (tup: (crate::c_types::PublicKey, crate::c_types::derived::COption_NetAddressZ)) -> Self { + Self { + a: tup.0, + b: tup.1, + } + } +} +impl C2Tuple_PublicKeyCOption_NetAddressZZ { + #[allow(unused)] pub(crate) fn to_rust(mut self) -> (crate::c_types::PublicKey, crate::c_types::derived::COption_NetAddressZ) { + (self.a, self.b) + } +} +impl Clone for C2Tuple_PublicKeyCOption_NetAddressZZ { + fn clone(&self) -> Self { + Self { + a: Clone::clone(&self.a), + b: Clone::clone(&self.b), + } + } +} +#[no_mangle] +/// Creates a new tuple which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn C2Tuple_PublicKeyCOption_NetAddressZZ_clone(orig: &C2Tuple_PublicKeyCOption_NetAddressZZ) -> C2Tuple_PublicKeyCOption_NetAddressZZ { Clone::clone(&orig) } +/// Creates a new C2Tuple_PublicKeyCOption_NetAddressZZ from the contained elements. +#[no_mangle] +pub extern "C" fn C2Tuple_PublicKeyCOption_NetAddressZZ_new(a: crate::c_types::PublicKey, b: crate::c_types::derived::COption_NetAddressZ) -> C2Tuple_PublicKeyCOption_NetAddressZZ { + C2Tuple_PublicKeyCOption_NetAddressZZ { a, b, } +} + +#[no_mangle] +/// Frees any resources used by the C2Tuple_PublicKeyCOption_NetAddressZZ. +pub extern "C" fn C2Tuple_PublicKeyCOption_NetAddressZZ_free(_res: C2Tuple_PublicKeyCOption_NetAddressZZ) { } +#[repr(C)] +/// A dynamically-allocated array of crate::c_types::derived::C2Tuple_PublicKeyCOption_NetAddressZZs of arbitrary size. +/// This corresponds to std::vector in C++ +pub struct CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ { + /// The elements in the array. + /// If datalen is non-0 this must be a valid, non-NULL pointer allocated by malloc(). + pub data: *mut crate::c_types::derived::C2Tuple_PublicKeyCOption_NetAddressZZ, + /// The number of elements pointed to by `data`. + pub datalen: usize +} +impl CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ { + #[allow(unused)] pub(crate) fn into_rust(&mut self) -> Vec { + if self.datalen == 0 { return Vec::new(); } + let ret = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }.into(); + self.data = core::ptr::null_mut(); + self.datalen = 0; + ret + } + #[allow(unused)] pub(crate) fn as_slice(&self) -> &[crate::c_types::derived::C2Tuple_PublicKeyCOption_NetAddressZZ] { + unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) } + } +} +impl From> for CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ { + fn from(v: Vec) -> Self { + let datalen = v.len(); + let data = Box::into_raw(v.into_boxed_slice()); + Self { datalen, data: unsafe { (*data).as_mut_ptr() } } + } +} +#[no_mangle] +/// Frees the buffer pointed to by `data` if `datalen` is non-0. +pub extern "C" fn CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ_free(_res: CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ) { } +impl Drop for CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ { + fn drop(&mut self) { + if self.datalen == 0 { return; } + let _ = unsafe { Box::from_raw(core::slice::from_raw_parts_mut(self.data, self.datalen)) }; + } +} +impl Clone for CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ { + fn clone(&self) -> Self { + let mut res = Vec::new(); + if self.datalen == 0 { return Self::from(res); } + res.extend_from_slice(unsafe { core::slice::from_raw_parts_mut(self.data, self.datalen) }); + Self::from(res) + } +} +#[repr(C)] /// The contents of CResult_CVec_u8ZPeerHandleErrorZ pub union CResult_CVec_u8ZPeerHandleErrorZPtr { /// A pointer to the contents in the success state. @@ -11986,6 +12269,102 @@ impl Clone for CResult_boolPeerHandleErrorZ { /// but with all dynamically-allocated buffers duplicated in new buffers. pub extern "C" fn CResult_boolPeerHandleErrorZ_clone(orig: &CResult_boolPeerHandleErrorZ) -> CResult_boolPeerHandleErrorZ { Clone::clone(&orig) } #[repr(C)] +/// The contents of CResult_TxOutUtxoLookupErrorZ +pub union CResult_TxOutUtxoLookupErrorZPtr { + /// A pointer to the contents in the success state. + /// Reading from this pointer when `result_ok` is not set is undefined. + pub result: *mut crate::c_types::TxOut, + /// A pointer to the contents in the error state. + /// Reading from this pointer when `result_ok` is set is undefined. + pub err: *mut crate::lightning::routing::utxo::UtxoLookupError, +} +#[repr(C)] +/// A CResult_TxOutUtxoLookupErrorZ represents the result of a fallible operation, +/// containing a crate::c_types::TxOut on success and a crate::lightning::routing::utxo::UtxoLookupError on failure. +/// `result_ok` indicates the overall state, and the contents are provided via `contents`. +pub struct CResult_TxOutUtxoLookupErrorZ { + /// The contents of this CResult_TxOutUtxoLookupErrorZ, accessible via either + /// `err` or `result` depending on the state of `result_ok`. + pub contents: CResult_TxOutUtxoLookupErrorZPtr, + /// Whether this CResult_TxOutUtxoLookupErrorZ represents a success state. + pub result_ok: bool, +} +#[no_mangle] +/// Creates a new CResult_TxOutUtxoLookupErrorZ in the success state. +pub extern "C" fn CResult_TxOutUtxoLookupErrorZ_ok(o: crate::c_types::TxOut) -> CResult_TxOutUtxoLookupErrorZ { + CResult_TxOutUtxoLookupErrorZ { + contents: CResult_TxOutUtxoLookupErrorZPtr { + result: Box::into_raw(Box::new(o)), + }, + result_ok: true, + } +} +#[no_mangle] +/// Creates a new CResult_TxOutUtxoLookupErrorZ in the error state. +pub extern "C" fn CResult_TxOutUtxoLookupErrorZ_err(e: crate::lightning::routing::utxo::UtxoLookupError) -> CResult_TxOutUtxoLookupErrorZ { + CResult_TxOutUtxoLookupErrorZ { + contents: CResult_TxOutUtxoLookupErrorZPtr { + err: Box::into_raw(Box::new(e)), + }, + result_ok: false, + } +} +/// Checks if the given object is currently in the success state +#[no_mangle] +pub extern "C" fn CResult_TxOutUtxoLookupErrorZ_is_ok(o: &CResult_TxOutUtxoLookupErrorZ) -> bool { + o.result_ok +} +#[no_mangle] +/// Frees any resources used by the CResult_TxOutUtxoLookupErrorZ. +pub extern "C" fn CResult_TxOutUtxoLookupErrorZ_free(_res: CResult_TxOutUtxoLookupErrorZ) { } +impl Drop for CResult_TxOutUtxoLookupErrorZ { + fn drop(&mut self) { + if self.result_ok { + if unsafe { !(self.contents.result as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.result) }; + } + } else { + if unsafe { !(self.contents.err as *mut ()).is_null() } { + let _ = unsafe { Box::from_raw(self.contents.err) }; + } + } + } +} +impl From> for CResult_TxOutUtxoLookupErrorZ { + fn from(mut o: crate::c_types::CResultTempl) -> Self { + let contents = if o.result_ok { + let result = unsafe { o.contents.result }; + unsafe { o.contents.result = core::ptr::null_mut() }; + CResult_TxOutUtxoLookupErrorZPtr { result } + } else { + let err = unsafe { o.contents.err }; + unsafe { o.contents.err = core::ptr::null_mut(); } + CResult_TxOutUtxoLookupErrorZPtr { err } + }; + Self { + contents, + result_ok: o.result_ok, + } + } +} +impl Clone for CResult_TxOutUtxoLookupErrorZ { + fn clone(&self) -> Self { + if self.result_ok { + Self { result_ok: true, contents: CResult_TxOutUtxoLookupErrorZPtr { + result: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.result }))) + } } + } else { + Self { result_ok: false, contents: CResult_TxOutUtxoLookupErrorZPtr { + err: Box::into_raw(Box::new(::clone(unsafe { &*self.contents.err }))) + } } + } + } +} +#[no_mangle] +/// Creates a new CResult_TxOutUtxoLookupErrorZ which has the same data as `orig` +/// but with all dynamically-allocated buffers duplicated in new buffers. +pub extern "C" fn CResult_TxOutUtxoLookupErrorZ_clone(orig: &CResult_TxOutUtxoLookupErrorZ) -> CResult_TxOutUtxoLookupErrorZ { Clone::clone(&orig) } +#[repr(C)] /// The contents of CResult_NoneSendErrorZ pub union CResult_NoneSendErrorZPtr { /// Note that this value is always NULL, as there are no contents in the OK variant diff --git a/lightning-c-bindings/src/lightning/chain/chainmonitor.rs b/lightning-c-bindings/src/lightning/chain/chainmonitor.rs index 9faddad..049fe4e 100644 --- a/lightning-c-bindings/src/lightning/chain/chainmonitor.rs +++ b/lightning-c-bindings/src/lightning/chain/chainmonitor.rs @@ -197,7 +197,7 @@ pub struct Persist { /// /// Note that update (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] - pub update_persisted_channel: extern "C" fn (this_arg: *const c_void, channel_id: crate::lightning::chain::transaction::OutPoint, update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &crate::lightning::chain::channelmonitor::ChannelMonitor, update_id: crate::lightning::chain::chainmonitor::MonitorUpdateId) -> crate::lightning::chain::ChannelMonitorUpdateStatus, + pub update_persisted_channel: extern "C" fn (this_arg: *const c_void, channel_id: crate::lightning::chain::transaction::OutPoint, update: crate::lightning::chain::channelmonitor::ChannelMonitorUpdate, data: &crate::lightning::chain::channelmonitor::ChannelMonitor, update_id: crate::lightning::chain::chainmonitor::MonitorUpdateId) -> crate::lightning::chain::ChannelMonitorUpdateStatus, /// Frees any resources associated with this object given its this_arg pointer. /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. pub free: Option, @@ -215,13 +215,13 @@ pub(crate) extern "C" fn Persist_clone_fields(orig: &Persist) -> Persist { } use lightning::chain::chainmonitor::Persist as rustPersist; -impl rustPersist for Persist { - fn persist_new_channel(&self, mut channel_id: lightning::chain::transaction::OutPoint, mut data: &lightning::chain::channelmonitor::ChannelMonitor, mut update_id: lightning::chain::chainmonitor::MonitorUpdateId) -> lightning::chain::ChannelMonitorUpdateStatus { +impl rustPersist for Persist { + fn persist_new_channel(&self, mut channel_id: lightning::chain::transaction::OutPoint, mut data: &lightning::chain::channelmonitor::ChannelMonitor, mut update_id: lightning::chain::chainmonitor::MonitorUpdateId) -> lightning::chain::ChannelMonitorUpdateStatus { let mut ret = (self.persist_new_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(channel_id), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const lightning::chain::channelmonitor::ChannelMonitor<_, >) as *mut _) }, is_owned: false }, crate::lightning::chain::chainmonitor::MonitorUpdateId { inner: ObjOps::heap_alloc(update_id), is_owned: true }); ret.into_native() } - fn update_persisted_channel(&self, mut channel_id: lightning::chain::transaction::OutPoint, mut update: &Option, mut data: &lightning::chain::channelmonitor::ChannelMonitor, mut update_id: lightning::chain::chainmonitor::MonitorUpdateId) -> lightning::chain::ChannelMonitorUpdateStatus { - let mut local_update = &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (if update.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (update.as_ref().unwrap()) }) } as *const lightning::chain::channelmonitor::ChannelMonitorUpdate<>) as *mut _ }, is_owned: false }; + fn update_persisted_channel(&self, mut channel_id: lightning::chain::transaction::OutPoint, mut update: Option<&lightning::chain::channelmonitor::ChannelMonitorUpdate>, mut data: &lightning::chain::channelmonitor::ChannelMonitor, mut update_id: lightning::chain::chainmonitor::MonitorUpdateId) -> lightning::chain::ChannelMonitorUpdateStatus { + let mut local_update = crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { (if update.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (update.unwrap()) }) } as *const lightning::chain::channelmonitor::ChannelMonitorUpdate<>) as *mut _ }, is_owned: false }; let mut ret = (self.update_persisted_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(channel_id), is_owned: true }, local_update, &crate::lightning::chain::channelmonitor::ChannelMonitor { inner: unsafe { ObjOps::nonnull_ptr_to_inner((data as *const lightning::chain::channelmonitor::ChannelMonitor<_, >) as *mut _) }, is_owned: false }, crate::lightning::chain::chainmonitor::MonitorUpdateId { inner: ObjOps::heap_alloc(update_id), is_owned: true }); ret.into_native() } @@ -247,7 +247,7 @@ impl Drop for Persist { } use lightning::chain::chainmonitor::LockedChannelMonitor as nativeLockedChannelMonitorImport; -pub(crate) type nativeLockedChannelMonitor = nativeLockedChannelMonitorImport<'static, crate::lightning::chain::keysinterface::Sign>; +pub(crate) type nativeLockedChannelMonitor = nativeLockedChannelMonitorImport<'static, crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner>; /// A read-only reference to a current ChannelMonitor. /// @@ -301,7 +301,7 @@ impl LockedChannelMonitor { } use lightning::chain::chainmonitor::ChainMonitor as nativeChainMonitorImport; -pub(crate) type nativeChainMonitor = nativeChainMonitorImport; +pub(crate) type nativeChainMonitor = nativeChainMonitorImport; /// An implementation of [`chain::Watch`] for monitoring channels. /// @@ -550,8 +550,8 @@ extern "C" fn ChainMonitor_Watch_watch_channel(this_arg: *const c_void, mut fund crate::lightning::chain::ChannelMonitorUpdateStatus::native_into(ret) } #[must_use] -extern "C" fn ChainMonitor_Watch_update_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, mut update: crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::lightning::chain::ChannelMonitorUpdateStatus { - let mut ret = >::update_channel(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, *unsafe { Box::from_raw(update.take_inner()) }); +extern "C" fn ChainMonitor_Watch_update_channel(this_arg: *const c_void, mut funding_txo: crate::lightning::chain::transaction::OutPoint, update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::lightning::chain::ChannelMonitorUpdateStatus { + let mut ret = >::update_channel(unsafe { &mut *(this_arg as *mut nativeChainMonitor) }, *unsafe { Box::from_raw(funding_txo.take_inner()) }, update.get_native_ref()); crate::lightning::chain::ChannelMonitorUpdateStatus::native_into(ret) } #[must_use] diff --git a/lightning-c-bindings/src/lightning/chain/channelmonitor.rs b/lightning-c-bindings/src/lightning/chain/channelmonitor.rs index 0d27aa5..1378873 100644 --- a/lightning-c-bindings/src/lightning/chain/channelmonitor.rs +++ b/lightning-c-bindings/src/lightning/chain/channelmonitor.rs @@ -790,7 +790,7 @@ pub extern "C" fn Balance_eq(a: &Balance, b: &Balance) -> bool { } use lightning::chain::channelmonitor::ChannelMonitor as nativeChannelMonitorImport; -pub(crate) type nativeChannelMonitor = nativeChannelMonitorImport; +pub(crate) type nativeChannelMonitor = nativeChannelMonitorImport; /// A ChannelMonitor handles chain events (blocks connected and disconnected) and generates /// on-chain transactions to ensure no loss of funds occurs. @@ -1086,9 +1086,11 @@ pub extern "C" fn ChannelMonitor_get_claimable_balances(this_arg: &crate::lightn #[no_mangle] /// Read a C2Tuple_BlockHashChannelMonitorZ from a byte array, created by C2Tuple_BlockHashChannelMonitorZ_write -pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_read(ser: crate::c_types::u8slice, arg: &crate::lightning::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ { - let arg_conv = arg; - let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv); +pub extern "C" fn C2Tuple_BlockHashChannelMonitorZ_read(ser: crate::c_types::u8slice, arg_a: &crate::lightning::chain::keysinterface::EntropySource, arg_b: &crate::lightning::chain::keysinterface::SignerProvider) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ { + let arg_a_conv = arg_a; + let arg_b_conv = arg_b; + let arg_conv = (arg_a_conv, arg_b_conv); + let res: Result<(bitcoin::hash_types::BlockHash, lightning::chain::channelmonitor::ChannelMonitor), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv); 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::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(orig_res_0_1), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } diff --git a/lightning-c-bindings/src/lightning/chain/keysinterface.rs b/lightning-c-bindings/src/lightning/chain/keysinterface.rs index 999300f..c8db360 100644 --- a/lightning-c-bindings/src/lightning/chain/keysinterface.rs +++ b/lightning-c-bindings/src/lightning/chain/keysinterface.rs @@ -133,14 +133,14 @@ pub extern "C" fn DelayedPaymentOutputDescriptor_get_revocation_pubkey(this_ptr: pub extern "C" fn DelayedPaymentOutputDescriptor_set_revocation_pubkey(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::PublicKey) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.revocation_pubkey = val.into_rust(); } -/// Arbitrary identification information returned by a call to [`BaseSign::channel_keys_id`]. +/// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`]. /// This may be useful in re-deriving keys used in the channel to spend the output. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &DelayedPaymentOutputDescriptor) -> *const [u8; 32] { let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_keys_id; inner_val } -/// Arbitrary identification information returned by a call to [`BaseSign::channel_keys_id`]. +/// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`]. /// This may be useful in re-deriving keys used in the channel to spend the output. #[no_mangle] pub extern "C" fn DelayedPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut DelayedPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) { @@ -292,14 +292,14 @@ pub extern "C" fn StaticPaymentOutputDescriptor_get_output(this_ptr: &StaticPaym pub extern "C" fn StaticPaymentOutputDescriptor_set_output(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::c_types::TxOut) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.output = val.into_rust(); } -/// Arbitrary identification information returned by a call to [`BaseSign::channel_keys_id`]. +/// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`]. /// This may be useful in re-deriving keys used in the channel to spend the output. #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_get_channel_keys_id(this_ptr: &StaticPaymentOutputDescriptor) -> *const [u8; 32] { let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_keys_id; inner_val } -/// Arbitrary identification information returned by a call to [`BaseSign::channel_keys_id`]. +/// Arbitrary identification information returned by a call to [`ChannelSigner::channel_keys_id`]. /// This may be useful in re-deriving keys used in the channel to spend the output. #[no_mangle] pub extern "C" fn StaticPaymentOutputDescriptor_set_channel_keys_id(this_ptr: &mut StaticPaymentOutputDescriptor, mut val: crate::c_types::ThirtyTwoBytes) { @@ -384,14 +384,14 @@ pub extern "C" fn StaticPaymentOutputDescriptor_read(ser: crate::c_types::u8slic #[must_use] #[repr(C)] pub enum SpendableOutputDescriptor { - /// An output to a script which was provided via [`KeysInterface`] directly, either from + /// An output to a script which was provided via [`SignerProvider`] directly, either from /// [`get_destination_script`] or [`get_shutdown_scriptpubkey`], thus you should already /// know how to spend it. No secret keys are provided as LDK was never given any key. /// These may include outputs from a transaction punishing our counterparty or claiming an HTLC /// on-chain using the payment preimage or after it has timed out. /// - /// [`get_shutdown_scriptpubkey`]: KeysInterface::get_shutdown_scriptpubkey - /// [`get_destination_script`]: KeysInterface::get_shutdown_scriptpubkey + /// [`get_shutdown_scriptpubkey`]: SignerProvider::get_shutdown_scriptpubkey + /// [`get_destination_script`]: SignerProvider::get_shutdown_scriptpubkey StaticOutput { /// The outpoint which is spendable. outpoint: crate::lightning::chain::transaction::OutPoint, @@ -419,15 +419,15 @@ pub enum SpendableOutputDescriptor { /// /// To derive the delayed payment key which is used to sign this input, you must pass the /// holder [`InMemorySigner::delayed_payment_base_key`] (i.e., the private key which corresponds to the - /// [`ChannelPublicKeys::delayed_payment_basepoint`] in [`BaseSign::pubkeys`]) and the provided + /// [`ChannelPublicKeys::delayed_payment_basepoint`] in [`ChannelSigner::pubkeys`]) and the provided /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to [`chan_utils::derive_private_key`]. The public key can be /// generated without the secret key using [`chan_utils::derive_public_key`] and only the - /// [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in [`BaseSign::pubkeys`]. + /// [`ChannelPublicKeys::delayed_payment_basepoint`] which appears in [`ChannelSigner::pubkeys`]. /// /// To derive the [`DelayedPaymentOutputDescriptor::revocation_pubkey`] provided here (which is /// used in the witness script generation), you must pass the counterparty /// [`ChannelPublicKeys::revocation_basepoint`] (which appears in the call to - /// [`BaseSign::provide_channel_parameters`]) and the provided + /// [`ChannelSigner::provide_channel_parameters`]) and the provided /// [`DelayedPaymentOutputDescriptor::per_commitment_point`] to /// [`chan_utils::derive_public_revocation_key`]. /// @@ -439,7 +439,7 @@ pub enum SpendableOutputDescriptor { DelayedPaymentOutput( crate::lightning::chain::keysinterface::DelayedPaymentOutputDescriptor), /// An output to a P2WPKH, spendable exclusively by our payment key (i.e., the private key - /// which corresponds to the `payment_point` in [`BaseSign::pubkeys`]). The witness + /// which corresponds to the `payment_point` in [`ChannelSigner::pubkeys`]). The witness /// in the spending input is, thus, simply: /// ```bitcoin /// @@ -591,15 +591,10 @@ pub extern "C" fn SpendableOutputDescriptor_read(ser: crate::c_types::u8slice) - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::SpendableOutputDescriptor::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } -/// A trait to sign Lightning channel transactions as described in -/// [BOLT 3](https://github.com/lightning/bolts/blob/master/03-transactions.md). -/// -/// Signing services could be implemented on a hardware wallet and should implement signing -/// policies in order to be secure. Please refer to the [VLS Policy -/// Controls](https://gitlab.com/lightning-signer/validating-lightning-signer/-/blob/main/docs/policy-controls.md) -/// for an example of such policies. +/// A trait to handle Lightning channel key material without concretizing the channel type or +/// the signature mechanism. #[repr(C)] -pub struct BaseSign { +pub struct ChannelSigner { /// An opaque pointer which is passed to your function implementations as an argument. /// This has no meaning in the LDK, and can be NULL or any other value. pub this_arg: *mut c_void, @@ -638,12 +633,104 @@ pub struct BaseSign { /// Fill in the pubkeys field as a reference to it will be given to Rust after this returns /// Note that this takes a pointer to this object, not the this_ptr like other methods do /// This function pointer may be NULL if pubkeys is filled in when this object is created and never needs updating. - pub set_pubkeys: Option, + pub set_pubkeys: Option, /// Returns an arbitrary identifier describing the set of keys which are provided back to you in /// some [`SpendableOutputDescriptor`] types. This should be sufficient to identify this - /// [`BaseSign`] object uniquely and lookup or re-derive its keys. + /// [`EcdsaChannelSigner`] object uniquely and lookup or re-derive its keys. #[must_use] pub channel_keys_id: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes, + /// Set the counterparty static channel data, including basepoints, + /// `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint. + /// + /// This data is static, and will never change for a channel once set. For a given [`ChannelSigner`] + /// instance, LDK will call this method exactly once - either immediately after construction + /// (not including if done via [`SignerProvider::read_chan_signer`]) or when the funding + /// information has been generated. + /// + /// channel_parameters.is_populated() MUST be true. + pub provide_channel_parameters: extern "C" fn (this_arg: *mut c_void, channel_parameters: &crate::lightning::ln::chan_utils::ChannelTransactionParameters), + /// Frees any resources associated with this object given its this_arg pointer. + /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. + pub free: Option, +} +unsafe impl Send for ChannelSigner {} +unsafe impl Sync for ChannelSigner {} +#[no_mangle] +pub(crate) extern "C" fn ChannelSigner_clone_fields(orig: &ChannelSigner) -> ChannelSigner { + ChannelSigner { + this_arg: orig.this_arg, + get_per_commitment_point: Clone::clone(&orig.get_per_commitment_point), + release_commitment_secret: Clone::clone(&orig.release_commitment_secret), + validate_holder_commitment: Clone::clone(&orig.validate_holder_commitment), + pubkeys: Clone::clone(&orig.pubkeys), + set_pubkeys: Clone::clone(&orig.set_pubkeys), + channel_keys_id: Clone::clone(&orig.channel_keys_id), + provide_channel_parameters: Clone::clone(&orig.provide_channel_parameters), + free: Clone::clone(&orig.free), + } +} + +use lightning::chain::keysinterface::ChannelSigner as rustChannelSigner; +impl rustChannelSigner for ChannelSigner { + fn get_per_commitment_point(&self, mut idx: u64, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> bitcoin::secp256k1::PublicKey { + let mut ret = (self.get_per_commitment_point)(self.this_arg, idx); + ret.into_rust() + } + fn release_commitment_secret(&self, mut idx: u64) -> [u8; 32] { + let mut ret = (self.release_commitment_secret)(self.this_arg, idx); + ret.data + } + fn validate_holder_commitment(&self, mut holder_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut preimages: Vec) -> Result<(), ()> { + let mut local_preimages = Vec::new(); for mut item in preimages.drain(..) { local_preimages.push( { crate::c_types::ThirtyTwoBytes { data: item.0 } }); }; + let mut ret = (self.validate_holder_commitment)(self.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((holder_tx as *const lightning::ln::chan_utils::HolderCommitmentTransaction<>) as *mut _) }, is_owned: false }, local_preimages.into()); + let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; + local_ret + } + fn pubkeys(&self) -> &lightning::ln::chan_utils::ChannelPublicKeys { + if let Some(f) = self.set_pubkeys { + (f)(&self); + } + self.pubkeys.get_native_ref() + } + fn channel_keys_id(&self) -> [u8; 32] { + let mut ret = (self.channel_keys_id)(self.this_arg); + ret.data + } + fn provide_channel_parameters(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) { + (self.provide_channel_parameters)(self.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_parameters as *const lightning::ln::chan_utils::ChannelTransactionParameters<>) as *mut _) }, is_owned: false }) + } +} + +// We're essentially a pointer already, or at least a set of pointers, so allow us to be used +// directly as a Deref trait in higher-level structs: +impl core::ops::Deref for ChannelSigner { + type Target = Self; + fn deref(&self) -> &Self { + self + } +} +/// Calls the free function if one is set +#[no_mangle] +pub extern "C" fn ChannelSigner_free(this_ptr: ChannelSigner) { } +impl Drop for ChannelSigner { + fn drop(&mut self) { + if let Some(f) = self.free { + f(self.this_arg); + } + } +} +/// A trait to sign Lightning channel transactions as described in +/// [BOLT 3](https://github.com/lightning/bolts/blob/master/03-transactions.md). +/// +/// Signing services could be implemented on a hardware wallet and should implement signing +/// policies in order to be secure. Please refer to the [VLS Policy +/// Controls](https://gitlab.com/lightning-signer/validating-lightning-signer/-/blob/main/docs/policy-controls.md) +/// for an example of such policies. +#[repr(C)] +pub struct EcdsaChannelSigner { + /// An opaque pointer which is passed to your function implementations as an argument. + /// This has no meaning in the LDK, and can be NULL or any other value. + pub this_arg: *mut c_void, /// Create a signature for a counterparty's commitment transaction and associated HTLC transactions. /// /// Note that if signing fails or is rejected, the channel will be force-closed. @@ -747,40 +834,29 @@ pub struct BaseSign { /// input within `anchor_tx`, which spends the commitment transaction, at index `input`. #[must_use] pub sign_holder_anchor_input: extern "C" fn (this_arg: *const c_void, anchor_tx: crate::c_types::Transaction, input: usize) -> crate::c_types::derived::CResult_SignatureNoneZ, - /// Signs a channel announcement message with our funding key and our node secret key (aka - /// node_id or network_key), proving it comes from one of the channel participants. + /// Signs a channel announcement message with our funding key proving it comes from one of the + /// channel participants. /// - /// The first returned signature should be from our node secret key, the second from our - /// funding key. + /// Channel announcements also require a signature from each node's network key. Our node + /// signature is computed through [`NodeSigner::sign_gossip_message`]. /// /// Note that if this fails or is rejected, the channel will not be publicly announced and /// our counterparty may (though likely will not) close the channel on us for violating the /// protocol. #[must_use] - pub sign_channel_announcement: extern "C" fn (this_arg: *const c_void, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_C2Tuple_SignatureSignatureZNoneZ, - /// Set the counterparty static channel data, including basepoints, - /// `counterparty_selected`/`holder_selected_contest_delay` and funding outpoint. Since these - /// are static channel data, they MUST NOT be allowed to change to different values once set, - /// as LDK may call this method more than once. - /// - /// channel_parameters.is_populated() MUST be true. - pub provide_channel_parameters: extern "C" fn (this_arg: *mut c_void, channel_parameters: &crate::lightning::ln::chan_utils::ChannelTransactionParameters), + pub sign_channel_announcement_with_funding_key: extern "C" fn (this_arg: *const c_void, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ, + /// Implementation of ChannelSigner for this object. + pub ChannelSigner: crate::lightning::chain::keysinterface::ChannelSigner, /// Frees any resources associated with this object given its this_arg pointer. /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. pub free: Option, } -unsafe impl Send for BaseSign {} -unsafe impl Sync for BaseSign {} +unsafe impl Send for EcdsaChannelSigner {} +unsafe impl Sync for EcdsaChannelSigner {} #[no_mangle] -pub(crate) extern "C" fn BaseSign_clone_fields(orig: &BaseSign) -> BaseSign { - BaseSign { +pub(crate) extern "C" fn EcdsaChannelSigner_clone_fields(orig: &EcdsaChannelSigner) -> EcdsaChannelSigner { + EcdsaChannelSigner { this_arg: orig.this_arg, - get_per_commitment_point: Clone::clone(&orig.get_per_commitment_point), - release_commitment_secret: Clone::clone(&orig.release_commitment_secret), - validate_holder_commitment: Clone::clone(&orig.validate_holder_commitment), - pubkeys: Clone::clone(&orig.pubkeys), - set_pubkeys: Clone::clone(&orig.set_pubkeys), - channel_keys_id: Clone::clone(&orig.channel_keys_id), sign_counterparty_commitment: Clone::clone(&orig.sign_counterparty_commitment), validate_counterparty_revocation: Clone::clone(&orig.validate_counterparty_revocation), sign_holder_commitment_and_htlcs: Clone::clone(&orig.sign_holder_commitment_and_htlcs), @@ -789,38 +865,43 @@ pub(crate) extern "C" fn BaseSign_clone_fields(orig: &BaseSign) -> BaseSign { sign_counterparty_htlc_transaction: Clone::clone(&orig.sign_counterparty_htlc_transaction), sign_closing_transaction: Clone::clone(&orig.sign_closing_transaction), sign_holder_anchor_input: Clone::clone(&orig.sign_holder_anchor_input), - sign_channel_announcement: Clone::clone(&orig.sign_channel_announcement), - provide_channel_parameters: Clone::clone(&orig.provide_channel_parameters), + sign_channel_announcement_with_funding_key: Clone::clone(&orig.sign_channel_announcement_with_funding_key), + ChannelSigner: crate::lightning::chain::keysinterface::ChannelSigner_clone_fields(&orig.ChannelSigner), free: Clone::clone(&orig.free), } } - -use lightning::chain::keysinterface::BaseSign as rustBaseSign; -impl rustBaseSign for BaseSign { +impl lightning::chain::keysinterface::ChannelSigner for EcdsaChannelSigner { fn get_per_commitment_point(&self, mut idx: u64, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> bitcoin::secp256k1::PublicKey { - let mut ret = (self.get_per_commitment_point)(self.this_arg, idx); + let mut ret = (self.ChannelSigner.get_per_commitment_point)(self.ChannelSigner.this_arg, idx); ret.into_rust() } fn release_commitment_secret(&self, mut idx: u64) -> [u8; 32] { - let mut ret = (self.release_commitment_secret)(self.this_arg, idx); + let mut ret = (self.ChannelSigner.release_commitment_secret)(self.ChannelSigner.this_arg, idx); ret.data } fn validate_holder_commitment(&self, mut holder_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut preimages: Vec) -> Result<(), ()> { let mut local_preimages = Vec::new(); for mut item in preimages.drain(..) { local_preimages.push( { crate::c_types::ThirtyTwoBytes { data: item.0 } }); }; - let mut ret = (self.validate_holder_commitment)(self.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((holder_tx as *const lightning::ln::chan_utils::HolderCommitmentTransaction<>) as *mut _) }, is_owned: false }, local_preimages.into()); + let mut ret = (self.ChannelSigner.validate_holder_commitment)(self.ChannelSigner.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((holder_tx as *const lightning::ln::chan_utils::HolderCommitmentTransaction<>) as *mut _) }, is_owned: false }, local_preimages.into()); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn pubkeys(&self) -> &lightning::ln::chan_utils::ChannelPublicKeys { - if let Some(f) = self.set_pubkeys { - (f)(&self); + if let Some(f) = self.ChannelSigner.set_pubkeys { + (f)(&self.ChannelSigner); } - self.pubkeys.get_native_ref() + self.ChannelSigner.pubkeys.get_native_ref() } fn channel_keys_id(&self) -> [u8; 32] { - let mut ret = (self.channel_keys_id)(self.this_arg); + let mut ret = (self.ChannelSigner.channel_keys_id)(self.ChannelSigner.this_arg); ret.data } + fn provide_channel_parameters(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) { + (self.ChannelSigner.provide_channel_parameters)(self.ChannelSigner.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_parameters as *const lightning::ln::chan_utils::ChannelTransactionParameters<>) as *mut _) }, is_owned: false }) + } +} + +use lightning::chain::keysinterface::EcdsaChannelSigner as rustEcdsaChannelSigner; +impl rustEcdsaChannelSigner for EcdsaChannelSigner { fn sign_counterparty_commitment(&self, mut commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, mut preimages: Vec, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::ecdsa::Signature, Vec), ()> { let mut local_preimages = Vec::new(); for mut item in preimages.drain(..) { local_preimages.push( { crate::c_types::ThirtyTwoBytes { data: item.0 } }); }; let mut ret = (self.sign_counterparty_commitment)(self.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const lightning::ln::chan_utils::CommitmentTransaction<>) as *mut _) }, is_owned: false }, local_preimages.into()); @@ -862,19 +943,16 @@ impl rustBaseSign for BaseSign { let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } - fn sign_channel_announcement(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::ecdsa::Signature, bitcoin::secp256k1::ecdsa::Signature), ()> { - let mut ret = (self.sign_channel_announcement)(self.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::UnsignedChannelAnnouncement<>) as *mut _) }, is_owned: false }); - let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_ret_0 = (orig_ret_0_0.into_rust(), orig_ret_0_1.into_rust()); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; + fn sign_channel_announcement_with_funding_key(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + let mut ret = (self.sign_channel_announcement_with_funding_key)(self.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::UnsignedChannelAnnouncement<>) as *mut _) }, is_owned: false }); + let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } - fn provide_channel_parameters(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) { - (self.provide_channel_parameters)(self.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_parameters as *const lightning::ln::chan_utils::ChannelTransactionParameters<>) as *mut _) }, is_owned: false }) - } } // We're essentially a pointer already, or at least a set of pointers, so allow us to be used // directly as a Deref trait in higher-level structs: -impl core::ops::Deref for BaseSign { +impl core::ops::Deref for EcdsaChannelSigner { type Target = Self; fn deref(&self) -> &Self { self @@ -882,8 +960,8 @@ impl core::ops::Deref for BaseSign { } /// Calls the free function if one is set #[no_mangle] -pub extern "C" fn BaseSign_free(this_ptr: BaseSign) { } -impl Drop for BaseSign { +pub extern "C" fn EcdsaChannelSigner_free(this_ptr: EcdsaChannelSigner) { } +impl Drop for EcdsaChannelSigner { fn drop(&mut self) { if let Some(f) = self.free { f(self.this_arg); @@ -898,118 +976,120 @@ impl Drop for BaseSign { /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor #[repr(C)] -pub struct Sign { +pub struct WriteableEcdsaChannelSigner { /// An opaque pointer which is passed to your function implementations as an argument. /// This has no meaning in the LDK, and can be NULL or any other value. pub this_arg: *mut c_void, - /// Implementation of BaseSign for this object. - pub BaseSign: crate::lightning::chain::keysinterface::BaseSign, + /// Implementation of EcdsaChannelSigner for this object. + pub EcdsaChannelSigner: crate::lightning::chain::keysinterface::EcdsaChannelSigner, /// Serialize the object into a byte array pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z, /// Frees any resources associated with this object given its this_arg pointer. /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. pub free: Option, } -unsafe impl Send for Sign {} -unsafe impl Sync for Sign {} +unsafe impl Send for WriteableEcdsaChannelSigner {} +unsafe impl Sync for WriteableEcdsaChannelSigner {} #[no_mangle] -pub(crate) extern "C" fn Sign_clone_fields(orig: &Sign) -> Sign { - Sign { +pub(crate) extern "C" fn WriteableEcdsaChannelSigner_clone_fields(orig: &WriteableEcdsaChannelSigner) -> WriteableEcdsaChannelSigner { + WriteableEcdsaChannelSigner { this_arg: orig.this_arg, - BaseSign: crate::lightning::chain::keysinterface::BaseSign_clone_fields(&orig.BaseSign), + EcdsaChannelSigner: crate::lightning::chain::keysinterface::EcdsaChannelSigner_clone_fields(&orig.EcdsaChannelSigner), write: Clone::clone(&orig.write), free: Clone::clone(&orig.free), } } -impl lightning::chain::keysinterface::BaseSign for Sign { - fn get_per_commitment_point(&self, mut idx: u64, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> bitcoin::secp256k1::PublicKey { - let mut ret = (self.BaseSign.get_per_commitment_point)(self.BaseSign.this_arg, idx); - ret.into_rust() - } - fn release_commitment_secret(&self, mut idx: u64) -> [u8; 32] { - let mut ret = (self.BaseSign.release_commitment_secret)(self.BaseSign.this_arg, idx); - ret.data - } - fn validate_holder_commitment(&self, mut holder_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut preimages: Vec) -> Result<(), ()> { - let mut local_preimages = Vec::new(); for mut item in preimages.drain(..) { local_preimages.push( { crate::c_types::ThirtyTwoBytes { data: item.0 } }); }; - let mut ret = (self.BaseSign.validate_holder_commitment)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((holder_tx as *const lightning::ln::chan_utils::HolderCommitmentTransaction<>) as *mut _) }, is_owned: false }, local_preimages.into()); - let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; - local_ret - } - fn pubkeys(&self) -> &lightning::ln::chan_utils::ChannelPublicKeys { - if let Some(f) = self.BaseSign.set_pubkeys { - (f)(&self.BaseSign); - } - self.BaseSign.pubkeys.get_native_ref() - } - fn channel_keys_id(&self) -> [u8; 32] { - let mut ret = (self.BaseSign.channel_keys_id)(self.BaseSign.this_arg); - ret.data - } +impl lightning::chain::keysinterface::EcdsaChannelSigner for WriteableEcdsaChannelSigner { fn sign_counterparty_commitment(&self, mut commitment_tx: &lightning::ln::chan_utils::CommitmentTransaction, mut preimages: Vec, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::ecdsa::Signature, Vec), ()> { let mut local_preimages = Vec::new(); for mut item in preimages.drain(..) { local_preimages.push( { crate::c_types::ThirtyTwoBytes { data: item.0 } }); }; - let mut ret = (self.BaseSign.sign_counterparty_commitment)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const lightning::ln::chan_utils::CommitmentTransaction<>) as *mut _) }, is_owned: false }, local_preimages.into()); + let mut ret = (self.EcdsaChannelSigner.sign_counterparty_commitment)(self.EcdsaChannelSigner.this_arg, &crate::lightning::ln::chan_utils::CommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const lightning::ln::chan_utils::CommitmentTransaction<>) as *mut _) }, is_owned: false }, local_preimages.into()); let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn validate_counterparty_revocation(&self, mut idx: u64, mut secret: &bitcoin::secp256k1::SecretKey) -> Result<(), ()> { - let mut ret = (self.BaseSign.validate_counterparty_revocation)(self.BaseSign.this_arg, idx, secret.as_ref()); + let mut ret = (self.EcdsaChannelSigner.validate_counterparty_revocation)(self.EcdsaChannelSigner.this_arg, idx, secret.as_ref()); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_holder_commitment_and_htlcs(&self, mut commitment_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::ecdsa::Signature, Vec), ()> { - let mut ret = (self.BaseSign.sign_holder_commitment_and_htlcs)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const lightning::ln::chan_utils::HolderCommitmentTransaction<>) as *mut _) }, is_owned: false }); + let mut ret = (self.EcdsaChannelSigner.sign_holder_commitment_and_htlcs)(self.EcdsaChannelSigner.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((commitment_tx as *const lightning::ln::chan_utils::HolderCommitmentTransaction<>) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.into_rust().drain(..) { local_orig_ret_0_1.push( { item.into_rust() }); }; let mut local_ret_0 = (orig_ret_0_0.into_rust(), local_orig_ret_0_1); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_justice_revoked_output(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::SecretKey, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.BaseSign.sign_justice_revoked_output)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref()); + let mut ret = (self.EcdsaChannelSigner.sign_justice_revoked_output)(self.EcdsaChannelSigner.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref()); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_justice_revoked_htlc(&self, mut justice_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_key: &bitcoin::secp256k1::SecretKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.BaseSign.sign_justice_revoked_htlc)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const lightning::ln::chan_utils::HTLCOutputInCommitment<>) as *mut _) }, is_owned: false }); + let mut ret = (self.EcdsaChannelSigner.sign_justice_revoked_htlc)(self.EcdsaChannelSigner.this_arg, crate::c_types::Transaction::from_bitcoin(justice_tx), input, amount, per_commitment_key.as_ref(), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const lightning::ln::chan_utils::HTLCOutputInCommitment<>) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_counterparty_htlc_transaction(&self, mut htlc_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: &bitcoin::secp256k1::PublicKey, mut htlc: &lightning::ln::chan_utils::HTLCOutputInCommitment, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.BaseSign.sign_counterparty_htlc_transaction)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const lightning::ln::chan_utils::HTLCOutputInCommitment<>) as *mut _) }, is_owned: false }); + let mut ret = (self.EcdsaChannelSigner.sign_counterparty_htlc_transaction)(self.EcdsaChannelSigner.this_arg, crate::c_types::Transaction::from_bitcoin(htlc_tx), input, amount, crate::c_types::PublicKey::from_rust(&per_commitment_point), &crate::lightning::ln::chan_utils::HTLCOutputInCommitment { inner: unsafe { ObjOps::nonnull_ptr_to_inner((htlc as *const lightning::ln::chan_utils::HTLCOutputInCommitment<>) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_closing_transaction(&self, mut closing_tx: &lightning::ln::chan_utils::ClosingTransaction, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.BaseSign.sign_closing_transaction)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::ClosingTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((closing_tx as *const lightning::ln::chan_utils::ClosingTransaction<>) as *mut _) }, is_owned: false }); + let mut ret = (self.EcdsaChannelSigner.sign_closing_transaction)(self.EcdsaChannelSigner.this_arg, &crate::lightning::ln::chan_utils::ClosingTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((closing_tx as *const lightning::ln::chan_utils::ClosingTransaction<>) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } fn sign_holder_anchor_input(&self, mut anchor_tx: &bitcoin::blockdata::transaction::Transaction, mut input: usize, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { - let mut ret = (self.BaseSign.sign_holder_anchor_input)(self.BaseSign.this_arg, crate::c_types::Transaction::from_bitcoin(anchor_tx), input); + let mut ret = (self.EcdsaChannelSigner.sign_holder_anchor_input)(self.EcdsaChannelSigner.this_arg, crate::c_types::Transaction::from_bitcoin(anchor_tx), input); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } - fn sign_channel_announcement(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result<(bitcoin::secp256k1::ecdsa::Signature, bitcoin::secp256k1::ecdsa::Signature), ()> { - let mut ret = (self.BaseSign.sign_channel_announcement)(self.BaseSign.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::UnsignedChannelAnnouncement<>) as *mut _) }, is_owned: false }); - let mut local_ret = match ret.result_ok { true => Ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).to_rust(); let mut local_ret_0 = (orig_ret_0_0.into_rust(), orig_ret_0_1.into_rust()); local_ret_0 }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; + fn sign_channel_announcement_with_funding_key(&self, mut msg: &lightning::ln::msgs::UnsignedChannelAnnouncement, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> Result { + let mut ret = (self.EcdsaChannelSigner.sign_channel_announcement_with_funding_key)(self.EcdsaChannelSigner.this_arg, &crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::UnsignedChannelAnnouncement<>) as *mut _) }, is_owned: false }); + let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } +} +impl lightning::chain::keysinterface::ChannelSigner for WriteableEcdsaChannelSigner { + fn get_per_commitment_point(&self, mut idx: u64, mut _secp_ctx: &bitcoin::secp256k1::Secp256k1) -> bitcoin::secp256k1::PublicKey { + let mut ret = (self.EcdsaChannelSigner.ChannelSigner.get_per_commitment_point)(self.EcdsaChannelSigner.ChannelSigner.this_arg, idx); + ret.into_rust() + } + fn release_commitment_secret(&self, mut idx: u64) -> [u8; 32] { + let mut ret = (self.EcdsaChannelSigner.ChannelSigner.release_commitment_secret)(self.EcdsaChannelSigner.ChannelSigner.this_arg, idx); + ret.data + } + fn validate_holder_commitment(&self, mut holder_tx: &lightning::ln::chan_utils::HolderCommitmentTransaction, mut preimages: Vec) -> Result<(), ()> { + let mut local_preimages = Vec::new(); for mut item in preimages.drain(..) { local_preimages.push( { crate::c_types::ThirtyTwoBytes { data: item.0 } }); }; + let mut ret = (self.EcdsaChannelSigner.ChannelSigner.validate_holder_commitment)(self.EcdsaChannelSigner.ChannelSigner.this_arg, &crate::lightning::ln::chan_utils::HolderCommitmentTransaction { inner: unsafe { ObjOps::nonnull_ptr_to_inner((holder_tx as *const lightning::ln::chan_utils::HolderCommitmentTransaction<>) as *mut _) }, is_owned: false }, local_preimages.into()); + let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; + local_ret + } + fn pubkeys(&self) -> &lightning::ln::chan_utils::ChannelPublicKeys { + if let Some(f) = self.EcdsaChannelSigner.ChannelSigner.set_pubkeys { + (f)(&self.EcdsaChannelSigner.ChannelSigner); + } + self.EcdsaChannelSigner.ChannelSigner.pubkeys.get_native_ref() + } + fn channel_keys_id(&self) -> [u8; 32] { + let mut ret = (self.EcdsaChannelSigner.ChannelSigner.channel_keys_id)(self.EcdsaChannelSigner.ChannelSigner.this_arg); + ret.data + } fn provide_channel_parameters(&mut self, mut channel_parameters: &lightning::ln::chan_utils::ChannelTransactionParameters) { - (self.BaseSign.provide_channel_parameters)(self.BaseSign.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_parameters as *const lightning::ln::chan_utils::ChannelTransactionParameters<>) as *mut _) }, is_owned: false }) + (self.EcdsaChannelSigner.ChannelSigner.provide_channel_parameters)(self.EcdsaChannelSigner.ChannelSigner.this_arg, &crate::lightning::ln::chan_utils::ChannelTransactionParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_parameters as *const lightning::ln::chan_utils::ChannelTransactionParameters<>) as *mut _) }, is_owned: false }) } } -impl lightning::util::ser::Writeable for Sign { +impl lightning::util::ser::Writeable for WriteableEcdsaChannelSigner { fn write(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> { let vec = (self.write)(self.this_arg); w.write_all(vec.as_slice()) } } -use lightning::chain::keysinterface::Sign as rustSign; -impl rustSign for Sign { +use lightning::chain::keysinterface::WriteableEcdsaChannelSigner as rustWriteableEcdsaChannelSigner; +impl rustWriteableEcdsaChannelSigner for WriteableEcdsaChannelSigner { } // We're essentially a pointer already, or at least a set of pointers, so allow us to be used // directly as a Deref trait in higher-level structs: -impl core::ops::Deref for Sign { +impl core::ops::Deref for WriteableEcdsaChannelSigner { type Target = Self; fn deref(&self) -> &Self { self @@ -1017,8 +1097,8 @@ impl core::ops::Deref for Sign { } /// Calls the free function if one is set #[no_mangle] -pub extern "C" fn Sign_free(this_ptr: Sign) { } -impl Drop for Sign { +pub extern "C" fn WriteableEcdsaChannelSigner_free(this_ptr: WriteableEcdsaChannelSigner) { } +impl Drop for WriteableEcdsaChannelSigner { fn drop(&mut self) { if let Some(f) = self.free { f(self.this_arg); @@ -1027,7 +1107,7 @@ impl Drop for Sign { } /// Specifies the recipient of an invoice. /// -/// This indicates to [`KeysInterface::sign_invoice`] what node secret key should be used to sign +/// This indicates to [`NodeSigner::sign_invoice`] what node secret key should be used to sign /// the invoice. #[derive(Clone)] #[must_use] @@ -1087,56 +1167,191 @@ pub extern "C" fn Recipient_node() -> Recipient { /// Utility method to constructs a new PhantomNode-variant Recipient pub extern "C" fn Recipient_phantom_node() -> Recipient { Recipient::PhantomNode} -/// A trait to describe an object which can get user secrets and key material. +/// A trait that describes a source of entropy. +#[repr(C)] +pub struct EntropySource { + /// An opaque pointer which is passed to your function implementations as an argument. + /// This has no meaning in the LDK, and can be NULL or any other value. + pub this_arg: *mut c_void, + /// Gets a unique, cryptographically-secure, random 32-byte value. This method must return a + /// different value each time it is called. + #[must_use] + pub get_secure_random_bytes: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes, + /// Frees any resources associated with this object given its this_arg pointer. + /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. + pub free: Option, +} +unsafe impl Send for EntropySource {} +unsafe impl Sync for EntropySource {} +#[no_mangle] +pub(crate) extern "C" fn EntropySource_clone_fields(orig: &EntropySource) -> EntropySource { + EntropySource { + this_arg: orig.this_arg, + get_secure_random_bytes: Clone::clone(&orig.get_secure_random_bytes), + free: Clone::clone(&orig.free), + } +} + +use lightning::chain::keysinterface::EntropySource as rustEntropySource; +impl rustEntropySource for EntropySource { + fn get_secure_random_bytes(&self) -> [u8; 32] { + let mut ret = (self.get_secure_random_bytes)(self.this_arg); + ret.data + } +} + +// We're essentially a pointer already, or at least a set of pointers, so allow us to be used +// directly as a Deref trait in higher-level structs: +impl core::ops::Deref for EntropySource { + type Target = Self; + fn deref(&self) -> &Self { + self + } +} +/// Calls the free function if one is set +#[no_mangle] +pub extern "C" fn EntropySource_free(this_ptr: EntropySource) { } +impl Drop for EntropySource { + fn drop(&mut self) { + if let Some(f) = self.free { + f(self.this_arg); + } + } +} +/// A trait that can handle cryptographic operations at the scope level of a node. #[repr(C)] -pub struct KeysInterface { +pub struct NodeSigner { /// An opaque pointer which is passed to your function implementations as an argument. /// This has no meaning in the LDK, and can be NULL or any other value. pub this_arg: *mut c_void, - /// Get node secret key based on the provided [`Recipient`]. + /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data. /// - /// The `node_id`/`network_key` is the public key that corresponds to this secret key. + /// If the implementor of this trait supports [phantom node payments], then every node that is + /// intended to be included in the phantom invoice route hints must return the same value from + /// this method. /// - /// This method must return the same value each time it is called with a given [`Recipient`] - /// parameter. + /// This method must return the same value each time it is called. /// - /// Errors if the [`Recipient`] variant is not supported by the implementation. + /// [phantom node payments]: PhantomKeysManager #[must_use] - pub get_node_secret: extern "C" fn (this_arg: *const c_void, recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_SecretKeyNoneZ, - /// Get node id based on the provided [`Recipient`]. This public key corresponds to the secret in - /// [`get_node_secret`]. + pub get_inbound_payment_key_material: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes, + /// Get node id based on the provided [`Recipient`]. /// /// This method must return the same value each time it is called with a given [`Recipient`] /// parameter. /// /// Errors if the [`Recipient`] variant is not supported by the implementation. - /// - /// [`get_node_secret`]: Self::get_node_secret #[must_use] pub get_node_id: extern "C" fn (this_arg: *const c_void, recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_PublicKeyNoneZ, - /// Gets the ECDH shared secret of our [`node secret`] and `other_key`, multiplying by `tweak` if + /// Gets the ECDH shared secret of our node secret and `other_key`, multiplying by `tweak` if /// one is provided. Note that this tweak can be applied to `other_key` instead of our node /// secret, though this is less efficient. /// - /// Errors if the [`Recipient`] variant is not supported by the implementation. + /// Note that if this fails while attempting to forward an HTLC, LDK will panic. The error + /// should be resolved to allow LDK to resume forwarding HTLCs. /// - /// [`node secret`]: Self::get_node_secret + /// Errors if the [`Recipient`] variant is not supported by the implementation. #[must_use] pub ecdh: extern "C" fn (this_arg: *const c_void, recipient: crate::lightning::chain::keysinterface::Recipient, other_key: crate::c_types::PublicKey, tweak: crate::c_types::derived::COption_ScalarZ) -> crate::c_types::derived::CResult_SharedSecretNoneZ, - /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs. + /// Sign an invoice. /// - /// This method should return a different value each time it is called, to avoid linking - /// on-chain funds across channels as controlled to the same user. + /// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of + /// this trait to parse the invoice and make sure they're signing what they expect, rather than + /// blindly signing the hash. + /// + /// The `hrp_bytes` are ASCII bytes, while the `invoice_data` is base32. + /// + /// The secret key used to sign the invoice is dependent on the [`Recipient`]. + /// + /// Errors if the [`Recipient`] variant is not supported by the implementation. #[must_use] - pub get_destination_script: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z, - /// Get a script pubkey which we will send funds to when closing a channel. + pub sign_invoice: extern "C" fn (this_arg: *const c_void, hrp_bytes: crate::c_types::u8slice, invoice_data: crate::c_types::derived::CVec_U5Z, recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_RecoverableSignatureNoneZ, + /// Sign a gossip message. /// - /// This method should return a different value each time it is called, to avoid linking - /// on-chain funds across channels as controlled to the same user. + /// Note that if this fails, LDK may panic and the message will not be broadcast to the network + /// or a possible channel counterparty. If LDK panics, the error should be resolved to allow the + /// message to be broadcast, as otherwise it may prevent one from receiving funds over the + /// corresponding channel. #[must_use] - pub get_shutdown_scriptpubkey: extern "C" fn (this_arg: *const c_void) -> crate::lightning::ln::script::ShutdownScript, - /// Get a new set of [`Sign`] for per-channel secrets. These MUST be unique even if you - /// restarted with some stale data! + pub sign_gossip_message: extern "C" fn (this_arg: *const c_void, msg: crate::lightning::ln::msgs::UnsignedGossipMessage) -> crate::c_types::derived::CResult_SignatureNoneZ, + /// Frees any resources associated with this object given its this_arg pointer. + /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. + pub free: Option, +} +unsafe impl Send for NodeSigner {} +unsafe impl Sync for NodeSigner {} +#[no_mangle] +pub(crate) extern "C" fn NodeSigner_clone_fields(orig: &NodeSigner) -> NodeSigner { + NodeSigner { + this_arg: orig.this_arg, + get_inbound_payment_key_material: Clone::clone(&orig.get_inbound_payment_key_material), + get_node_id: Clone::clone(&orig.get_node_id), + ecdh: Clone::clone(&orig.ecdh), + sign_invoice: Clone::clone(&orig.sign_invoice), + sign_gossip_message: Clone::clone(&orig.sign_gossip_message), + free: Clone::clone(&orig.free), + } +} + +use lightning::chain::keysinterface::NodeSigner as rustNodeSigner; +impl rustNodeSigner for NodeSigner { + fn get_inbound_payment_key_material(&self) -> lightning::chain::keysinterface::KeyMaterial { + let mut ret = (self.get_inbound_payment_key_material)(self.this_arg); + ::lightning::chain::keysinterface::KeyMaterial(ret.data) + } + fn get_node_id(&self, mut recipient: lightning::chain::keysinterface::Recipient) -> Result { + let mut ret = (self.get_node_id)(self.this_arg, crate::lightning::chain::keysinterface::Recipient::native_into(recipient)); + let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; + local_ret + } + fn ecdh(&self, mut recipient: lightning::chain::keysinterface::Recipient, mut other_key: &bitcoin::secp256k1::PublicKey, mut tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result { + let mut local_tweak = if tweak.is_none() { crate::c_types::derived::COption_ScalarZ::None } else { crate::c_types::derived::COption_ScalarZ::Some(/* WARNING: CLONING CONVERSION HERE! &Option is otherwise un-expressable. */ { crate::c_types::BigEndianScalar::from_rust(tweak.clone().unwrap()) }) }; + let mut ret = (self.ecdh)(self.this_arg, crate::lightning::chain::keysinterface::Recipient::native_into(recipient), crate::c_types::PublicKey::from_rust(&other_key), local_tweak); + let mut local_ret = match ret.result_ok { true => Ok( { ::bitcoin::secp256k1::ecdh::SharedSecret::from_bytes((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).data) }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; + local_ret + } + fn sign_invoice(&self, mut hrp_bytes: &[u8], mut invoice_data: &[bitcoin::bech32::u5], mut recipient: lightning::chain::keysinterface::Recipient) -> Result { + let mut local_hrp_bytes = crate::c_types::u8slice::from_slice(hrp_bytes); + let mut local_invoice_data_clone = Vec::new(); local_invoice_data_clone.extend_from_slice(invoice_data); let mut invoice_data = local_invoice_data_clone; let mut local_invoice_data = Vec::new(); for mut item in invoice_data.drain(..) { local_invoice_data.push( { item.into() }); }; + let mut ret = (self.sign_invoice)(self.this_arg, local_hrp_bytes, local_invoice_data.into(), crate::lightning::chain::keysinterface::Recipient::native_into(recipient)); + let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; + local_ret + } + fn sign_gossip_message(&self, mut msg: lightning::ln::msgs::UnsignedGossipMessage) -> Result { + let mut ret = (self.sign_gossip_message)(self.this_arg, crate::lightning::ln::msgs::UnsignedGossipMessage::native_into(msg)); + let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; + local_ret + } +} + +// We're essentially a pointer already, or at least a set of pointers, so allow us to be used +// directly as a Deref trait in higher-level structs: +impl core::ops::Deref for NodeSigner { + type Target = Self; + fn deref(&self) -> &Self { + self + } +} +/// Calls the free function if one is set +#[no_mangle] +pub extern "C" fn NodeSigner_free(this_ptr: NodeSigner) { } +impl Drop for NodeSigner { + fn drop(&mut self) { + if let Some(f) = self.free { + f(self.this_arg); + } + } +} +/// A trait that can return signer instances for individual channels. +#[repr(C)] +pub struct SignerProvider { + /// An opaque pointer which is passed to your function implementations as an argument. + /// This has no meaning in the LDK, and can be NULL or any other value. + pub this_arg: *mut c_void, + /// Generates a unique `channel_keys_id` that can be used to obtain a [`Self::Signer`] through + /// [`SignerProvider::derive_channel_signer`]. The `user_channel_id` is provided to allow + /// implementations of [`SignerProvider`] to maintain a mapping between itself and the generated + /// `channel_keys_id`. /// /// This method must return a different value each time it is called. #[must_use] @@ -1144,21 +1359,14 @@ pub struct KeysInterface { /// Derives the private key material backing a `Signer`. /// /// To derive a new `Signer`, a fresh `channel_keys_id` should be obtained through - /// [`KeysInterface::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be + /// [`SignerProvider::generate_channel_keys_id`]. Otherwise, an existing `Signer` can be /// re-derived from its `channel_keys_id`, which can be obtained through its trait method - /// [`BaseSign::channel_keys_id`]. + /// [`ChannelSigner::channel_keys_id`]. #[must_use] - pub derive_channel_signer: extern "C" fn (this_arg: *const c_void, channel_value_satoshis: u64, channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::Sign, - /// Gets a unique, cryptographically-secure, random 32 byte value. This is used for encrypting - /// onion packets and for temporary channel IDs. There is no requirement that these be - /// persisted anywhere, though they must be unique across restarts. - /// - /// This method must return a different value each time it is called. - #[must_use] - pub get_secure_random_bytes: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes, - /// Reads a [`Signer`] for this [`KeysInterface`] from the given input stream. + pub derive_channel_signer: extern "C" fn (this_arg: *const c_void, channel_value_satoshis: u64, channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner, + /// Reads a [`Signer`] for this [`SignerProvider`] from the given input stream. /// This is only called during deserialization of other objects which contain - /// [`Sign`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s). + /// [`WriteableEcdsaChannelSigner`]-implementing objects (i.e., [`ChannelMonitor`]s and [`ChannelManager`]s). /// The bytes are exactly those which `::write()` writes, and /// contain no versioning scheme. You may wish to include your own version prefix and ensure /// you've read all of the provided bytes to ensure no corruption occurred. @@ -1170,115 +1378,68 @@ pub struct KeysInterface { /// [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor /// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager #[must_use] - pub read_chan_signer: extern "C" fn (this_arg: *const c_void, reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ, - /// Sign an invoice. - /// By parameterizing by the raw invoice bytes instead of the hash, we allow implementors of - /// this trait to parse the invoice and make sure they're signing what they expect, rather than - /// blindly signing the hash. - /// The `hrp` is ASCII bytes, while the invoice data is base32-encoded. - /// - /// The secret key used to sign the invoice is dependent on the [`Recipient`]. + pub read_chan_signer: extern "C" fn (this_arg: *const c_void, reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_WriteableEcdsaChannelSignerDecodeErrorZ, + /// Get a script pubkey which we send funds to when claiming on-chain contestable outputs. /// - /// Errors if the [`Recipient`] variant is not supported by the implementation. + /// This method should return a different value each time it is called, to avoid linking + /// on-chain funds across channels as controlled to the same user. #[must_use] - pub sign_invoice: extern "C" fn (this_arg: *const c_void, hrp_bytes: crate::c_types::u8slice, invoice_data: crate::c_types::derived::CVec_U5Z, receipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_RecoverableSignatureNoneZ, - /// Get secret key material as bytes for use in encrypting and decrypting inbound payment data. - /// - /// If the implementor of this trait supports [phantom node payments], then every node that is - /// intended to be included in the phantom invoice route hints must return the same value from - /// this method. - /// - /// This method must return the same value each time it is called. + pub get_destination_script: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z, + /// Get a script pubkey which we will send funds to when closing a channel. /// - /// [phantom node payments]: PhantomKeysManager + /// This method should return a different value each time it is called, to avoid linking + /// on-chain funds across channels as controlled to the same user. #[must_use] - pub get_inbound_payment_key_material: extern "C" fn (this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes, + pub get_shutdown_scriptpubkey: extern "C" fn (this_arg: *const c_void) -> crate::lightning::ln::script::ShutdownScript, /// Frees any resources associated with this object given its this_arg pointer. /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. pub free: Option, } -unsafe impl Send for KeysInterface {} -unsafe impl Sync for KeysInterface {} +unsafe impl Send for SignerProvider {} +unsafe impl Sync for SignerProvider {} #[no_mangle] -pub(crate) extern "C" fn KeysInterface_clone_fields(orig: &KeysInterface) -> KeysInterface { - KeysInterface { +pub(crate) extern "C" fn SignerProvider_clone_fields(orig: &SignerProvider) -> SignerProvider { + SignerProvider { this_arg: orig.this_arg, - get_node_secret: Clone::clone(&orig.get_node_secret), - get_node_id: Clone::clone(&orig.get_node_id), - ecdh: Clone::clone(&orig.ecdh), - get_destination_script: Clone::clone(&orig.get_destination_script), - get_shutdown_scriptpubkey: Clone::clone(&orig.get_shutdown_scriptpubkey), generate_channel_keys_id: Clone::clone(&orig.generate_channel_keys_id), derive_channel_signer: Clone::clone(&orig.derive_channel_signer), - get_secure_random_bytes: Clone::clone(&orig.get_secure_random_bytes), read_chan_signer: Clone::clone(&orig.read_chan_signer), - sign_invoice: Clone::clone(&orig.sign_invoice), - get_inbound_payment_key_material: Clone::clone(&orig.get_inbound_payment_key_material), + get_destination_script: Clone::clone(&orig.get_destination_script), + get_shutdown_scriptpubkey: Clone::clone(&orig.get_shutdown_scriptpubkey), free: Clone::clone(&orig.free), } } -use lightning::chain::keysinterface::KeysInterface as rustKeysInterface; -impl rustKeysInterface for KeysInterface { - type Signer = crate::lightning::chain::keysinterface::Sign; - fn get_node_secret(&self, mut recipient: lightning::chain::keysinterface::Recipient) -> Result { - let mut ret = (self.get_node_secret)(self.this_arg, crate::lightning::chain::keysinterface::Recipient::native_into(recipient)); - let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; - local_ret - } - fn get_node_id(&self, mut recipient: lightning::chain::keysinterface::Recipient) -> Result { - let mut ret = (self.get_node_id)(self.this_arg, crate::lightning::chain::keysinterface::Recipient::native_into(recipient)); - let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; - local_ret - } - fn ecdh(&self, mut recipient: lightning::chain::keysinterface::Recipient, mut other_key: &bitcoin::secp256k1::PublicKey, mut tweak: Option<&bitcoin::secp256k1::Scalar>) -> Result { - let mut local_tweak = if tweak.is_none() { crate::c_types::derived::COption_ScalarZ::None } else { crate::c_types::derived::COption_ScalarZ::Some(/* WARNING: CLONING CONVERSION HERE! &Option is otherwise un-expressable. */ { crate::c_types::BigEndianScalar::from_rust(tweak.clone().unwrap()) }) }; - let mut ret = (self.ecdh)(self.this_arg, crate::lightning::chain::keysinterface::Recipient::native_into(recipient), crate::c_types::PublicKey::from_rust(&other_key), local_tweak); - let mut local_ret = match ret.result_ok { true => Ok( { ::bitcoin::secp256k1::ecdh::SharedSecret::from_bytes((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).data) }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; - local_ret - } - fn get_destination_script(&self) -> bitcoin::blockdata::script::Script { - let mut ret = (self.get_destination_script)(self.this_arg); - ::bitcoin::blockdata::script::Script::from(ret.into_rust()) - } - fn get_shutdown_scriptpubkey(&self) -> lightning::ln::script::ShutdownScript { - let mut ret = (self.get_shutdown_scriptpubkey)(self.this_arg); - *unsafe { Box::from_raw(ret.take_inner()) } - } +use lightning::chain::keysinterface::SignerProvider as rustSignerProvider; +impl rustSignerProvider for SignerProvider { + type Signer = crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner; fn generate_channel_keys_id(&self, mut inbound: bool, mut channel_value_satoshis: u64, mut user_channel_id: u128) -> [u8; 32] { let mut ret = (self.generate_channel_keys_id)(self.this_arg, inbound, channel_value_satoshis, user_channel_id.into()); ret.data } - fn derive_channel_signer(&self, mut channel_value_satoshis: u64, mut channel_keys_id: [u8; 32]) -> crate::lightning::chain::keysinterface::Sign { + fn derive_channel_signer(&self, mut channel_value_satoshis: u64, mut channel_keys_id: [u8; 32]) -> crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner { let mut ret = (self.derive_channel_signer)(self.this_arg, channel_value_satoshis, crate::c_types::ThirtyTwoBytes { data: channel_keys_id }); ret } - fn get_secure_random_bytes(&self) -> [u8; 32] { - let mut ret = (self.get_secure_random_bytes)(self.this_arg); - ret.data - } - fn read_chan_signer(&self, mut reader: &[u8]) -> Result { + fn read_chan_signer(&self, mut reader: &[u8]) -> Result { let mut local_reader = crate::c_types::u8slice::from_slice(reader); let mut ret = (self.read_chan_signer)(self.this_arg, local_reader); let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }) }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; local_ret } - fn sign_invoice(&self, mut hrp_bytes: &[u8], mut invoice_data: &[bitcoin::bech32::u5], mut receipient: lightning::chain::keysinterface::Recipient) -> Result { - let mut local_hrp_bytes = crate::c_types::u8slice::from_slice(hrp_bytes); - let mut local_invoice_data_clone = Vec::new(); local_invoice_data_clone.extend_from_slice(invoice_data); let mut invoice_data = local_invoice_data_clone; let mut local_invoice_data = Vec::new(); for mut item in invoice_data.drain(..) { local_invoice_data.push( { item.into() }); }; - let mut ret = (self.sign_invoice)(self.this_arg, local_hrp_bytes, local_invoice_data.into(), crate::lightning::chain::keysinterface::Recipient::native_into(receipient)); - let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; - local_ret + fn get_destination_script(&self) -> bitcoin::blockdata::script::Script { + let mut ret = (self.get_destination_script)(self.this_arg); + ::bitcoin::blockdata::script::Script::from(ret.into_rust()) } - fn get_inbound_payment_key_material(&self) -> lightning::chain::keysinterface::KeyMaterial { - let mut ret = (self.get_inbound_payment_key_material)(self.this_arg); - ::lightning::chain::keysinterface::KeyMaterial(ret.data) + fn get_shutdown_scriptpubkey(&self) -> lightning::ln::script::ShutdownScript { + let mut ret = (self.get_shutdown_scriptpubkey)(self.this_arg); + *unsafe { Box::from_raw(ret.take_inner()) } } } // We're essentially a pointer already, or at least a set of pointers, so allow us to be used // directly as a Deref trait in higher-level structs: -impl core::ops::Deref for KeysInterface { +impl core::ops::Deref for SignerProvider { type Target = Self; fn deref(&self) -> &Self { self @@ -1286,8 +1447,8 @@ impl core::ops::Deref for KeysInterface { } /// Calls the free function if one is set #[no_mangle] -pub extern "C" fn KeysInterface_free(this_ptr: KeysInterface) { } -impl Drop for KeysInterface { +pub extern "C" fn SignerProvider_free(this_ptr: SignerProvider) { } +impl Drop for SignerProvider { fn drop(&mut self) { if let Some(f) = self.free { f(self.this_arg); @@ -1298,7 +1459,7 @@ impl Drop for KeysInterface { use lightning::chain::keysinterface::InMemorySigner as nativeInMemorySignerImport; pub(crate) type nativeInMemorySigner = nativeInMemorySignerImport; -/// A simple implementation of [`Sign`] that just keeps the private keys in memory. +/// A simple implementation of [`WriteableEcdsaChannelSigner`] that just keeps the private keys in memory. /// /// This implementation performs no policy checks and is insufficient by itself as /// a secure external signer. @@ -1438,14 +1599,14 @@ pub extern "C" fn InMemorySigner_clone(orig: &InMemorySigner) -> InMemorySigner /// Creates a new [`InMemorySigner`]. #[must_use] #[no_mangle] -pub extern "C" fn InMemorySigner_new(mut node_secret: crate::c_types::SecretKey, mut funding_key: crate::c_types::SecretKey, mut revocation_base_key: crate::c_types::SecretKey, mut payment_key: crate::c_types::SecretKey, mut delayed_payment_base_key: crate::c_types::SecretKey, mut htlc_base_key: crate::c_types::SecretKey, mut commitment_seed: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::InMemorySigner { - let mut ret = lightning::chain::keysinterface::InMemorySigner::new(secp256k1::global::SECP256K1, node_secret.into_rust(), funding_key.into_rust(), revocation_base_key.into_rust(), payment_key.into_rust(), delayed_payment_base_key.into_rust(), htlc_base_key.into_rust(), commitment_seed.data, channel_value_satoshis, channel_keys_id.data); +pub extern "C" fn InMemorySigner_new(mut funding_key: crate::c_types::SecretKey, mut revocation_base_key: crate::c_types::SecretKey, mut payment_key: crate::c_types::SecretKey, mut delayed_payment_base_key: crate::c_types::SecretKey, mut htlc_base_key: crate::c_types::SecretKey, mut commitment_seed: crate::c_types::ThirtyTwoBytes, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::InMemorySigner { + let mut ret = lightning::chain::keysinterface::InMemorySigner::new(secp256k1::global::SECP256K1, funding_key.into_rust(), revocation_base_key.into_rust(), payment_key.into_rust(), delayed_payment_base_key.into_rust(), htlc_base_key.into_rust(), commitment_seed.data, channel_value_satoshis, channel_keys_id.data); crate::lightning::chain::keysinterface::InMemorySigner { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Returns the counterparty's pubkeys. /// -/// Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. +/// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_counterparty_pubkeys(this_arg: &crate::lightning::chain::keysinterface::InMemorySigner) -> crate::lightning::ln::chan_utils::ChannelPublicKeys { @@ -1457,7 +1618,7 @@ pub extern "C" fn InMemorySigner_counterparty_pubkeys(this_arg: &crate::lightnin /// transactions, i.e., the amount of time that we have to wait to recover our funds if we /// broadcast a transaction. /// -/// Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. +/// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_counterparty_selected_contest_delay(this_arg: &crate::lightning::chain::keysinterface::InMemorySigner) -> u16 { @@ -1469,7 +1630,7 @@ pub extern "C" fn InMemorySigner_counterparty_selected_contest_delay(this_arg: & /// by our counterparty, i.e., the amount of time that they have to wait to recover their funds /// if they broadcast a transaction. /// -/// Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. +/// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_holder_selected_contest_delay(this_arg: &crate::lightning::chain::keysinterface::InMemorySigner) -> u16 { @@ -1479,7 +1640,7 @@ pub extern "C" fn InMemorySigner_holder_selected_contest_delay(this_arg: &crate: /// Returns whether the holder is the initiator. /// -/// Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. +/// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_is_outbound(this_arg: &crate::lightning::chain::keysinterface::InMemorySigner) -> bool { @@ -1489,7 +1650,7 @@ pub extern "C" fn InMemorySigner_is_outbound(this_arg: &crate::lightning::chain: /// Funding outpoint /// -/// Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. +/// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_funding_outpoint(this_arg: &crate::lightning::chain::keysinterface::InMemorySigner) -> crate::lightning::chain::transaction::OutPoint { @@ -1500,7 +1661,7 @@ pub extern "C" fn InMemorySigner_funding_outpoint(this_arg: &crate::lightning::c /// Returns a [`ChannelTransactionParameters`] for this channel, to be used when verifying or /// building transactions. /// -/// Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. +/// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &crate::lightning::chain::keysinterface::InMemorySigner) -> crate::lightning::ln::chan_utils::ChannelTransactionParameters { @@ -1510,7 +1671,7 @@ pub extern "C" fn InMemorySigner_get_channel_parameters(this_arg: &crate::lightn /// Returns whether anchors should be used. /// -/// Will panic if [`BaseSign::provide_channel_parameters`] has not been called before. +/// Will panic if [`ChannelSigner::provide_channel_parameters`] has not been called before. #[must_use] #[no_mangle] pub extern "C" fn InMemorySigner_opt_anchors(this_arg: &crate::lightning::chain::keysinterface::InMemorySigner) -> bool { @@ -1552,173 +1713,210 @@ pub extern "C" fn InMemorySigner_sign_dynamic_p2wsh_input(this_arg: &crate::ligh local_ret } -impl From for crate::lightning::chain::keysinterface::BaseSign { +impl From for crate::lightning::chain::keysinterface::ChannelSigner { fn from(obj: nativeInMemorySigner) -> Self { let mut rust_obj = InMemorySigner { inner: ObjOps::heap_alloc(obj), is_owned: true }; - let mut ret = InMemorySigner_as_BaseSign(&rust_obj); + let mut ret = InMemorySigner_as_ChannelSigner(&rust_obj); // 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 rust_obj.inner = core::ptr::null_mut(); ret.free = Some(InMemorySigner_free_void); ret } } -/// Constructs a new BaseSign which calls the relevant methods on this_arg. -/// This copies the `inner` pointer in this_arg and thus the returned BaseSign must be freed before this_arg is +/// Constructs a new ChannelSigner which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned ChannelSigner must be freed before this_arg is #[no_mangle] -pub extern "C" fn InMemorySigner_as_BaseSign(this_arg: &InMemorySigner) -> crate::lightning::chain::keysinterface::BaseSign { - crate::lightning::chain::keysinterface::BaseSign { +pub extern "C" fn InMemorySigner_as_ChannelSigner(this_arg: &InMemorySigner) -> crate::lightning::chain::keysinterface::ChannelSigner { + crate::lightning::chain::keysinterface::ChannelSigner { this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, - get_per_commitment_point: InMemorySigner_BaseSign_get_per_commitment_point, - release_commitment_secret: InMemorySigner_BaseSign_release_commitment_secret, - validate_holder_commitment: InMemorySigner_BaseSign_validate_holder_commitment, + get_per_commitment_point: InMemorySigner_ChannelSigner_get_per_commitment_point, + release_commitment_secret: InMemorySigner_ChannelSigner_release_commitment_secret, + validate_holder_commitment: InMemorySigner_ChannelSigner_validate_holder_commitment, pubkeys: crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: core::ptr::null_mut(), is_owned: true }, - set_pubkeys: Some(InMemorySigner_BaseSign_set_pubkeys), - channel_keys_id: InMemorySigner_BaseSign_channel_keys_id, - sign_counterparty_commitment: InMemorySigner_BaseSign_sign_counterparty_commitment, - validate_counterparty_revocation: InMemorySigner_BaseSign_validate_counterparty_revocation, - sign_holder_commitment_and_htlcs: InMemorySigner_BaseSign_sign_holder_commitment_and_htlcs, - sign_justice_revoked_output: InMemorySigner_BaseSign_sign_justice_revoked_output, - sign_justice_revoked_htlc: InMemorySigner_BaseSign_sign_justice_revoked_htlc, - sign_counterparty_htlc_transaction: InMemorySigner_BaseSign_sign_counterparty_htlc_transaction, - sign_closing_transaction: InMemorySigner_BaseSign_sign_closing_transaction, - sign_holder_anchor_input: InMemorySigner_BaseSign_sign_holder_anchor_input, - sign_channel_announcement: InMemorySigner_BaseSign_sign_channel_announcement, - provide_channel_parameters: InMemorySigner_BaseSign_provide_channel_parameters, + set_pubkeys: Some(InMemorySigner_ChannelSigner_set_pubkeys), + channel_keys_id: InMemorySigner_ChannelSigner_channel_keys_id, + provide_channel_parameters: InMemorySigner_ChannelSigner_provide_channel_parameters, } } #[must_use] -extern "C" fn InMemorySigner_BaseSign_get_per_commitment_point(this_arg: *const c_void, mut idx: u64) -> crate::c_types::PublicKey { - let mut ret = >::get_per_commitment_point(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, idx, secp256k1::global::SECP256K1); +extern "C" fn InMemorySigner_ChannelSigner_get_per_commitment_point(this_arg: *const c_void, mut idx: u64) -> crate::c_types::PublicKey { + let mut ret = >::get_per_commitment_point(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, idx, secp256k1::global::SECP256K1); crate::c_types::PublicKey::from_rust(&ret) } #[must_use] -extern "C" fn InMemorySigner_BaseSign_release_commitment_secret(this_arg: *const c_void, mut idx: u64) -> crate::c_types::ThirtyTwoBytes { - let mut ret = >::release_commitment_secret(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, idx); +extern "C" fn InMemorySigner_ChannelSigner_release_commitment_secret(this_arg: *const c_void, mut idx: u64) -> crate::c_types::ThirtyTwoBytes { + let mut ret = >::release_commitment_secret(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, idx); crate::c_types::ThirtyTwoBytes { data: ret } } #[must_use] -extern "C" fn InMemorySigner_BaseSign_validate_holder_commitment(this_arg: *const c_void, holder_tx: &crate::lightning::ln::chan_utils::HolderCommitmentTransaction, mut preimages: crate::c_types::derived::CVec_PaymentPreimageZ) -> crate::c_types::derived::CResult_NoneNoneZ { +extern "C" fn InMemorySigner_ChannelSigner_validate_holder_commitment(this_arg: *const c_void, holder_tx: &crate::lightning::ln::chan_utils::HolderCommitmentTransaction, mut preimages: crate::c_types::derived::CVec_PaymentPreimageZ) -> crate::c_types::derived::CResult_NoneNoneZ { let mut local_preimages = Vec::new(); for mut item in preimages.into_rust().drain(..) { local_preimages.push( { ::lightning::ln::PaymentPreimage(item.data) }); }; - let mut ret = >::validate_holder_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, holder_tx.get_native_ref(), local_preimages); + let mut ret = >::validate_holder_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, holder_tx.get_native_ref(), local_preimages); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn InMemorySigner_BaseSign_pubkeys(this_arg: *const c_void) -> crate::lightning::ln::chan_utils::ChannelPublicKeys { - let mut ret = >::pubkeys(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, ); +extern "C" fn InMemorySigner_ChannelSigner_pubkeys(this_arg: *const c_void) -> crate::lightning::ln::chan_utils::ChannelPublicKeys { + let mut ret = >::pubkeys(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, ); crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: unsafe { ObjOps::nonnull_ptr_to_inner((ret as *const lightning::ln::chan_utils::ChannelPublicKeys<>) as *mut _) }, is_owned: false } } -extern "C" fn InMemorySigner_BaseSign_set_pubkeys(trait_self_arg: &BaseSign) { +extern "C" fn InMemorySigner_ChannelSigner_set_pubkeys(trait_self_arg: &ChannelSigner) { // This is a bit race-y in the general case, but for our specific use-cases today, we're safe // Specifically, we must ensure that the first time we're called it can never be in parallel if trait_self_arg.pubkeys.inner.is_null() { - unsafe { &mut *(trait_self_arg as *const BaseSign as *mut BaseSign) }.pubkeys = InMemorySigner_BaseSign_pubkeys(trait_self_arg.this_arg); + unsafe { &mut *(trait_self_arg as *const ChannelSigner as *mut ChannelSigner) }.pubkeys = InMemorySigner_ChannelSigner_pubkeys(trait_self_arg.this_arg); } } #[must_use] -extern "C" fn InMemorySigner_BaseSign_channel_keys_id(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { - let mut ret = >::channel_keys_id(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, ); +extern "C" fn InMemorySigner_ChannelSigner_channel_keys_id(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { + let mut ret = >::channel_keys_id(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, ); crate::c_types::ThirtyTwoBytes { data: ret } } +extern "C" fn InMemorySigner_ChannelSigner_provide_channel_parameters(this_arg: *mut c_void, channel_parameters: &crate::lightning::ln::chan_utils::ChannelTransactionParameters) { + >::provide_channel_parameters(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, channel_parameters.get_native_ref()) +} + +impl From for crate::lightning::chain::keysinterface::EcdsaChannelSigner { + fn from(obj: nativeInMemorySigner) -> Self { + let mut rust_obj = InMemorySigner { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = InMemorySigner_as_EcdsaChannelSigner(&rust_obj); + // 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 + rust_obj.inner = core::ptr::null_mut(); + ret.free = Some(InMemorySigner_free_void); + ret + } +} +/// Constructs a new EcdsaChannelSigner which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned EcdsaChannelSigner must be freed before this_arg is +#[no_mangle] +pub extern "C" fn InMemorySigner_as_EcdsaChannelSigner(this_arg: &InMemorySigner) -> crate::lightning::chain::keysinterface::EcdsaChannelSigner { + crate::lightning::chain::keysinterface::EcdsaChannelSigner { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + sign_counterparty_commitment: InMemorySigner_EcdsaChannelSigner_sign_counterparty_commitment, + validate_counterparty_revocation: InMemorySigner_EcdsaChannelSigner_validate_counterparty_revocation, + sign_holder_commitment_and_htlcs: InMemorySigner_EcdsaChannelSigner_sign_holder_commitment_and_htlcs, + sign_justice_revoked_output: InMemorySigner_EcdsaChannelSigner_sign_justice_revoked_output, + sign_justice_revoked_htlc: InMemorySigner_EcdsaChannelSigner_sign_justice_revoked_htlc, + sign_counterparty_htlc_transaction: InMemorySigner_EcdsaChannelSigner_sign_counterparty_htlc_transaction, + sign_closing_transaction: InMemorySigner_EcdsaChannelSigner_sign_closing_transaction, + sign_holder_anchor_input: InMemorySigner_EcdsaChannelSigner_sign_holder_anchor_input, + sign_channel_announcement_with_funding_key: InMemorySigner_EcdsaChannelSigner_sign_channel_announcement_with_funding_key, + ChannelSigner: crate::lightning::chain::keysinterface::ChannelSigner { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + get_per_commitment_point: InMemorySigner_ChannelSigner_get_per_commitment_point, + release_commitment_secret: InMemorySigner_ChannelSigner_release_commitment_secret, + validate_holder_commitment: InMemorySigner_ChannelSigner_validate_holder_commitment, + + pubkeys: crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: core::ptr::null_mut(), is_owned: true }, + set_pubkeys: Some(InMemorySigner_ChannelSigner_set_pubkeys), + channel_keys_id: InMemorySigner_ChannelSigner_channel_keys_id, + provide_channel_parameters: InMemorySigner_ChannelSigner_provide_channel_parameters, + }, + } +} + #[must_use] -extern "C" fn InMemorySigner_BaseSign_sign_counterparty_commitment(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::CommitmentTransaction, mut preimages: crate::c_types::derived::CVec_PaymentPreimageZ) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { +extern "C" fn InMemorySigner_EcdsaChannelSigner_sign_counterparty_commitment(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::CommitmentTransaction, mut preimages: crate::c_types::derived::CVec_PaymentPreimageZ) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { let mut local_preimages = Vec::new(); for mut item in preimages.into_rust().drain(..) { local_preimages.push( { ::lightning::ln::PaymentPreimage(item.data) }); }; - let mut ret = >::sign_counterparty_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, commitment_tx.get_native_ref(), local_preimages, secp256k1::global::SECP256K1); + let mut ret = >::sign_counterparty_commitment(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, commitment_tx.get_native_ref(), local_preimages, secp256k1::global::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn InMemorySigner_BaseSign_validate_counterparty_revocation(this_arg: *const c_void, mut idx: u64, secret: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneNoneZ { - let mut ret = >::validate_counterparty_revocation(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, idx, &::bitcoin::secp256k1::SecretKey::from_slice(&unsafe { *secret}[..]).unwrap()); +extern "C" fn InMemorySigner_EcdsaChannelSigner_validate_counterparty_revocation(this_arg: *const c_void, mut idx: u64, secret: *const [u8; 32]) -> crate::c_types::derived::CResult_NoneNoneZ { + let mut ret = >::validate_counterparty_revocation(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, idx, &::bitcoin::secp256k1::SecretKey::from_slice(&unsafe { *secret}[..]).unwrap()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn InMemorySigner_BaseSign_sign_holder_commitment_and_htlcs(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { - let mut ret = >::sign_holder_commitment_and_htlcs(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, commitment_tx.get_native_ref(), secp256k1::global::SECP256K1); +extern "C" fn InMemorySigner_EcdsaChannelSigner_sign_holder_commitment_and_htlcs(this_arg: *const c_void, commitment_tx: &crate::lightning::ln::chan_utils::HolderCommitmentTransaction) -> crate::c_types::derived::CResult_C2Tuple_SignatureCVec_SignatureZZNoneZ { + let mut ret = >::sign_holder_commitment_and_htlcs(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, commitment_tx.get_native_ref(), secp256k1::global::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_orig_ret_0_1 = Vec::new(); for mut item in orig_ret_0_1.drain(..) { local_orig_ret_0_1.push( { crate::c_types::Signature::from_rust(&item) }); }; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), local_orig_ret_0_1.into()).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn InMemorySigner_BaseSign_sign_justice_revoked_output(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32]) -> crate::c_types::derived::CResult_SignatureNoneZ { - let mut ret = >::sign_justice_revoked_output(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), secp256k1::global::SECP256K1); +extern "C" fn InMemorySigner_EcdsaChannelSigner_sign_justice_revoked_output(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32]) -> crate::c_types::derived::CResult_SignatureNoneZ { + let mut ret = >::sign_justice_revoked_output(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), secp256k1::global::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn InMemorySigner_BaseSign_sign_justice_revoked_htlc(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ { - let mut ret = >::sign_justice_revoked_htlc(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), htlc.get_native_ref(), secp256k1::global::SECP256K1); +extern "C" fn InMemorySigner_EcdsaChannelSigner_sign_justice_revoked_htlc(this_arg: *const c_void, mut justice_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, per_commitment_key: *const [u8; 32], htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ { + let mut ret = >::sign_justice_revoked_htlc(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &justice_tx.into_bitcoin(), input, amount, &::bitcoin::secp256k1::SecretKey::from_slice(&unsafe { *per_commitment_key}[..]).unwrap(), htlc.get_native_ref(), secp256k1::global::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn InMemorySigner_BaseSign_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ { - let mut ret = >::sign_counterparty_htlc_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), htlc.get_native_ref(), secp256k1::global::SECP256K1); +extern "C" fn InMemorySigner_EcdsaChannelSigner_sign_counterparty_htlc_transaction(this_arg: *const c_void, mut htlc_tx: crate::c_types::Transaction, mut input: usize, mut amount: u64, mut per_commitment_point: crate::c_types::PublicKey, htlc: &crate::lightning::ln::chan_utils::HTLCOutputInCommitment) -> crate::c_types::derived::CResult_SignatureNoneZ { + let mut ret = >::sign_counterparty_htlc_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &htlc_tx.into_bitcoin(), input, amount, &per_commitment_point.into_rust(), htlc.get_native_ref(), secp256k1::global::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn InMemorySigner_BaseSign_sign_closing_transaction(this_arg: *const c_void, closing_tx: &crate::lightning::ln::chan_utils::ClosingTransaction) -> crate::c_types::derived::CResult_SignatureNoneZ { - let mut ret = >::sign_closing_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, closing_tx.get_native_ref(), secp256k1::global::SECP256K1); +extern "C" fn InMemorySigner_EcdsaChannelSigner_sign_closing_transaction(this_arg: *const c_void, closing_tx: &crate::lightning::ln::chan_utils::ClosingTransaction) -> crate::c_types::derived::CResult_SignatureNoneZ { + let mut ret = >::sign_closing_transaction(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, closing_tx.get_native_ref(), secp256k1::global::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn InMemorySigner_BaseSign_sign_holder_anchor_input(this_arg: *const c_void, mut anchor_tx: crate::c_types::Transaction, mut input: usize) -> crate::c_types::derived::CResult_SignatureNoneZ { - let mut ret = >::sign_holder_anchor_input(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &anchor_tx.into_bitcoin(), input, secp256k1::global::SECP256K1); +extern "C" fn InMemorySigner_EcdsaChannelSigner_sign_holder_anchor_input(this_arg: *const c_void, mut anchor_tx: crate::c_types::Transaction, mut input: usize) -> crate::c_types::derived::CResult_SignatureNoneZ { + let mut ret = >::sign_holder_anchor_input(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, &anchor_tx.into_bitcoin(), input, secp256k1::global::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn InMemorySigner_BaseSign_sign_channel_announcement(this_arg: *const c_void, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_C2Tuple_SignatureSignatureZNoneZ { - let mut ret = >::sign_channel_announcement(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, msg.get_native_ref(), secp256k1::global::SECP256K1); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::Signature::from_rust(&orig_ret_0_0), crate::c_types::Signature::from_rust(&orig_ret_0_1)).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; +extern "C" fn InMemorySigner_EcdsaChannelSigner_sign_channel_announcement_with_funding_key(this_arg: *const c_void, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement) -> crate::c_types::derived::CResult_SignatureNoneZ { + let mut ret = >::sign_channel_announcement_with_funding_key(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, msg.get_native_ref(), secp256k1::global::SECP256K1); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } -extern "C" fn InMemorySigner_BaseSign_provide_channel_parameters(this_arg: *mut c_void, channel_parameters: &crate::lightning::ln::chan_utils::ChannelTransactionParameters) { - >::provide_channel_parameters(unsafe { &mut *(this_arg as *mut nativeInMemorySigner) }, channel_parameters.get_native_ref()) -} -impl From for crate::lightning::chain::keysinterface::Sign { +impl From for crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner { fn from(obj: nativeInMemorySigner) -> Self { let mut rust_obj = InMemorySigner { inner: ObjOps::heap_alloc(obj), is_owned: true }; - let mut ret = InMemorySigner_as_Sign(&rust_obj); + let mut ret = InMemorySigner_as_WriteableEcdsaChannelSigner(&rust_obj); // 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 rust_obj.inner = core::ptr::null_mut(); ret.free = Some(InMemorySigner_free_void); ret } } -/// Constructs a new Sign which calls the relevant methods on this_arg. -/// This copies the `inner` pointer in this_arg and thus the returned Sign must be freed before this_arg is +/// Constructs a new WriteableEcdsaChannelSigner which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned WriteableEcdsaChannelSigner must be freed before this_arg is #[no_mangle] -pub extern "C" fn InMemorySigner_as_Sign(this_arg: &InMemorySigner) -> crate::lightning::chain::keysinterface::Sign { - crate::lightning::chain::keysinterface::Sign { +pub extern "C" fn InMemorySigner_as_WriteableEcdsaChannelSigner(this_arg: &InMemorySigner) -> crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner { + crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner { this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, - BaseSign: crate::lightning::chain::keysinterface::BaseSign { + EcdsaChannelSigner: crate::lightning::chain::keysinterface::EcdsaChannelSigner { this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, - get_per_commitment_point: InMemorySigner_BaseSign_get_per_commitment_point, - release_commitment_secret: InMemorySigner_BaseSign_release_commitment_secret, - validate_holder_commitment: InMemorySigner_BaseSign_validate_holder_commitment, + sign_counterparty_commitment: InMemorySigner_EcdsaChannelSigner_sign_counterparty_commitment, + validate_counterparty_revocation: InMemorySigner_EcdsaChannelSigner_validate_counterparty_revocation, + sign_holder_commitment_and_htlcs: InMemorySigner_EcdsaChannelSigner_sign_holder_commitment_and_htlcs, + sign_justice_revoked_output: InMemorySigner_EcdsaChannelSigner_sign_justice_revoked_output, + sign_justice_revoked_htlc: InMemorySigner_EcdsaChannelSigner_sign_justice_revoked_htlc, + sign_counterparty_htlc_transaction: InMemorySigner_EcdsaChannelSigner_sign_counterparty_htlc_transaction, + sign_closing_transaction: InMemorySigner_EcdsaChannelSigner_sign_closing_transaction, + sign_holder_anchor_input: InMemorySigner_EcdsaChannelSigner_sign_holder_anchor_input, + sign_channel_announcement_with_funding_key: InMemorySigner_EcdsaChannelSigner_sign_channel_announcement_with_funding_key, + ChannelSigner: crate::lightning::chain::keysinterface::ChannelSigner { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + get_per_commitment_point: InMemorySigner_ChannelSigner_get_per_commitment_point, + release_commitment_secret: InMemorySigner_ChannelSigner_release_commitment_secret, + validate_holder_commitment: InMemorySigner_ChannelSigner_validate_holder_commitment, - pubkeys: crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: core::ptr::null_mut(), is_owned: true }, - set_pubkeys: Some(InMemorySigner_BaseSign_set_pubkeys), - channel_keys_id: InMemorySigner_BaseSign_channel_keys_id, - sign_counterparty_commitment: InMemorySigner_BaseSign_sign_counterparty_commitment, - validate_counterparty_revocation: InMemorySigner_BaseSign_validate_counterparty_revocation, - sign_holder_commitment_and_htlcs: InMemorySigner_BaseSign_sign_holder_commitment_and_htlcs, - sign_justice_revoked_output: InMemorySigner_BaseSign_sign_justice_revoked_output, - sign_justice_revoked_htlc: InMemorySigner_BaseSign_sign_justice_revoked_htlc, - sign_counterparty_htlc_transaction: InMemorySigner_BaseSign_sign_counterparty_htlc_transaction, - sign_closing_transaction: InMemorySigner_BaseSign_sign_closing_transaction, - sign_holder_anchor_input: InMemorySigner_BaseSign_sign_holder_anchor_input, - sign_channel_announcement: InMemorySigner_BaseSign_sign_channel_announcement, - provide_channel_parameters: InMemorySigner_BaseSign_provide_channel_parameters, + pubkeys: crate::lightning::ln::chan_utils::ChannelPublicKeys { inner: core::ptr::null_mut(), is_owned: true }, + set_pubkeys: Some(InMemorySigner_ChannelSigner_set_pubkeys), + channel_keys_id: InMemorySigner_ChannelSigner_channel_keys_id, + provide_channel_parameters: InMemorySigner_ChannelSigner_provide_channel_parameters, + }, }, write: InMemorySigner_write_void, } @@ -1736,9 +1934,8 @@ pub(crate) extern "C" fn InMemorySigner_write_void(obj: *const c_void) -> crate: } #[no_mangle] /// Read a InMemorySigner from a byte array, created by InMemorySigner_write -pub extern "C" fn InMemorySigner_read(ser: crate::c_types::u8slice, arg: crate::c_types::SecretKey) -> crate::c_types::derived::CResult_InMemorySignerDecodeErrorZ { - let arg_conv = arg.into_rust(); - let res: Result = crate::c_types::deserialize_obj_arg(ser, arg_conv); +pub extern "C" fn InMemorySigner_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InMemorySignerDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::chain::keysinterface::InMemorySigner { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } @@ -1746,8 +1943,8 @@ pub extern "C" fn InMemorySigner_read(ser: crate::c_types::u8slice, arg: crate:: use lightning::chain::keysinterface::KeysManager as nativeKeysManagerImport; pub(crate) type nativeKeysManager = nativeKeysManagerImport; -/// Simple [`KeysInterface`] implementation that takes a 32-byte seed for use as a BIP 32 extended -/// key and derives keys from that. +/// Simple implementation of [`EntropySource`], [`NodeSigner`], and [`SignerProvider`] that takes a +/// 32-byte seed for use as a BIP 32 extended key and derives keys from that. /// /// Your `node_id` is seed/0'. /// Unilateral closes may use seed/1'. @@ -1829,7 +2026,15 @@ pub extern "C" fn KeysManager_new(seed: *const [u8; 32], mut starting_time_secs: crate::lightning::chain::keysinterface::KeysManager { inner: ObjOps::heap_alloc(ret), is_owned: true } } -/// Derive an old [`Sign`] containing per-channel secrets based on a key derivation parameters. +/// Gets the \"node_id\" secret key used to sign gossip announcements, decode onion data, etc. +#[must_use] +#[no_mangle] +pub extern "C" fn KeysManager_get_node_secret_key(this_arg: &crate::lightning::chain::keysinterface::KeysManager) -> crate::c_types::SecretKey { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_node_secret_key(); + crate::c_types::SecretKey::from_rust(ret) +} + +/// Derive an old [`WriteableEcdsaChannelSigner`] containing per-channel secrets based on a key derivation parameters. #[must_use] #[no_mangle] pub extern "C" fn KeysManager_derive_channel_keys(this_arg: &crate::lightning::chain::keysinterface::KeysManager, mut channel_value_satoshis: u64, params: *const [u8; 32]) -> crate::lightning::chain::keysinterface::InMemorySigner { @@ -1859,98 +2064,140 @@ pub extern "C" fn KeysManager_spend_spendable_outputs(this_arg: &crate::lightnin local_ret } -impl From for crate::lightning::chain::keysinterface::KeysInterface { +impl From for crate::lightning::chain::keysinterface::EntropySource { fn from(obj: nativeKeysManager) -> Self { let mut rust_obj = KeysManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; - let mut ret = KeysManager_as_KeysInterface(&rust_obj); + let mut ret = KeysManager_as_EntropySource(&rust_obj); // 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 rust_obj.inner = core::ptr::null_mut(); ret.free = Some(KeysManager_free_void); ret } } -/// Constructs a new KeysInterface which calls the relevant methods on this_arg. -/// This copies the `inner` pointer in this_arg and thus the returned KeysInterface must be freed before this_arg is +/// Constructs a new EntropySource which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned EntropySource must be freed before this_arg is #[no_mangle] -pub extern "C" fn KeysManager_as_KeysInterface(this_arg: &KeysManager) -> crate::lightning::chain::keysinterface::KeysInterface { - crate::lightning::chain::keysinterface::KeysInterface { +pub extern "C" fn KeysManager_as_EntropySource(this_arg: &KeysManager) -> crate::lightning::chain::keysinterface::EntropySource { + crate::lightning::chain::keysinterface::EntropySource { this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, - get_node_secret: KeysManager_KeysInterface_get_node_secret, - get_node_id: KeysManager_KeysInterface_get_node_id, - ecdh: KeysManager_KeysInterface_ecdh, - get_destination_script: KeysManager_KeysInterface_get_destination_script, - get_shutdown_scriptpubkey: KeysManager_KeysInterface_get_shutdown_scriptpubkey, - generate_channel_keys_id: KeysManager_KeysInterface_generate_channel_keys_id, - derive_channel_signer: KeysManager_KeysInterface_derive_channel_signer, - get_secure_random_bytes: KeysManager_KeysInterface_get_secure_random_bytes, - read_chan_signer: KeysManager_KeysInterface_read_chan_signer, - sign_invoice: KeysManager_KeysInterface_sign_invoice, - get_inbound_payment_key_material: KeysManager_KeysInterface_get_inbound_payment_key_material, + get_secure_random_bytes: KeysManager_EntropySource_get_secure_random_bytes, } } #[must_use] -extern "C" fn KeysManager_KeysInterface_get_node_secret(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_SecretKeyNoneZ { - let mut ret = >::get_node_secret(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, recipient.into_native()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::SecretKey::from_rust(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; - local_ret +extern "C" fn KeysManager_EntropySource_get_secure_random_bytes(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { + let mut ret = >::get_secure_random_bytes(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, ); + crate::c_types::ThirtyTwoBytes { data: ret } } + +impl From for crate::lightning::chain::keysinterface::NodeSigner { + fn from(obj: nativeKeysManager) -> Self { + let mut rust_obj = KeysManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = KeysManager_as_NodeSigner(&rust_obj); + // 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 + rust_obj.inner = core::ptr::null_mut(); + ret.free = Some(KeysManager_free_void); + ret + } +} +/// Constructs a new NodeSigner which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned NodeSigner must be freed before this_arg is +#[no_mangle] +pub extern "C" fn KeysManager_as_NodeSigner(this_arg: &KeysManager) -> crate::lightning::chain::keysinterface::NodeSigner { + crate::lightning::chain::keysinterface::NodeSigner { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + get_inbound_payment_key_material: KeysManager_NodeSigner_get_inbound_payment_key_material, + get_node_id: KeysManager_NodeSigner_get_node_id, + ecdh: KeysManager_NodeSigner_ecdh, + sign_invoice: KeysManager_NodeSigner_sign_invoice, + sign_gossip_message: KeysManager_NodeSigner_sign_gossip_message, + } +} + #[must_use] -extern "C" fn KeysManager_KeysInterface_get_node_id(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_PublicKeyNoneZ { - let mut ret = >::get_node_id(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, recipient.into_native()); +extern "C" fn KeysManager_NodeSigner_get_inbound_payment_key_material(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { + let mut ret = >::get_inbound_payment_key_material(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, ); + crate::c_types::ThirtyTwoBytes { data: ret.0 } +} +#[must_use] +extern "C" fn KeysManager_NodeSigner_get_node_id(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_PublicKeyNoneZ { + let mut ret = >::get_node_id(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, recipient.into_native()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::PublicKey::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn KeysManager_KeysInterface_ecdh(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient, mut other_key: crate::c_types::PublicKey, mut tweak: crate::c_types::derived::COption_ScalarZ) -> crate::c_types::derived::CResult_SharedSecretNoneZ { +extern "C" fn KeysManager_NodeSigner_ecdh(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient, mut other_key: crate::c_types::PublicKey, mut tweak: crate::c_types::derived::COption_ScalarZ) -> crate::c_types::derived::CResult_SharedSecretNoneZ { let mut local_tweak_base = { /* tweak*/ let tweak_opt = tweak; { } if tweak_opt.is_none() { None } else { Some({ tweak_opt.take().into_rust() }) } }; let mut local_tweak = local_tweak_base.as_ref(); - let mut ret = >::ecdh(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, recipient.into_native(), &other_key.into_rust(), local_tweak); + let mut ret = >::ecdh(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, recipient.into_native(), &other_key.into_rust(), local_tweak); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.secret_bytes() } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn KeysManager_KeysInterface_get_destination_script(this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z { - let mut ret = >::get_destination_script(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, ); - ret.into_bytes().into() +extern "C" fn KeysManager_NodeSigner_sign_invoice(this_arg: *const c_void, mut hrp_bytes: crate::c_types::u8slice, mut invoice_data: crate::c_types::derived::CVec_U5Z, mut recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_RecoverableSignatureNoneZ { + let mut local_invoice_data = Vec::new(); for mut item in invoice_data.into_rust().drain(..) { local_invoice_data.push( { item.into() }); }; + let mut ret = >::sign_invoice(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, hrp_bytes.to_slice(), &local_invoice_data[..], recipient.into_native()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::RecoverableSignature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; + local_ret } #[must_use] -extern "C" fn KeysManager_KeysInterface_get_shutdown_scriptpubkey(this_arg: *const c_void) -> crate::lightning::ln::script::ShutdownScript { - let mut ret = >::get_shutdown_scriptpubkey(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, ); - crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true } +extern "C" fn KeysManager_NodeSigner_sign_gossip_message(this_arg: *const c_void, mut msg: crate::lightning::ln::msgs::UnsignedGossipMessage) -> crate::c_types::derived::CResult_SignatureNoneZ { + let mut ret = >::sign_gossip_message(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, msg.into_native()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; + local_ret +} + +impl From for crate::lightning::chain::keysinterface::SignerProvider { + fn from(obj: nativeKeysManager) -> Self { + let mut rust_obj = KeysManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = KeysManager_as_SignerProvider(&rust_obj); + // 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 + rust_obj.inner = core::ptr::null_mut(); + ret.free = Some(KeysManager_free_void); + ret + } +} +/// Constructs a new SignerProvider which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned SignerProvider must be freed before this_arg is +#[no_mangle] +pub extern "C" fn KeysManager_as_SignerProvider(this_arg: &KeysManager) -> crate::lightning::chain::keysinterface::SignerProvider { + crate::lightning::chain::keysinterface::SignerProvider { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + generate_channel_keys_id: KeysManager_SignerProvider_generate_channel_keys_id, + derive_channel_signer: KeysManager_SignerProvider_derive_channel_signer, + read_chan_signer: KeysManager_SignerProvider_read_chan_signer, + get_destination_script: KeysManager_SignerProvider_get_destination_script, + get_shutdown_scriptpubkey: KeysManager_SignerProvider_get_shutdown_scriptpubkey, + } } + #[must_use] -extern "C" fn KeysManager_KeysInterface_generate_channel_keys_id(this_arg: *const c_void, mut inbound: bool, mut channel_value_satoshis: u64, mut user_channel_id: crate::c_types::U128) -> crate::c_types::ThirtyTwoBytes { - let mut ret = >::generate_channel_keys_id(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, inbound, channel_value_satoshis, user_channel_id.into()); +extern "C" fn KeysManager_SignerProvider_generate_channel_keys_id(this_arg: *const c_void, mut inbound: bool, mut channel_value_satoshis: u64, mut user_channel_id: crate::c_types::U128) -> crate::c_types::ThirtyTwoBytes { + let mut ret = >::generate_channel_keys_id(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, inbound, channel_value_satoshis, user_channel_id.into()); crate::c_types::ThirtyTwoBytes { data: ret } } #[must_use] -extern "C" fn KeysManager_KeysInterface_derive_channel_signer(this_arg: *const c_void, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::Sign { - let mut ret = >::derive_channel_signer(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, channel_value_satoshis, channel_keys_id.data); +extern "C" fn KeysManager_SignerProvider_derive_channel_signer(this_arg: *const c_void, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner { + let mut ret = >::derive_channel_signer(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, channel_value_satoshis, channel_keys_id.data); Into::into(ret) } #[must_use] -extern "C" fn KeysManager_KeysInterface_get_secure_random_bytes(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { - let mut ret = >::get_secure_random_bytes(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, ); - crate::c_types::ThirtyTwoBytes { data: ret } -} -#[must_use] -extern "C" fn KeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ { - let mut ret = >::read_chan_signer(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, reader.to_slice()); +extern "C" fn KeysManager_SignerProvider_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_WriteableEcdsaChannelSignerDecodeErrorZ { + let mut ret = >::read_chan_signer(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, reader.to_slice()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { Into::into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_ret } #[must_use] -extern "C" fn KeysManager_KeysInterface_sign_invoice(this_arg: *const c_void, mut hrp_bytes: crate::c_types::u8slice, mut invoice_data: crate::c_types::derived::CVec_U5Z, mut receipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_RecoverableSignatureNoneZ { - let mut local_invoice_data = Vec::new(); for mut item in invoice_data.into_rust().drain(..) { local_invoice_data.push( { item.into() }); }; - let mut ret = >::sign_invoice(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, hrp_bytes.to_slice(), &local_invoice_data[..], receipient.into_native()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::RecoverableSignature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; - local_ret +extern "C" fn KeysManager_SignerProvider_get_destination_script(this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z { + let mut ret = >::get_destination_script(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, ); + ret.into_bytes().into() } #[must_use] -extern "C" fn KeysManager_KeysInterface_get_inbound_payment_key_material(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { - let mut ret = >::get_inbound_payment_key_material(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, ); - crate::c_types::ThirtyTwoBytes { data: ret.0 } +extern "C" fn KeysManager_SignerProvider_get_shutdown_scriptpubkey(this_arg: *const c_void) -> crate::lightning::ln::script::ShutdownScript { + let mut ret = >::get_shutdown_scriptpubkey(unsafe { &mut *(this_arg as *mut nativeKeysManager) }, ); + crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -2018,98 +2265,140 @@ impl PhantomKeysManager { ret } } -impl From for crate::lightning::chain::keysinterface::KeysInterface { +impl From for crate::lightning::chain::keysinterface::EntropySource { fn from(obj: nativePhantomKeysManager) -> Self { let mut rust_obj = PhantomKeysManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; - let mut ret = PhantomKeysManager_as_KeysInterface(&rust_obj); + let mut ret = PhantomKeysManager_as_EntropySource(&rust_obj); // 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 rust_obj.inner = core::ptr::null_mut(); ret.free = Some(PhantomKeysManager_free_void); ret } } -/// Constructs a new KeysInterface which calls the relevant methods on this_arg. -/// This copies the `inner` pointer in this_arg and thus the returned KeysInterface must be freed before this_arg is +/// Constructs a new EntropySource which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned EntropySource must be freed before this_arg is #[no_mangle] -pub extern "C" fn PhantomKeysManager_as_KeysInterface(this_arg: &PhantomKeysManager) -> crate::lightning::chain::keysinterface::KeysInterface { - crate::lightning::chain::keysinterface::KeysInterface { +pub extern "C" fn PhantomKeysManager_as_EntropySource(this_arg: &PhantomKeysManager) -> crate::lightning::chain::keysinterface::EntropySource { + crate::lightning::chain::keysinterface::EntropySource { this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, free: None, - get_node_secret: PhantomKeysManager_KeysInterface_get_node_secret, - get_node_id: PhantomKeysManager_KeysInterface_get_node_id, - ecdh: PhantomKeysManager_KeysInterface_ecdh, - get_destination_script: PhantomKeysManager_KeysInterface_get_destination_script, - get_shutdown_scriptpubkey: PhantomKeysManager_KeysInterface_get_shutdown_scriptpubkey, - generate_channel_keys_id: PhantomKeysManager_KeysInterface_generate_channel_keys_id, - derive_channel_signer: PhantomKeysManager_KeysInterface_derive_channel_signer, - get_secure_random_bytes: PhantomKeysManager_KeysInterface_get_secure_random_bytes, - read_chan_signer: PhantomKeysManager_KeysInterface_read_chan_signer, - sign_invoice: PhantomKeysManager_KeysInterface_sign_invoice, - get_inbound_payment_key_material: PhantomKeysManager_KeysInterface_get_inbound_payment_key_material, + get_secure_random_bytes: PhantomKeysManager_EntropySource_get_secure_random_bytes, } } #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_get_node_secret(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_SecretKeyNoneZ { - let mut ret = >::get_node_secret(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, recipient.into_native()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::SecretKey::from_rust(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; - local_ret +extern "C" fn PhantomKeysManager_EntropySource_get_secure_random_bytes(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { + let mut ret = >::get_secure_random_bytes(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, ); + crate::c_types::ThirtyTwoBytes { data: ret } +} + +impl From for crate::lightning::chain::keysinterface::NodeSigner { + fn from(obj: nativePhantomKeysManager) -> Self { + let mut rust_obj = PhantomKeysManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = PhantomKeysManager_as_NodeSigner(&rust_obj); + // 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 + rust_obj.inner = core::ptr::null_mut(); + ret.free = Some(PhantomKeysManager_free_void); + ret + } +} +/// Constructs a new NodeSigner which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned NodeSigner must be freed before this_arg is +#[no_mangle] +pub extern "C" fn PhantomKeysManager_as_NodeSigner(this_arg: &PhantomKeysManager) -> crate::lightning::chain::keysinterface::NodeSigner { + crate::lightning::chain::keysinterface::NodeSigner { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + get_inbound_payment_key_material: PhantomKeysManager_NodeSigner_get_inbound_payment_key_material, + get_node_id: PhantomKeysManager_NodeSigner_get_node_id, + ecdh: PhantomKeysManager_NodeSigner_ecdh, + sign_invoice: PhantomKeysManager_NodeSigner_sign_invoice, + sign_gossip_message: PhantomKeysManager_NodeSigner_sign_gossip_message, + } +} + +#[must_use] +extern "C" fn PhantomKeysManager_NodeSigner_get_inbound_payment_key_material(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { + let mut ret = >::get_inbound_payment_key_material(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, ); + crate::c_types::ThirtyTwoBytes { data: ret.0 } } #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_get_node_id(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_PublicKeyNoneZ { - let mut ret = >::get_node_id(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, recipient.into_native()); +extern "C" fn PhantomKeysManager_NodeSigner_get_node_id(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_PublicKeyNoneZ { + let mut ret = >::get_node_id(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, recipient.into_native()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::PublicKey::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_ecdh(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient, mut other_key: crate::c_types::PublicKey, mut tweak: crate::c_types::derived::COption_ScalarZ) -> crate::c_types::derived::CResult_SharedSecretNoneZ { +extern "C" fn PhantomKeysManager_NodeSigner_ecdh(this_arg: *const c_void, mut recipient: crate::lightning::chain::keysinterface::Recipient, mut other_key: crate::c_types::PublicKey, mut tweak: crate::c_types::derived::COption_ScalarZ) -> crate::c_types::derived::CResult_SharedSecretNoneZ { let mut local_tweak_base = { /* tweak*/ let tweak_opt = tweak; { } if tweak_opt.is_none() { None } else { Some({ tweak_opt.take().into_rust() }) } }; let mut local_tweak = local_tweak_base.as_ref(); - let mut ret = >::ecdh(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, recipient.into_native(), &other_key.into_rust(), local_tweak); + let mut ret = >::ecdh(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, recipient.into_native(), &other_key.into_rust(), local_tweak); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.secret_bytes() } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_get_destination_script(this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z { - let mut ret = >::get_destination_script(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, ); - ret.into_bytes().into() +extern "C" fn PhantomKeysManager_NodeSigner_sign_invoice(this_arg: *const c_void, mut hrp_bytes: crate::c_types::u8slice, mut invoice_data: crate::c_types::derived::CVec_U5Z, mut recipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_RecoverableSignatureNoneZ { + let mut local_invoice_data = Vec::new(); for mut item in invoice_data.into_rust().drain(..) { local_invoice_data.push( { item.into() }); }; + let mut ret = >::sign_invoice(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, hrp_bytes.to_slice(), &local_invoice_data[..], recipient.into_native()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::RecoverableSignature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; + local_ret } #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_get_shutdown_scriptpubkey(this_arg: *const c_void) -> crate::lightning::ln::script::ShutdownScript { - let mut ret = >::get_shutdown_scriptpubkey(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, ); - crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true } +extern "C" fn PhantomKeysManager_NodeSigner_sign_gossip_message(this_arg: *const c_void, mut msg: crate::lightning::ln::msgs::UnsignedGossipMessage) -> crate::c_types::derived::CResult_SignatureNoneZ { + let mut ret = >::sign_gossip_message(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, msg.into_native()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::Signature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; + local_ret } + +impl From for crate::lightning::chain::keysinterface::SignerProvider { + fn from(obj: nativePhantomKeysManager) -> Self { + let mut rust_obj = PhantomKeysManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; + let mut ret = PhantomKeysManager_as_SignerProvider(&rust_obj); + // 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 + rust_obj.inner = core::ptr::null_mut(); + ret.free = Some(PhantomKeysManager_free_void); + ret + } +} +/// Constructs a new SignerProvider which calls the relevant methods on this_arg. +/// This copies the `inner` pointer in this_arg and thus the returned SignerProvider must be freed before this_arg is +#[no_mangle] +pub extern "C" fn PhantomKeysManager_as_SignerProvider(this_arg: &PhantomKeysManager) -> crate::lightning::chain::keysinterface::SignerProvider { + crate::lightning::chain::keysinterface::SignerProvider { + this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, + free: None, + generate_channel_keys_id: PhantomKeysManager_SignerProvider_generate_channel_keys_id, + derive_channel_signer: PhantomKeysManager_SignerProvider_derive_channel_signer, + read_chan_signer: PhantomKeysManager_SignerProvider_read_chan_signer, + get_destination_script: PhantomKeysManager_SignerProvider_get_destination_script, + get_shutdown_scriptpubkey: PhantomKeysManager_SignerProvider_get_shutdown_scriptpubkey, + } +} + #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_generate_channel_keys_id(this_arg: *const c_void, mut inbound: bool, mut channel_value_satoshis: u64, mut user_channel_id: crate::c_types::U128) -> crate::c_types::ThirtyTwoBytes { - let mut ret = >::generate_channel_keys_id(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, inbound, channel_value_satoshis, user_channel_id.into()); +extern "C" fn PhantomKeysManager_SignerProvider_generate_channel_keys_id(this_arg: *const c_void, mut inbound: bool, mut channel_value_satoshis: u64, mut user_channel_id: crate::c_types::U128) -> crate::c_types::ThirtyTwoBytes { + let mut ret = >::generate_channel_keys_id(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, inbound, channel_value_satoshis, user_channel_id.into()); crate::c_types::ThirtyTwoBytes { data: ret } } #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_derive_channel_signer(this_arg: *const c_void, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::Sign { - let mut ret = >::derive_channel_signer(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, channel_value_satoshis, channel_keys_id.data); +extern "C" fn PhantomKeysManager_SignerProvider_derive_channel_signer(this_arg: *const c_void, mut channel_value_satoshis: u64, mut channel_keys_id: crate::c_types::ThirtyTwoBytes) -> crate::lightning::chain::keysinterface::WriteableEcdsaChannelSigner { + let mut ret = >::derive_channel_signer(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, channel_value_satoshis, channel_keys_id.data); Into::into(ret) } #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_get_secure_random_bytes(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { - let mut ret = >::get_secure_random_bytes(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, ); - crate::c_types::ThirtyTwoBytes { data: ret } -} -#[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_SignDecodeErrorZ { - let mut ret = >::read_chan_signer(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, reader.to_slice()); +extern "C" fn PhantomKeysManager_SignerProvider_read_chan_signer(this_arg: *const c_void, mut reader: crate::c_types::u8slice) -> crate::c_types::derived::CResult_WriteableEcdsaChannelSignerDecodeErrorZ { + let mut ret = >::read_chan_signer(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, reader.to_slice()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { Into::into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_ret } #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_sign_invoice(this_arg: *const c_void, mut hrp_bytes: crate::c_types::u8slice, mut invoice_data: crate::c_types::derived::CVec_U5Z, mut receipient: crate::lightning::chain::keysinterface::Recipient) -> crate::c_types::derived::CResult_RecoverableSignatureNoneZ { - let mut local_invoice_data = Vec::new(); for mut item in invoice_data.into_rust().drain(..) { local_invoice_data.push( { item.into() }); }; - let mut ret = >::sign_invoice(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, hrp_bytes.to_slice(), &local_invoice_data[..], receipient.into_native()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::RecoverableSignature::from_rust(&o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; - local_ret +extern "C" fn PhantomKeysManager_SignerProvider_get_destination_script(this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z { + let mut ret = >::get_destination_script(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, ); + ret.into_bytes().into() } #[must_use] -extern "C" fn PhantomKeysManager_KeysInterface_get_inbound_payment_key_material(this_arg: *const c_void) -> crate::c_types::ThirtyTwoBytes { - let mut ret = >::get_inbound_payment_key_material(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, ); - crate::c_types::ThirtyTwoBytes { data: ret.0 } +extern "C" fn PhantomKeysManager_SignerProvider_get_shutdown_scriptpubkey(this_arg: *const c_void) -> crate::lightning::ln::script::ShutdownScript { + let mut ret = >::get_shutdown_scriptpubkey(unsafe { &mut *(this_arg as *mut nativePhantomKeysManager) }, ); + crate::lightning::ln::script::ShutdownScript { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Constructs a [`PhantomKeysManager`] given a 32-byte seed and an additional `cross_node_seed` @@ -2149,3 +2438,20 @@ pub extern "C" fn PhantomKeysManager_derive_channel_keys(this_arg: &crate::light crate::lightning::chain::keysinterface::InMemorySigner { inner: ObjOps::heap_alloc(ret), is_owned: true } } +/// Gets the \"node_id\" secret key used to sign gossip announcements, decode onion data, etc. +#[must_use] +#[no_mangle] +pub extern "C" fn PhantomKeysManager_get_node_secret_key(this_arg: &crate::lightning::chain::keysinterface::PhantomKeysManager) -> crate::c_types::SecretKey { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_node_secret_key(); + crate::c_types::SecretKey::from_rust(ret) +} + +/// Gets the \"node_id\" secret key of the phantom node used to sign invoices, decode the +/// last-hop onion data, etc. +#[must_use] +#[no_mangle] +pub extern "C" fn PhantomKeysManager_get_phantom_node_secret_key(this_arg: &crate::lightning::chain::keysinterface::PhantomKeysManager) -> crate::c_types::SecretKey { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_phantom_node_secret_key(); + crate::c_types::SecretKey::from_rust(ret) +} + diff --git a/lightning-c-bindings/src/lightning/chain/mod.rs b/lightning-c-bindings/src/lightning/chain/mod.rs index 1561f74..62d26cb 100644 --- a/lightning-c-bindings/src/lightning/chain/mod.rs +++ b/lightning-c-bindings/src/lightning/chain/mod.rs @@ -126,8 +126,8 @@ pub extern "C" fn BestBlock_eq(a: &BestBlock, b: &BestBlock) -> bool { /// network. #[must_use] #[no_mangle] -pub extern "C" fn BestBlock_from_genesis(mut network: crate::bitcoin::network::Network) -> crate::lightning::chain::BestBlock { - let mut ret = lightning::chain::BestBlock::from_genesis(network.into_bitcoin()); +pub extern "C" fn BestBlock_from_network(mut network: crate::bitcoin::network::Network) -> crate::lightning::chain::BestBlock { + let mut ret = lightning::chain::BestBlock::from_network(network.into_bitcoin()); crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -155,118 +155,6 @@ pub extern "C" fn BestBlock_height(this_arg: &crate::lightning::chain::BestBlock ret } -/// An error when accessing the chain via [`Access`]. -#[derive(Clone)] -#[must_use] -#[repr(C)] -pub enum AccessError { - /// The requested chain is unknown. - UnknownChain, - /// The requested transaction doesn't exist or hasn't confirmed. - UnknownTx, -} -use lightning::chain::AccessError as AccessErrorImport; -pub(crate) type nativeAccessError = AccessErrorImport; - -impl AccessError { - #[allow(unused)] - pub(crate) fn to_native(&self) -> nativeAccessError { - match self { - AccessError::UnknownChain => nativeAccessError::UnknownChain, - AccessError::UnknownTx => nativeAccessError::UnknownTx, - } - } - #[allow(unused)] - pub(crate) fn into_native(self) -> nativeAccessError { - match self { - AccessError::UnknownChain => nativeAccessError::UnknownChain, - AccessError::UnknownTx => nativeAccessError::UnknownTx, - } - } - #[allow(unused)] - pub(crate) fn from_native(native: &nativeAccessError) -> Self { - match native { - nativeAccessError::UnknownChain => AccessError::UnknownChain, - nativeAccessError::UnknownTx => AccessError::UnknownTx, - } - } - #[allow(unused)] - pub(crate) fn native_into(native: nativeAccessError) -> Self { - match native { - nativeAccessError::UnknownChain => AccessError::UnknownChain, - nativeAccessError::UnknownTx => AccessError::UnknownTx, - } - } -} -/// Creates a copy of the AccessError -#[no_mangle] -pub extern "C" fn AccessError_clone(orig: &AccessError) -> AccessError { - orig.clone() -} -#[no_mangle] -/// Utility method to constructs a new UnknownChain-variant AccessError -pub extern "C" fn AccessError_unknown_chain() -> AccessError { - AccessError::UnknownChain} -#[no_mangle] -/// Utility method to constructs a new UnknownTx-variant AccessError -pub extern "C" fn AccessError_unknown_tx() -> AccessError { - AccessError::UnknownTx} -/// The `Access` trait defines behavior for accessing chain data and state, such as blocks and -/// UTXOs. -#[repr(C)] -pub struct Access { - /// An opaque pointer which is passed to your function implementations as an argument. - /// This has no meaning in the LDK, and can be NULL or any other value. - pub this_arg: *mut c_void, - /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`]. - /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output - /// is unknown. - /// - /// [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id - #[must_use] - pub get_utxo: extern "C" fn (this_arg: *const c_void, genesis_hash: *const [u8; 32], short_channel_id: u64) -> crate::c_types::derived::CResult_TxOutAccessErrorZ, - /// Frees any resources associated with this object given its this_arg pointer. - /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. - pub free: Option, -} -unsafe impl Send for Access {} -unsafe impl Sync for Access {} -#[no_mangle] -pub(crate) extern "C" fn Access_clone_fields(orig: &Access) -> Access { - Access { - this_arg: orig.this_arg, - get_utxo: Clone::clone(&orig.get_utxo), - free: Clone::clone(&orig.free), - } -} - -use lightning::chain::Access as rustAccess; -impl rustAccess for Access { - fn get_utxo(&self, mut genesis_hash: &bitcoin::hash_types::BlockHash, mut short_channel_id: u64) -> Result { - let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id); - let mut local_ret = match ret.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; - local_ret - } -} - -// We're essentially a pointer already, or at least a set of pointers, so allow us to be used -// directly as a Deref trait in higher-level structs: -impl core::ops::Deref for Access { - type Target = Self; - fn deref(&self) -> &Self { - self - } -} -/// Calls the free function if one is set -#[no_mangle] -pub extern "C" fn Access_free(this_ptr: Access) { } -impl Drop for Access { - fn drop(&mut self) { - if let Some(f) = self.free { - f(self.this_arg); - } - } -} /// The `Listen` trait is used to notify when blocks have been connected or disconnected from the /// chain. /// @@ -415,6 +303,9 @@ pub struct Confirm { /// Returns transactions that must be monitored for reorganization out of the chain along /// with the hash of the block as part of which it had been previously confirmed. /// + /// Note that the returned `Option` might be `None` for channels created with LDK + /// 0.0.112 and prior, in which case you need to manually track previous confirmations. + /// /// Will include any transactions passed to [`transactions_confirmed`] that have insufficient /// confirmations to be safe from a chain reorganization. Will not include any transactions /// passed to [`transaction_unconfirmed`], unless later reconfirmed. @@ -673,7 +564,7 @@ pub struct Watch { /// /// [`update_monitor`]: channelmonitor::ChannelMonitor::update_monitor #[must_use] - pub update_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::lightning::chain::transaction::OutPoint, update: crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::lightning::chain::ChannelMonitorUpdateStatus, + pub update_channel: extern "C" fn (this_arg: *const c_void, funding_txo: crate::lightning::chain::transaction::OutPoint, update: &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate) -> crate::lightning::chain::ChannelMonitorUpdateStatus, /// Returns any monitor events since the last call. Subsequent calls must only return new /// events. /// @@ -703,13 +594,13 @@ pub(crate) extern "C" fn Watch_clone_fields(orig: &Watch) -> Watch { } use lightning::chain::Watch as rustWatch; -impl rustWatch for Watch { - fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor) -> lightning::chain::ChannelMonitorUpdateStatus { +impl rustWatch for Watch { + fn watch_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut monitor: lightning::chain::channelmonitor::ChannelMonitor) -> lightning::chain::ChannelMonitorUpdateStatus { let mut ret = (self.watch_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(monitor), is_owned: true }); ret.into_native() } - fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: lightning::chain::channelmonitor::ChannelMonitorUpdate) -> lightning::chain::ChannelMonitorUpdateStatus { - let mut ret = (self.update_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: ObjOps::heap_alloc(update), is_owned: true }); + fn update_channel(&self, mut funding_txo: lightning::chain::transaction::OutPoint, mut update: &lightning::chain::channelmonitor::ChannelMonitorUpdate) -> lightning::chain::ChannelMonitorUpdateStatus { + let mut ret = (self.update_channel)(self.this_arg, crate::lightning::chain::transaction::OutPoint { inner: ObjOps::heap_alloc(funding_txo), is_owned: true }, &crate::lightning::chain::channelmonitor::ChannelMonitorUpdate { inner: unsafe { ObjOps::nonnull_ptr_to_inner((update as *const lightning::chain::channelmonitor::ChannelMonitorUpdate<>) as *mut _) }, is_owned: false }); ret.into_native() } fn release_pending_monitor_events(&self) -> Vec<(lightning::chain::transaction::OutPoint, Vec, Option)> { diff --git a/lightning-c-bindings/src/lightning/ln/channelmanager.rs b/lightning-c-bindings/src/lightning/ln/channelmanager.rs index 78db7d8..79daeb2 100644 --- a/lightning-c-bindings/src/lightning/ln/channelmanager.rs +++ b/lightning-c-bindings/src/lightning/ln/channelmanager.rs @@ -12,11 +12,9 @@ //! responsible for tracking which channels are open, HTLCs are in flight and reestablishing those //! upon reconnect to the relevant peer(s). //! -//! It does not manage routing logic (see [`find_route`] for that) nor does it manage constructing +//! It does not manage routing logic (see [`Router`] for that) nor does it manage constructing //! on-chain transactions (it only monitors the chain to watch for any force-closes that might //! imply it needs to fail HTLCs/payments/channels it manages). -//! -//! [`find_route`]: crate::routing::router::find_route use alloc::str::FromStr; use core::ffi::c_void; @@ -26,9 +24,83 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; +/// This enum is used to specify which error data to send to peers when failing back an HTLC +/// using [`ChannelManager::fail_htlc_backwards_with_reason`]. +/// +/// For more info on failure codes, see . +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum FailureCode { + /// We had a temporary error processing the payment. Useful if no other error codes fit + /// and you want to indicate that the payer may want to retry. + TemporaryNodeFailure, + /// We have a required feature which was not in this onion. For example, you may require + /// some additional metadata that was not provided with this payment. + RequiredNodeFeatureMissing, + /// You may wish to use this when a `payment_preimage` is unknown, or the CLTV expiry of + /// the HTLC is too close to the current block height for safe handling. + /// Using this failure code in [`ChannelManager::fail_htlc_backwards_with_reason`] is + /// equivalent to calling [`ChannelManager::fail_htlc_backwards`]. + IncorrectOrUnknownPaymentDetails, +} +use lightning::ln::channelmanager::FailureCode as FailureCodeImport; +pub(crate) type nativeFailureCode = FailureCodeImport; + +impl FailureCode { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeFailureCode { + match self { + FailureCode::TemporaryNodeFailure => nativeFailureCode::TemporaryNodeFailure, + FailureCode::RequiredNodeFeatureMissing => nativeFailureCode::RequiredNodeFeatureMissing, + FailureCode::IncorrectOrUnknownPaymentDetails => nativeFailureCode::IncorrectOrUnknownPaymentDetails, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeFailureCode { + match self { + FailureCode::TemporaryNodeFailure => nativeFailureCode::TemporaryNodeFailure, + FailureCode::RequiredNodeFeatureMissing => nativeFailureCode::RequiredNodeFeatureMissing, + FailureCode::IncorrectOrUnknownPaymentDetails => nativeFailureCode::IncorrectOrUnknownPaymentDetails, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeFailureCode) -> Self { + match native { + nativeFailureCode::TemporaryNodeFailure => FailureCode::TemporaryNodeFailure, + nativeFailureCode::RequiredNodeFeatureMissing => FailureCode::RequiredNodeFeatureMissing, + nativeFailureCode::IncorrectOrUnknownPaymentDetails => FailureCode::IncorrectOrUnknownPaymentDetails, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeFailureCode) -> Self { + match native { + nativeFailureCode::TemporaryNodeFailure => FailureCode::TemporaryNodeFailure, + nativeFailureCode::RequiredNodeFeatureMissing => FailureCode::RequiredNodeFeatureMissing, + nativeFailureCode::IncorrectOrUnknownPaymentDetails => FailureCode::IncorrectOrUnknownPaymentDetails, + } + } +} +/// Creates a copy of the FailureCode +#[no_mangle] +pub extern "C" fn FailureCode_clone(orig: &FailureCode) -> FailureCode { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new TemporaryNodeFailure-variant FailureCode +pub extern "C" fn FailureCode_temporary_node_failure() -> FailureCode { + FailureCode::TemporaryNodeFailure} +#[no_mangle] +/// Utility method to constructs a new RequiredNodeFeatureMissing-variant FailureCode +pub extern "C" fn FailureCode_required_node_feature_missing() -> FailureCode { + FailureCode::RequiredNodeFeatureMissing} +#[no_mangle] +/// Utility method to constructs a new IncorrectOrUnknownPaymentDetails-variant FailureCode +pub extern "C" fn FailureCode_incorrect_or_unknown_payment_details() -> FailureCode { + FailureCode::IncorrectOrUnknownPaymentDetails} use lightning::ln::channelmanager::ChannelManager as nativeChannelManagerImport; -pub(crate) type nativeChannelManager = nativeChannelManagerImport; +pub(crate) type nativeChannelManager = nativeChannelManagerImport; /// Manager which keeps track of a number of channels and sends messages to the appropriate /// channel, also tracking HTLC preimages and forwarding onion packets appropriately. @@ -61,6 +133,15 @@ pub(crate) type nativeChannelManager = nativeChannelManagerImport nativePaymentSendFailure { + pub(crate) fn to_native(&self) -> nativeRecentPaymentDetails { match self { - PaymentSendFailure::ParameterError (ref a, ) => { - let mut a_nonref = Clone::clone(a); - nativePaymentSendFailure::ParameterError ( - a_nonref.into_native(), - ) - }, - PaymentSendFailure::PathParameterError (ref a, ) => { - let mut a_nonref = Clone::clone(a); - 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 }); }; - nativePaymentSendFailure::PathParameterError ( - local_a_nonref, - ) + RecentPaymentDetails::Pending {ref payment_hash, ref total_msat, } => { + let mut payment_hash_nonref = Clone::clone(payment_hash); + let mut total_msat_nonref = Clone::clone(total_msat); + nativeRecentPaymentDetails::Pending { + payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data), + total_msat: total_msat_nonref, + } }, - PaymentSendFailure::AllFailedResendSafe (ref a, ) => { - let mut a_nonref = Clone::clone(a); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { item.into_native() }); }; - nativePaymentSendFailure::AllFailedResendSafe ( - local_a_nonref, - ) + RecentPaymentDetails::Fulfilled {ref payment_hash, } => { + let mut payment_hash_nonref = Clone::clone(payment_hash); + let mut local_payment_hash_nonref = if payment_hash_nonref.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentHash(payment_hash_nonref.data) }) }; + nativeRecentPaymentDetails::Fulfilled { + payment_hash: local_payment_hash_nonref, + } }, - PaymentSendFailure::DuplicatePayment => nativePaymentSendFailure::DuplicatePayment, - PaymentSendFailure::PartialFailure {ref results, ref failed_paths_retry, ref payment_id, } => { - let mut results_nonref = Clone::clone(results); - let mut local_results_nonref = Vec::new(); for mut item in results_nonref.into_rust().drain(..) { local_results_nonref.push( { let mut local_results_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_results_nonref_0 }); }; - let mut failed_paths_retry_nonref = Clone::clone(failed_paths_retry); - let mut local_failed_paths_retry_nonref = if failed_paths_retry_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(failed_paths_retry_nonref.take_inner()) } }) }; - let mut payment_id_nonref = Clone::clone(payment_id); - nativePaymentSendFailure::PartialFailure { - results: local_results_nonref, - failed_paths_retry: local_failed_paths_retry_nonref, - payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data), + RecentPaymentDetails::Abandoned {ref payment_hash, } => { + let mut payment_hash_nonref = Clone::clone(payment_hash); + nativeRecentPaymentDetails::Abandoned { + payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data), } }, } } #[allow(unused)] - pub(crate) fn into_native(self) -> nativePaymentSendFailure { + pub(crate) fn into_native(self) -> nativeRecentPaymentDetails { match self { - PaymentSendFailure::ParameterError (mut a, ) => { - nativePaymentSendFailure::ParameterError ( - a.into_native(), - ) - }, - PaymentSendFailure::PathParameterError (mut a, ) => { - 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 }); }; - nativePaymentSendFailure::PathParameterError ( - local_a, - ) + RecentPaymentDetails::Pending {mut payment_hash, mut total_msat, } => { + nativeRecentPaymentDetails::Pending { + payment_hash: ::lightning::ln::PaymentHash(payment_hash.data), + total_msat: total_msat, + } }, - PaymentSendFailure::AllFailedResendSafe (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { item.into_native() }); }; - nativePaymentSendFailure::AllFailedResendSafe ( - local_a, - ) + RecentPaymentDetails::Fulfilled {mut payment_hash, } => { + let mut local_payment_hash = if payment_hash.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentHash(payment_hash.data) }) }; + nativeRecentPaymentDetails::Fulfilled { + payment_hash: local_payment_hash, + } }, - PaymentSendFailure::DuplicatePayment => nativePaymentSendFailure::DuplicatePayment, - PaymentSendFailure::PartialFailure {mut results, mut failed_paths_retry, mut payment_id, } => { - let mut local_results = Vec::new(); for mut item in results.into_rust().drain(..) { local_results.push( { let mut local_results_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_results_0 }); }; - let mut local_failed_paths_retry = if failed_paths_retry.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(failed_paths_retry.take_inner()) } }) }; - nativePaymentSendFailure::PartialFailure { - results: local_results, - failed_paths_retry: local_failed_paths_retry, - payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data), + RecentPaymentDetails::Abandoned {mut payment_hash, } => { + nativeRecentPaymentDetails::Abandoned { + payment_hash: ::lightning::ln::PaymentHash(payment_hash.data), } }, } } #[allow(unused)] - pub(crate) fn from_native(native: &nativePaymentSendFailure) -> Self { + pub(crate) fn from_native(native: &nativeRecentPaymentDetails) -> Self { match native { - nativePaymentSendFailure::ParameterError (ref a, ) => { - let mut a_nonref = Clone::clone(a); - PaymentSendFailure::ParameterError ( - crate::lightning::util::errors::APIError::native_into(a_nonref), - ) - }, - nativePaymentSendFailure::PathParameterError (ref a, ) => { - let mut a_nonref = Clone::clone(a); - 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( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); }; - PaymentSendFailure::PathParameterError ( - local_a_nonref.into(), - ) + nativeRecentPaymentDetails::Pending {ref payment_hash, ref total_msat, } => { + let mut payment_hash_nonref = Clone::clone(payment_hash); + let mut total_msat_nonref = Clone::clone(total_msat); + RecentPaymentDetails::Pending { + payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 }, + total_msat: total_msat_nonref, + } }, - nativePaymentSendFailure::AllFailedResendSafe (ref a, ) => { - let mut a_nonref = Clone::clone(a); - let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { crate::lightning::util::errors::APIError::native_into(item) }); }; - PaymentSendFailure::AllFailedResendSafe ( - local_a_nonref.into(), - ) + nativeRecentPaymentDetails::Fulfilled {ref payment_hash, } => { + let mut payment_hash_nonref = Clone::clone(payment_hash); + let mut local_payment_hash_nonref = if payment_hash_nonref.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (payment_hash_nonref.unwrap()).0 } } }; + RecentPaymentDetails::Fulfilled { + payment_hash: local_payment_hash_nonref, + } }, - nativePaymentSendFailure::DuplicatePayment => PaymentSendFailure::DuplicatePayment, - nativePaymentSendFailure::PartialFailure {ref results, ref failed_paths_retry, ref payment_id, } => { - let mut results_nonref = Clone::clone(results); - let mut local_results_nonref = Vec::new(); for mut item in results_nonref.drain(..) { local_results_nonref.push( { let mut local_results_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_results_nonref_0 }); }; - let mut failed_paths_retry_nonref = Clone::clone(failed_paths_retry); - let mut local_failed_paths_retry_nonref = crate::lightning::routing::router::RouteParameters { inner: if failed_paths_retry_nonref.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((failed_paths_retry_nonref.unwrap())) } }, is_owned: true }; - let mut payment_id_nonref = Clone::clone(payment_id); - PaymentSendFailure::PartialFailure { - results: local_results_nonref.into(), - failed_paths_retry: local_failed_paths_retry_nonref, - payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 }, + nativeRecentPaymentDetails::Abandoned {ref payment_hash, } => { + let mut payment_hash_nonref = Clone::clone(payment_hash); + RecentPaymentDetails::Abandoned { + payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 }, } }, } } #[allow(unused)] - pub(crate) fn native_into(native: nativePaymentSendFailure) -> Self { + pub(crate) fn native_into(native: nativeRecentPaymentDetails) -> Self { match native { - nativePaymentSendFailure::ParameterError (mut a, ) => { - PaymentSendFailure::ParameterError ( - crate::lightning::util::errors::APIError::native_into(a), - ) - }, - nativePaymentSendFailure::PathParameterError (mut a, ) => { - 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( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); }; - PaymentSendFailure::PathParameterError ( - local_a.into(), - ) + nativeRecentPaymentDetails::Pending {mut payment_hash, mut total_msat, } => { + RecentPaymentDetails::Pending { + payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 }, + total_msat: total_msat, + } }, - nativePaymentSendFailure::AllFailedResendSafe (mut a, ) => { - let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { crate::lightning::util::errors::APIError::native_into(item) }); }; - PaymentSendFailure::AllFailedResendSafe ( - local_a.into(), - ) + nativeRecentPaymentDetails::Fulfilled {mut payment_hash, } => { + let mut local_payment_hash = if payment_hash.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (payment_hash.unwrap()).0 } } }; + RecentPaymentDetails::Fulfilled { + payment_hash: local_payment_hash, + } }, - nativePaymentSendFailure::DuplicatePayment => PaymentSendFailure::DuplicatePayment, - nativePaymentSendFailure::PartialFailure {mut results, mut failed_paths_retry, mut payment_id, } => { - let mut local_results = Vec::new(); for mut item in results.drain(..) { local_results.push( { let mut local_results_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_results_0 }); }; - let mut local_failed_paths_retry = crate::lightning::routing::router::RouteParameters { inner: if failed_paths_retry.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((failed_paths_retry.unwrap())) } }, is_owned: true }; - PaymentSendFailure::PartialFailure { - results: local_results.into(), - failed_paths_retry: local_failed_paths_retry, - payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 }, + nativeRecentPaymentDetails::Abandoned {mut payment_hash, } => { + RecentPaymentDetails::Abandoned { + payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 }, } }, } } } -/// Frees any resources used by the PaymentSendFailure +/// Frees any resources used by the RecentPaymentDetails #[no_mangle] -pub extern "C" fn PaymentSendFailure_free(this_ptr: PaymentSendFailure) { } -/// Creates a copy of the PaymentSendFailure +pub extern "C" fn RecentPaymentDetails_free(this_ptr: RecentPaymentDetails) { } +/// Creates a copy of the RecentPaymentDetails #[no_mangle] -pub extern "C" fn PaymentSendFailure_clone(orig: &PaymentSendFailure) -> PaymentSendFailure { +pub extern "C" fn RecentPaymentDetails_clone(orig: &RecentPaymentDetails) -> RecentPaymentDetails { orig.clone() } #[no_mangle] -/// Utility method to constructs a new ParameterError-variant PaymentSendFailure -pub extern "C" fn PaymentSendFailure_parameter_error(a: crate::lightning::util::errors::APIError) -> PaymentSendFailure { - PaymentSendFailure::ParameterError(a, ) -} -#[no_mangle] -/// Utility method to constructs a new PathParameterError-variant PaymentSendFailure -pub extern "C" fn PaymentSendFailure_path_parameter_error(a: crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ) -> PaymentSendFailure { - PaymentSendFailure::PathParameterError(a, ) +/// Utility method to constructs a new Pending-variant RecentPaymentDetails +pub extern "C" fn RecentPaymentDetails_pending(payment_hash: crate::c_types::ThirtyTwoBytes, total_msat: u64) -> RecentPaymentDetails { + RecentPaymentDetails::Pending { + payment_hash, + total_msat, + } } #[no_mangle] -/// Utility method to constructs a new AllFailedResendSafe-variant PaymentSendFailure -pub extern "C" fn PaymentSendFailure_all_failed_resend_safe(a: crate::c_types::derived::CVec_APIErrorZ) -> PaymentSendFailure { - PaymentSendFailure::AllFailedResendSafe(a, ) +/// Utility method to constructs a new Fulfilled-variant RecentPaymentDetails +pub extern "C" fn RecentPaymentDetails_fulfilled(payment_hash: crate::c_types::ThirtyTwoBytes) -> RecentPaymentDetails { + RecentPaymentDetails::Fulfilled { + payment_hash, + } } #[no_mangle] -/// Utility method to constructs a new DuplicatePayment-variant PaymentSendFailure -pub extern "C" fn PaymentSendFailure_duplicate_payment() -> PaymentSendFailure { - PaymentSendFailure::DuplicatePayment} -#[no_mangle] -/// Utility method to constructs a new PartialFailure-variant PaymentSendFailure -pub extern "C" fn PaymentSendFailure_partial_failure(results: crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ, failed_paths_retry: crate::lightning::routing::router::RouteParameters, payment_id: crate::c_types::ThirtyTwoBytes) -> PaymentSendFailure { - PaymentSendFailure::PartialFailure { - results, - failed_paths_retry, - payment_id, +/// Utility method to constructs a new Abandoned-variant RecentPaymentDetails +pub extern "C" fn RecentPaymentDetails_abandoned(payment_hash: crate::c_types::ThirtyTwoBytes) -> RecentPaymentDetails { + RecentPaymentDetails::Abandoned { + payment_hash, } } @@ -1589,8 +1583,8 @@ pub extern "C" fn PhantomRouteHints_clone(orig: &PhantomRouteHints) -> PhantomRo /// from after `params.latest_hash`. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_new(mut fee_est: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut config: crate::lightning::util::config::UserConfig, mut params: crate::lightning::ln::channelmanager::ChainParameters) -> crate::lightning::ln::channelmanager::ChannelManager { - 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()) }); +pub extern "C" fn ChannelManager_new(mut fee_est: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut router: crate::lightning::routing::router::Router, mut logger: crate::lightning::util::logger::Logger, mut entropy_source: crate::lightning::chain::keysinterface::EntropySource, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut signer_provider: crate::lightning::chain::keysinterface::SignerProvider, mut config: crate::lightning::util::config::UserConfig, mut params: crate::lightning::ln::channelmanager::ChainParameters) -> crate::lightning::ln::channelmanager::ChannelManager { + let mut ret = lightning::ln::channelmanager::ChannelManager::new(fee_est, chain_monitor, tx_broadcaster, router, logger, entropy_source, node_signer, signer_provider, *unsafe { Box::from_raw(config.take_inner()) }, *unsafe { Box::from_raw(params.take_inner()) }); crate::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -1648,14 +1642,12 @@ pub extern "C" fn ChannelManager_list_channels(this_arg: &crate::lightning::ln:: local_ret.into() } -/// Gets the list of usable channels, in random order. Useful as an argument to [`find_route`] -/// to ensure non-announced channels are used. +/// Gets the list of usable channels, in random order. Useful as an argument to +/// [`Router::find_route`] to ensure non-announced channels are used. /// /// These are guaranteed to have their [`ChannelDetails::is_usable`] value set to true, see the /// documentation for [`ChannelDetails::is_usable`] for more info on exactly what the criteria /// are. -/// -/// [`find_route`]: crate::routing::router::find_route #[must_use] #[no_mangle] pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_ChannelDetailsZ { @@ -1664,6 +1656,22 @@ pub extern "C" fn ChannelManager_list_usable_channels(this_arg: &crate::lightnin local_ret.into() } +/// Returns in an undefined order recent payments that -- if not fulfilled -- have yet to find a +/// successful path, or have unresolved HTLCs. +/// +/// This can be useful for payments that may have been prepared, but ultimately not sent, as a +/// result of a crash. If such a payment exists, is not listed here, and an +/// [`Event::PaymentSent`] has not been received, you may consider resending the payment. +/// +/// [`Event::PaymentSent`]: events::Event::PaymentSent +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_list_recent_payments(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CVec_RecentPaymentDetailsZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.list_recent_payments(); + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::RecentPaymentDetails::native_into(item) }); }; + local_ret.into() +} + /// Begins the process of closing a channel. After this call (plus some timeout), no new HTLCs /// will be accepted on the given channel, and after additional timeout/the closing of all /// pending HTLCs, the channel will be closed on chain. @@ -1758,14 +1766,19 @@ pub extern "C" fn ChannelManager_force_close_all_channels_without_broadcasting_t /// Sends a payment along a given route. /// -/// Value parameters are provided via the last hop in route, see documentation for RouteHop +/// Value parameters are provided via the last hop in route, see documentation for [`RouteHop`] /// fields for more info. /// +/// May generate SendHTLCs message(s) event on success, which should be relayed (e.g. via +/// [`PeerManager::process_events`]). +/// +/// # Avoiding Duplicate Payments +/// /// If a pending payment is currently in-flight with the same [`PaymentId`] provided, this /// method will error with an [`APIError::InvalidRoute`]. Note, however, that once a payment /// is no longer pending (either via [`ChannelManager::abandon_payment`], or handling of an -/// [`Event::PaymentSent`]) LDK will not stop you from sending a second payment with the same -/// [`PaymentId`]. +/// [`Event::PaymentSent`] or [`Event::PaymentFailed`]) LDK will not stop you from sending a +/// second payment with the same [`PaymentId`]. /// /// Thus, in order to ensure duplicate payments are not sent, you should implement your own /// tracking of payments, including state to indicate once a payment has completed. Because you @@ -1773,12 +1786,16 @@ pub extern "C" fn ChannelManager_force_close_all_channels_without_broadcasting_t /// consider using the [`PaymentHash`] as the key for tracking payments. In that case, the /// [`PaymentId`] should be a copy of the [`PaymentHash`] bytes. /// -/// May generate SendHTLCs message(s) event on success, which should be relayed (e.g. via -/// [`PeerManager::process_events`]). +/// Additionally, in the scenario where we begin the process of sending a payment, but crash +/// before `send_payment` returns (or prior to [`ChannelMonitorUpdate`] persistence if you're +/// using [`ChannelMonitorUpdateStatus::InProgress`]), the payment may be lost on restart. See +/// [`ChannelManager::list_recent_payments`] for more information. +/// +/// # Possible Error States on [`PaymentSendFailure`] /// /// Each path may have a different return value, and PaymentSendValue may return a Vec with /// each entry matching the corresponding-index entry in the route paths, see -/// PaymentSendFailure for more info. +/// [`PaymentSendFailure`] for more info. /// /// In general, a path may raise: /// * [`APIError::InvalidRoute`] when an invalid route or forwarding parameter (cltv_delta, fee, @@ -1793,18 +1810,22 @@ pub extern "C" fn ChannelManager_force_close_all_channels_without_broadcasting_t /// irrevocably committed to on our end. In such a case, do NOT retry the payment with a /// different route unless you intend to pay twice! /// -/// payment_secret is unrelated to payment_hash (or PaymentPreimage) and exists to authenticate -/// the sender to the recipient and prevent payment-probing (deanonymization) attacks. For -/// newer nodes, it will be provided to you in the invoice. If you do not have one, the Route -/// must not contain multiple paths as multi-path payments require a recipient-provided -/// payment_secret. +/// # A caution on `payment_secret` /// -/// If a payment_secret *is* provided, we assume that the invoice had the payment_secret feature -/// bit set (either as required or as available). If multiple paths are present in the Route, -/// we assume the invoice had the basic_mpp feature set. +/// `payment_secret` is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to +/// authenticate the sender to the recipient and prevent payment-probing (deanonymization) +/// attacks. For newer nodes, it will be provided to you in the invoice. If you do not have one, +/// the [`Route`] must not contain multiple paths as multi-path payments require a +/// recipient-provided `payment_secret`. +/// +/// If a `payment_secret` *is* provided, we assume that the invoice had the payment_secret +/// feature bit set (either as required or as available). If multiple paths are present in the +/// [`Route`], we assume the invoice had the basic_mpp feature set. /// /// [`Event::PaymentSent`]: events::Event::PaymentSent +/// [`Event::PaymentFailed`]: events::Event::PaymentFailed /// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events +/// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress /// /// Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] @@ -1812,46 +1833,37 @@ pub extern "C" fn ChannelManager_force_close_all_channels_without_broadcasting_t pub extern "C" fn ChannelManager_send_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ { let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentSecret(payment_secret.data) }) }; let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_payment(route.get_native_ref(), ::lightning::ln::PaymentHash(payment_hash.data), &local_payment_secret, ::lightning::ln::channelmanager::PaymentId(payment_id.data)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::PaymentSendFailure::native_into(e) }).into() }; local_ret } -/// Retries a payment along the given [`Route`]. +/// Similar to [`ChannelManager::send_payment`], but will automatically find a route based on +/// `route_params` and retry failed payment paths based on `retry_strategy`. /// -/// Errors returned are a superset of those returned from [`send_payment`], so see -/// [`send_payment`] documentation for more details on errors. This method will also error if the -/// retry amount puts the payment more than 10% over the payment's total amount, if the payment -/// for the given `payment_id` cannot be found (likely due to timeout or success), or if -/// further retries have been disabled with [`abandon_payment`]. -/// -/// [`send_payment`]: [`ChannelManager::send_payment`] -/// [`abandon_payment`]: [`ChannelManager::abandon_payment`] +/// Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_retry_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.retry_payment(route.get_native_ref(), ::lightning::ln::channelmanager::PaymentId(payment_id.data)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; +pub extern "C" fn ChannelManager_send_payment_with_retry(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes, mut payment_id: crate::c_types::ThirtyTwoBytes, mut route_params: crate::lightning::routing::router::RouteParameters, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry) -> crate::c_types::derived::CResult_NoneRetryableSendFailureZ { + let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentSecret(payment_secret.data) }) }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_payment_with_retry(::lightning::ln::PaymentHash(payment_hash.data), &local_payment_secret, ::lightning::ln::channelmanager::PaymentId(payment_id.data), *unsafe { Box::from_raw(route_params.take_inner()) }, retry_strategy.into_native()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::RetryableSendFailure::native_into(e) }).into() }; local_ret } -/// Signals that no further retries for the given payment will occur. +/// Signals that no further retries for the given payment should occur. Useful if you have a +/// pending outbound payment with retries remaining, but wish to stop retrying the payment before +/// retries are exhausted. /// -/// After this method returns, no future calls to [`retry_payment`] for the given `payment_id` -/// are allowed. If no [`Event::PaymentFailed`] event had been generated before, one will be -/// generated as soon as there are no remaining pending HTLCs for this payment. +/// If no [`Event::PaymentFailed`] event had been generated before, one will be generated as soon +/// as there are no remaining pending HTLCs for this payment. /// /// Note that calling this method does *not* prevent a payment from succeeding. You must still /// wait until you receive either a [`Event::PaymentFailed`] or [`Event::PaymentSent`] event to /// determine the ultimate status of a payment. /// /// If an [`Event::PaymentFailed`] event is generated and we restart without this -/// [`ChannelManager`] having been persisted, the payment may still be in the pending state -/// upon restart. This allows further calls to [`retry_payment`] (and requiring a second call -/// to [`abandon_payment`] to mark the payment as failed again). Otherwise, future calls to -/// [`retry_payment`] will fail with [`PaymentSendFailure::ParameterError`]. +/// [`ChannelManager`] having been persisted, another [`Event::PaymentFailed`] may be generated. /// -/// [`abandon_payment`]: Self::abandon_payment -/// [`retry_payment`]: Self::retry_payment /// [`Event::PaymentFailed`]: events::Event::PaymentFailed /// [`Event::PaymentSent`]: events::Event::PaymentSent #[no_mangle] @@ -1881,7 +1893,25 @@ pub extern "C" fn ChannelManager_abandon_payment(this_arg: &crate::lightning::ln pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, route: &crate::lightning::routing::router::Route, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_PaymentHashPaymentSendFailureZ { let mut local_payment_preimage = if payment_preimage.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage.data) }) }; let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_payment(route.get_native_ref(), local_payment_preimage, ::lightning::ln::channelmanager::PaymentId(payment_id.data)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::PaymentSendFailure::native_into(e) }).into() }; + local_ret +} + +/// Similar to [`ChannelManager::send_spontaneous_payment`], but will automatically find a route +/// based on `route_params` and retry failed payment paths based on `retry_strategy`. +/// +/// See [`PaymentParameters::for_keysend`] for help in constructing `route_params` for spontaneous +/// payments. +/// +/// [`PaymentParameters::for_keysend`]: crate::routing::router::PaymentParameters::for_keysend +/// +/// Note that payment_preimage (or a relevant inner pointer) may be NULL or all-0s to represent None +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_send_spontaneous_payment_with_retry(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut payment_id: crate::c_types::ThirtyTwoBytes, mut route_params: crate::lightning::routing::router::RouteParameters, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry) -> crate::c_types::derived::CResult_PaymentHashRetryableSendFailureZ { + let mut local_payment_preimage = if payment_preimage.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentPreimage(payment_preimage.data) }) }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_spontaneous_payment_with_retry(local_payment_preimage, ::lightning::ln::channelmanager::PaymentId(payment_id.data), *unsafe { Box::from_raw(route_params.take_inner()) }, retry_strategy.into_native()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::RetryableSendFailure::native_into(e) }).into() }; local_ret } @@ -1893,7 +1923,7 @@ pub extern "C" fn ChannelManager_send_spontaneous_payment(this_arg: &crate::ligh pub extern "C" fn ChannelManager_send_probe(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut hops: crate::c_types::derived::CVec_RouteHopZ) -> crate::c_types::derived::CResult_C2Tuple_PaymentHashPaymentIdZPaymentSendFailureZ { let mut local_hops = Vec::new(); for mut item in hops.into_rust().drain(..) { local_hops.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.send_probe(local_hops); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::outbound_payment::PaymentSendFailure::native_into(e) }).into() }; local_ret } @@ -1988,8 +2018,8 @@ pub extern "C" fn ChannelManager_update_channel_config(this_arg: &crate::lightni /// [`HTLCIntercepted`]: events::Event::HTLCIntercepted #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_forward_intercepted_htlc(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut intercept_id: crate::c_types::ThirtyTwoBytes, next_hop_channel_id: *const [u8; 32], mut _next_node_id: crate::c_types::PublicKey, mut amt_to_forward_msat: u64) -> crate::c_types::derived::CResult_NoneAPIErrorZ { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.forward_intercepted_htlc(::lightning::ln::channelmanager::InterceptId(intercept_id.data), unsafe { &*next_hop_channel_id}, _next_node_id.into_rust(), amt_to_forward_msat); +pub extern "C" fn ChannelManager_forward_intercepted_htlc(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut intercept_id: crate::c_types::ThirtyTwoBytes, next_hop_channel_id: *const [u8; 32], mut next_node_id: crate::c_types::PublicKey, mut amt_to_forward_msat: u64) -> crate::c_types::derived::CResult_NoneAPIErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.forward_intercepted_htlc(::lightning::ln::channelmanager::InterceptId(intercept_id.data), unsafe { &*next_hop_channel_id}, next_node_id.into_rust(), amt_to_forward_msat); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_ret } @@ -2027,6 +2057,7 @@ pub extern "C" fn ChannelManager_process_pending_htlc_forwards(this_arg: &crate: /// the channel. /// * Expiring a channel's previous `ChannelConfig` if necessary to only allow forwarding HTLCs /// with the current `ChannelConfig`. +/// * Removing peers which have disconnected but and no longer have any channels. /// /// Note that this may cause reentrancy through `chain::Watch::update_channel` calls or feerate /// estimate fetches. @@ -2053,6 +2084,15 @@ pub extern "C" fn ChannelManager_fail_htlc_backwards(this_arg: &crate::lightning unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_htlc_backwards(&::lightning::ln::PaymentHash(unsafe { *payment_hash })) } +/// This is a variant of [`ChannelManager::fail_htlc_backwards`] that allows you to specify the +/// reason for the failure. +/// +/// See [`FailureCode`] for valid failure codes. +#[no_mangle] +pub extern "C" fn ChannelManager_fail_htlc_backwards_with_reason(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, payment_hash: *const [u8; 32], mut failure_code: crate::lightning::ln::channelmanager::FailureCode) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.fail_htlc_backwards_with_reason(&::lightning::ln::PaymentHash(unsafe { *payment_hash }), failure_code.into_native()) +} + /// Provides a payment preimage in response to [`Event::PaymentClaimable`], generating any /// [`MessageSendEvent`]s needed to claim the payment. /// @@ -2140,7 +2180,8 @@ pub extern "C" fn ChannelManager_accept_inbound_channel_from_trusted_peer_0conf( /// [`PaymentHash`] and [`PaymentPreimage`] for you. /// /// The [`PaymentPreimage`] will ultimately be returned to you in the [`PaymentClaimable`], which -/// will have the [`PaymentClaimable::payment_preimage`] field filled in. That should then be +/// will have the [`PaymentClaimable::purpose`] be [`PaymentPurpose::InvoicePayment`] with +/// its [`PaymentPurpose::InvoicePayment::payment_preimage`] field filled in. That should then be /// passed directly to [`claim_funds`]. /// /// See [`create_inbound_payment_for_hash`] for detailed documentation on behavior and requirements. @@ -2155,15 +2196,21 @@ pub extern "C" fn ChannelManager_accept_inbound_channel_from_trusted_peer_0conf( /// /// Errors if `min_value_msat` is greater than total bitcoin supply. /// +/// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable +/// on versions of LDK prior to 0.0.114. +/// /// [`claim_funds`]: Self::claim_funds /// [`PaymentClaimable`]: events::Event::PaymentClaimable -/// [`PaymentClaimable::payment_preimage`]: events::Event::PaymentClaimable::payment_preimage +/// [`PaymentClaimable::purpose`]: events::Event::PaymentClaimable::purpose +/// [`PaymentPurpose::InvoicePayment`]: events::PaymentPurpose::InvoicePayment +/// [`PaymentPurpose::InvoicePayment::payment_preimage`]: events::PaymentPurpose::InvoicePayment::payment_preimage /// [`create_inbound_payment_for_hash`]: Self::create_inbound_payment_for_hash #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32) -> crate::c_types::derived::CResult_C2Tuple_PaymentHashPaymentSecretZNoneZ { +pub extern "C" fn ChannelManager_create_inbound_payment(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_C2Tuple_PaymentHashPaymentSecretZNoneZ { let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None }; - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment(local_min_value_msat, invoice_expiry_delta_secs); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment(local_min_value_msat, invoice_expiry_delta_secs, local_min_final_cltv_expiry_delta); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -2214,8 +2261,8 @@ pub extern "C" fn ChannelManager_create_inbound_payment_legacy(this_arg: &crate: /// If you need exact expiry semantics, you should enforce them upon receipt of /// [`PaymentClaimable`]. /// -/// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry` -/// set to at least [`MIN_FINAL_CLTV_EXPIRY`]. +/// Note that invoices generated for inbound payments should have their `min_final_cltv_expiry_delta` +/// set to at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. /// /// Note that a malicious eavesdropper can intuit whether an inbound payment was created by /// `create_inbound_payment` or `create_inbound_payment_for_hash` based on runtime. @@ -2227,13 +2274,17 @@ pub extern "C" fn ChannelManager_create_inbound_payment_legacy(this_arg: &crate: /// /// Errors if `min_value_msat` is greater than total bitcoin supply. /// +/// If `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable +/// on versions of LDK prior to 0.0.114. +/// /// [`create_inbound_payment`]: Self::create_inbound_payment /// [`PaymentClaimable`]: events::Event::PaymentClaimable #[must_use] #[no_mangle] -pub extern "C" fn ChannelManager_create_inbound_payment_for_hash(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32) -> crate::c_types::derived::CResult_PaymentSecretNoneZ { +pub extern "C" fn ChannelManager_create_inbound_payment_for_hash(this_arg: &crate::lightning::ln::channelmanager::ChannelManager, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_PaymentSecretNoneZ { let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None }; - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment_for_hash(::lightning::ln::PaymentHash(payment_hash.data), local_min_value_msat, invoice_expiry_delta_secs); + let mut local_min_final_cltv_expiry = if min_final_cltv_expiry.is_some() { Some( { min_final_cltv_expiry.take() }) } else { None }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.create_inbound_payment_for_hash(::lightning::ln::PaymentHash(payment_hash.data), local_min_value_msat, invoice_expiry_delta_secs, local_min_final_cltv_expiry); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -2486,6 +2537,42 @@ pub extern "C" fn ChannelManager_current_best_block(this_arg: &crate::lightning: crate::lightning::chain::BestBlock { inner: ObjOps::heap_alloc(ret), is_owned: true } } +/// Fetches the set of [`NodeFeatures`] flags which are provided by or required by +/// [`ChannelManager`]. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_node_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::NodeFeatures { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.node_features(); + crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by +/// [`ChannelManager`]. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_channel_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::ChannelFeatures { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.channel_features(); + crate::lightning::ln::features::ChannelFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Fetches the set of [`ChannelTypeFeatures`] flags which are provided by or required by +/// [`ChannelManager`]. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_channel_type_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::ChannelTypeFeatures { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.channel_type_features(); + crate::lightning::ln::features::ChannelTypeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Fetches the set of [`InitFeatures`] flags which are provided by or required by +/// [`ChannelManager`]. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelManager_init_features(this_arg: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::lightning::ln::features::InitFeatures { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.init_features(); + crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + impl From for crate::lightning::ln::msgs::ChannelMessageHandler { fn from(obj: nativeChannelManager) -> Self { let mut rust_obj = ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; @@ -2533,11 +2620,11 @@ pub extern "C" fn ChannelManager_as_ChannelMessageHandler(this_arg: &ChannelMana } } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::OpenChannel) { - >::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, msg.get_native_ref()) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::OpenChannel) { + >::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::AcceptChannel) { - >::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, msg.get_native_ref()) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AcceptChannel) { + >::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_created(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingCreated) { >::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) @@ -2548,8 +2635,8 @@ extern "C" fn ChannelManager_ChannelMessageHandler_handle_funding_signed(this_ar extern "C" fn ChannelManager_ChannelMessageHandler_handle_channel_ready(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReady) { >::handle_channel_ready(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, their_features: &crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::Shutdown) { - >::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), their_features.get_native_ref(), msg.get_native_ref()) +extern "C" fn ChannelManager_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Shutdown) { + >::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ChannelManager_ChannelMessageHandler_handle_closing_signed(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ClosingSigned) { >::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) @@ -2578,12 +2665,12 @@ extern "C" fn ChannelManager_ChannelMessageHandler_handle_update_fee(this_arg: * extern "C" fn ChannelManager_ChannelMessageHandler_handle_announcement_signatures(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AnnouncementSignatures) { >::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ChannelManager_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) { - >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), no_connection_possible) +extern "C" fn ChannelManager_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) { + >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust()) } #[must_use] -extern "C" fn ChannelManager_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Init) -> crate::c_types::derived::CResult_NoneNoneZ { - let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref()); +extern "C" fn ChannelManager_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Init, mut inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ { + let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, &their_node_id.into_rust(), msg.get_native_ref(), inbound); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -2607,27 +2694,11 @@ extern "C" fn ChannelManager_ChannelMessageHandler_provided_init_features(this_a crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } -/// Fetches the set of [`NodeFeatures`] flags which are provided by or required by -/// [`ChannelManager`]. -#[no_mangle] -pub extern "C" fn provided_node_features() -> crate::lightning::ln::features::NodeFeatures { - let mut ret = lightning::ln::channelmanager::provided_node_features(); - crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } -} - -/// Fetches the set of [`ChannelFeatures`] flags which are provided by or required by -/// [`ChannelManager`]. -#[no_mangle] -pub extern "C" fn provided_channel_features() -> crate::lightning::ln::features::ChannelFeatures { - let mut ret = lightning::ln::channelmanager::provided_channel_features(); - crate::lightning::ln::features::ChannelFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } -} - /// Fetches the set of [`InitFeatures`] flags which are provided by or required by /// [`ChannelManager`]. #[no_mangle] -pub extern "C" fn provided_init_features() -> crate::lightning::ln::features::InitFeatures { - let mut ret = lightning::ln::channelmanager::provided_init_features(); +pub extern "C" fn provided_init_features(_config: &crate::lightning::util::config::UserConfig) -> crate::lightning::ln::features::InitFeatures { + let mut ret = lightning::ln::channelmanager::provided_init_features(_config.get_native_ref()); crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -2706,7 +2777,7 @@ pub(crate) extern "C" fn ChannelManager_write_void(obj: *const c_void) -> crate: } use lightning::ln::channelmanager::ChannelManagerReadArgs as nativeChannelManagerReadArgsImport; -pub(crate) type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::keysinterface::KeysInterface, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::util::logger::Logger>; +pub(crate) type nativeChannelManagerReadArgs = nativeChannelManagerReadArgsImport<'static, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::keysinterface::EntropySource, crate::lightning::chain::keysinterface::NodeSigner, crate::lightning::chain::keysinterface::SignerProvider, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::routing::router::Router, crate::lightning::util::logger::Logger>; /// Arguments for the creation of a ChannelManager that are not deserialized. /// @@ -2786,20 +2857,42 @@ impl ChannelManagerReadArgs { ret } } +/// A cryptographically secure source of entropy. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_get_entropy_source(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::keysinterface::EntropySource { + let mut inner_val = &mut this_ptr.get_native_mut_ref().entropy_source; + inner_val +} +/// A cryptographically secure source of entropy. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_set_entropy_source(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::keysinterface::EntropySource) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.entropy_source = val; +} +/// A signer that is able to perform node-scoped cryptographic operations. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_get_node_signer(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::keysinterface::NodeSigner { + let mut inner_val = &mut this_ptr.get_native_mut_ref().node_signer; + inner_val +} +/// A signer that is able to perform node-scoped cryptographic operations. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_set_node_signer(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::keysinterface::NodeSigner) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_signer = val; +} /// The keys provider which will give us relevant keys. Some keys will be loaded during /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel /// signing data. #[no_mangle] -pub extern "C" fn ChannelManagerReadArgs_get_keys_manager(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::keysinterface::KeysInterface { - let mut inner_val = &mut this_ptr.get_native_mut_ref().keys_manager; +pub extern "C" fn ChannelManagerReadArgs_get_signer_provider(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::chain::keysinterface::SignerProvider { + let mut inner_val = &mut this_ptr.get_native_mut_ref().signer_provider; inner_val } /// The keys provider which will give us relevant keys. Some keys will be loaded during /// deserialization and KeysInterface::read_chan_signer will be used to read per-Channel /// signing data. #[no_mangle] -pub extern "C" fn ChannelManagerReadArgs_set_keys_manager(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::keysinterface::KeysInterface) { - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.keys_manager = val; +pub extern "C" fn ChannelManagerReadArgs_set_signer_provider(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::keysinterface::SignerProvider) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.signer_provider = val; } /// The fee_estimator for use in the ChannelManager in the future. /// @@ -2850,6 +2943,23 @@ pub extern "C" fn ChannelManagerReadArgs_get_tx_broadcaster(this_ptr: &ChannelMa pub extern "C" fn ChannelManagerReadArgs_set_tx_broadcaster(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::chain::chaininterface::BroadcasterInterface) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.tx_broadcaster = val; } +/// The router which will be used in the ChannelManager in the future for finding routes +/// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding. +/// +/// No calls to the router will be made during deserialization. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_get_router(this_ptr: &ChannelManagerReadArgs) -> *const crate::lightning::routing::router::Router { + let mut inner_val = &mut this_ptr.get_native_mut_ref().router; + inner_val +} +/// The router which will be used in the ChannelManager in the future for finding routes +/// on-the-fly for trampoline payments. Absent in private nodes that don't support forwarding. +/// +/// No calls to the router will be made during deserialization. +#[no_mangle] +pub extern "C" fn ChannelManagerReadArgs_set_router(this_ptr: &mut ChannelManagerReadArgs, mut val: crate::lightning::routing::router::Router) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.router = val; +} /// The Logger for use in the ChannelManager and which may be used to log information during /// deserialization. #[no_mangle] @@ -2881,9 +2991,9 @@ pub extern "C" fn ChannelManagerReadArgs_set_default_config(this_ptr: &mut Chann /// populate a HashMap directly from C. #[must_use] #[no_mangle] -pub extern "C" fn ChannelManagerReadArgs_new(mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut logger: crate::lightning::util::logger::Logger, mut default_config: crate::lightning::util::config::UserConfig, mut channel_monitors: crate::c_types::derived::CVec_ChannelMonitorZ) -> crate::lightning::ln::channelmanager::ChannelManagerReadArgs { +pub extern "C" fn ChannelManagerReadArgs_new(mut entropy_source: crate::lightning::chain::keysinterface::EntropySource, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut signer_provider: crate::lightning::chain::keysinterface::SignerProvider, mut fee_estimator: crate::lightning::chain::chaininterface::FeeEstimator, mut chain_monitor: crate::lightning::chain::Watch, mut tx_broadcaster: crate::lightning::chain::chaininterface::BroadcasterInterface, mut router: crate::lightning::routing::router::Router, mut logger: crate::lightning::util::logger::Logger, mut default_config: crate::lightning::util::config::UserConfig, mut channel_monitors: crate::c_types::derived::CVec_ChannelMonitorZ) -> crate::lightning::ln::channelmanager::ChannelManagerReadArgs { let mut local_channel_monitors = Vec::new(); for mut item in channel_monitors.into_rust().drain(..) { local_channel_monitors.push( { item.get_native_mut_ref() }); }; - 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); + let mut ret = lightning::ln::channelmanager::ChannelManagerReadArgs::new(entropy_source, node_signer, signer_provider, fee_estimator, chain_monitor, tx_broadcaster, router, logger, *unsafe { Box::from_raw(default_config.take_inner()) }, local_channel_monitors); crate::lightning::ln::channelmanager::ChannelManagerReadArgs { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -2891,7 +3001,7 @@ pub extern "C" fn ChannelManagerReadArgs_new(mut keys_manager: crate::lightning: /// Read a C2Tuple_BlockHashChannelManagerZ from a byte array, created by C2Tuple_BlockHashChannelManagerZ_write pub extern "C" fn C2Tuple_BlockHashChannelManagerZ_read(ser: crate::c_types::u8slice, arg: crate::lightning::ln::channelmanager::ChannelManagerReadArgs) -> crate::c_types::derived::CResult_C2Tuple_BlockHashChannelManagerZDecodeErrorZ { let arg_conv = *unsafe { Box::from_raw(arg.take_inner()) }; - let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv); + let res: Result<(bitcoin::hash_types::BlockHash, lightning::ln::channelmanager::ChannelManager), lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv); 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::lightning::ln::channelmanager::ChannelManager { inner: ObjOps::heap_alloc(orig_res_0_1), is_owned: true }).into(); local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } diff --git a/lightning-c-bindings/src/lightning/ln/features.rs b/lightning-c-bindings/src/lightning/ln/features.rs index 44fa8d3..18fe70c 100644 --- a/lightning-c-bindings/src/lightning/ln/features.rs +++ b/lightning-c-bindings/src/lightning/ln/features.rs @@ -51,6 +51,10 @@ //! (see [BOLT-2](https://github.com/lightning/bolts/blob/master/02-peer-protocol.md) for more information). //! - `Keysend` - send funds to a node without an invoice //! (see the [`Keysend` feature assignment proposal](https://github.com/lightning/bolts/issues/605#issuecomment-606679798) for more information). +//! - `AnchorsZeroFeeHtlcTx` - requires/supports that commitment transactions include anchor outputs +//! and HTLC transactions are pre-signed with zero fee (see +//! [BOLT-3](https://github.com/lightning/bolts/blob/master/03-transactions.md) for more +//! information). //! //! [BOLT #9]: https://github.com/lightning/bolts/blob/master/09-features.md //! [messages]: crate::ln::msgs @@ -573,6 +577,26 @@ pub extern "C" fn InvoiceFeatures_supports_basic_mpp(this_arg: &crate::lightning ret } +/// Set this feature as optional. +#[no_mangle] +pub extern "C" fn Bolt12InvoiceFeatures_set_basic_mpp_optional(this_arg: &mut crate::lightning::ln::features::Bolt12InvoiceFeatures) { + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::ln::features::nativeBolt12InvoiceFeatures)) }.set_basic_mpp_optional() +} + +/// Set this feature as required. +#[no_mangle] +pub extern "C" fn Bolt12InvoiceFeatures_set_basic_mpp_required(this_arg: &mut crate::lightning::ln::features::Bolt12InvoiceFeatures) { + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::ln::features::nativeBolt12InvoiceFeatures)) }.set_basic_mpp_required() +} + +/// Checks if this feature is supported. +#[must_use] +#[no_mangle] +pub extern "C" fn Bolt12InvoiceFeatures_supports_basic_mpp(this_arg: &crate::lightning::ln::features::Bolt12InvoiceFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_basic_mpp(); + ret +} + /// Checks if this feature is required. #[must_use] #[no_mangle] @@ -597,6 +621,14 @@ pub extern "C" fn InvoiceFeatures_requires_basic_mpp(this_arg: &crate::lightning ret } +/// Checks if this feature is required. +#[must_use] +#[no_mangle] +pub extern "C" fn Bolt12InvoiceFeatures_requires_basic_mpp(this_arg: &crate::lightning::ln::features::Bolt12InvoiceFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.requires_basic_mpp(); + ret +} + /// Set this feature as optional. #[no_mangle] pub extern "C" fn InitFeatures_set_wumbo_optional(this_arg: &mut crate::lightning::ln::features::InitFeatures) { @@ -653,6 +685,90 @@ pub extern "C" fn NodeFeatures_requires_wumbo(this_arg: &crate::lightning::ln::f ret } +/// Set this feature as optional. +#[no_mangle] +pub extern "C" fn InitFeatures_set_anchors_zero_fee_htlc_tx_optional(this_arg: &mut crate::lightning::ln::features::InitFeatures) { + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::ln::features::nativeInitFeatures)) }.set_anchors_zero_fee_htlc_tx_optional() +} + +/// Set this feature as required. +#[no_mangle] +pub extern "C" fn InitFeatures_set_anchors_zero_fee_htlc_tx_required(this_arg: &mut crate::lightning::ln::features::InitFeatures) { + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::ln::features::nativeInitFeatures)) }.set_anchors_zero_fee_htlc_tx_required() +} + +/// Checks if this feature is supported. +#[must_use] +#[no_mangle] +pub extern "C" fn InitFeatures_supports_anchors_zero_fee_htlc_tx(this_arg: &crate::lightning::ln::features::InitFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_anchors_zero_fee_htlc_tx(); + ret +} + +/// Set this feature as optional. +#[no_mangle] +pub extern "C" fn NodeFeatures_set_anchors_zero_fee_htlc_tx_optional(this_arg: &mut crate::lightning::ln::features::NodeFeatures) { + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::ln::features::nativeNodeFeatures)) }.set_anchors_zero_fee_htlc_tx_optional() +} + +/// Set this feature as required. +#[no_mangle] +pub extern "C" fn NodeFeatures_set_anchors_zero_fee_htlc_tx_required(this_arg: &mut crate::lightning::ln::features::NodeFeatures) { + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::ln::features::nativeNodeFeatures)) }.set_anchors_zero_fee_htlc_tx_required() +} + +/// Checks if this feature is supported. +#[must_use] +#[no_mangle] +pub extern "C" fn NodeFeatures_supports_anchors_zero_fee_htlc_tx(this_arg: &crate::lightning::ln::features::NodeFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_anchors_zero_fee_htlc_tx(); + ret +} + +/// Set this feature as optional. +#[no_mangle] +pub extern "C" fn ChannelTypeFeatures_set_anchors_zero_fee_htlc_tx_optional(this_arg: &mut crate::lightning::ln::features::ChannelTypeFeatures) { + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::ln::features::nativeChannelTypeFeatures)) }.set_anchors_zero_fee_htlc_tx_optional() +} + +/// Set this feature as required. +#[no_mangle] +pub extern "C" fn ChannelTypeFeatures_set_anchors_zero_fee_htlc_tx_required(this_arg: &mut crate::lightning::ln::features::ChannelTypeFeatures) { + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::ln::features::nativeChannelTypeFeatures)) }.set_anchors_zero_fee_htlc_tx_required() +} + +/// Checks if this feature is supported. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelTypeFeatures_supports_anchors_zero_fee_htlc_tx(this_arg: &crate::lightning::ln::features::ChannelTypeFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.supports_anchors_zero_fee_htlc_tx(); + ret +} + +/// Checks if this feature is required. +#[must_use] +#[no_mangle] +pub extern "C" fn InitFeatures_requires_anchors_zero_fee_htlc_tx(this_arg: &crate::lightning::ln::features::InitFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.requires_anchors_zero_fee_htlc_tx(); + ret +} + +/// Checks if this feature is required. +#[must_use] +#[no_mangle] +pub extern "C" fn NodeFeatures_requires_anchors_zero_fee_htlc_tx(this_arg: &crate::lightning::ln::features::NodeFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.requires_anchors_zero_fee_htlc_tx(); + ret +} + +/// Checks if this feature is required. +#[must_use] +#[no_mangle] +pub extern "C" fn ChannelTypeFeatures_requires_anchors_zero_fee_htlc_tx(this_arg: &crate::lightning::ln::features::ChannelTypeFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.requires_anchors_zero_fee_htlc_tx(); + ret +} + /// Set this feature as optional. #[no_mangle] pub extern "C" fn InitFeatures_set_shutdown_any_segwit_optional(this_arg: &mut crate::lightning::ln::features::InitFeatures) { @@ -1072,6 +1188,24 @@ pub extern "C" fn InvoiceRequestFeatures_eq(a: &InvoiceRequestFeatures, b: &Invo if a.inner.is_null() || b.inner.is_null() { return false; } if a.get_native_ref() == b.get_native_ref() { true } else { false } } +/// Checks if two Bolt12InvoiceFeaturess contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn Bolt12InvoiceFeatures_eq(a: &Bolt12InvoiceFeatures, b: &Bolt12InvoiceFeatures) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} +/// Checks if two BlindedHopFeaturess contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn BlindedHopFeatures_eq(a: &BlindedHopFeatures, b: &BlindedHopFeatures) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} /// Checks if two ChannelTypeFeaturess contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. /// Two objects with NULL inner values will be considered "equal" here. @@ -1195,6 +1329,44 @@ pub(crate) extern "C" fn InvoiceRequestFeatures_clone_void(this_ptr: *const c_vo pub extern "C" fn InvoiceRequestFeatures_clone(orig: &InvoiceRequestFeatures) -> InvoiceRequestFeatures { orig.clone() } +impl Clone for Bolt12InvoiceFeatures { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativeBolt12InvoiceFeatures>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn Bolt12InvoiceFeatures_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBolt12InvoiceFeatures)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the Bolt12InvoiceFeatures +pub extern "C" fn Bolt12InvoiceFeatures_clone(orig: &Bolt12InvoiceFeatures) -> Bolt12InvoiceFeatures { + orig.clone() +} +impl Clone for BlindedHopFeatures { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativeBlindedHopFeatures>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn BlindedHopFeatures_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeBlindedHopFeatures)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the BlindedHopFeatures +pub extern "C" fn BlindedHopFeatures_clone(orig: &BlindedHopFeatures) -> BlindedHopFeatures { + orig.clone() +} impl Clone for ChannelTypeFeatures { fn clone(&self) -> Self { Self { @@ -1521,6 +1693,108 @@ impl InvoiceRequestFeatures { } } +use lightning::ln::features::Bolt12InvoiceFeatures as nativeBolt12InvoiceFeaturesImport; +pub(crate) type nativeBolt12InvoiceFeatures = nativeBolt12InvoiceFeaturesImport; + +/// Features used within an `invoice`. +#[must_use] +#[repr(C)] +pub struct Bolt12InvoiceFeatures { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativeBolt12InvoiceFeatures, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for Bolt12InvoiceFeatures { + fn drop(&mut self) { + if self.is_owned && !<*mut nativeBolt12InvoiceFeatures>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the Bolt12InvoiceFeatures, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn Bolt12InvoiceFeatures_free(this_obj: Bolt12InvoiceFeatures) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn Bolt12InvoiceFeatures_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeBolt12InvoiceFeatures) }; +} +#[allow(unused)] +impl Bolt12InvoiceFeatures { + pub(crate) fn get_native_ref(&self) -> &'static nativeBolt12InvoiceFeatures { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBolt12InvoiceFeatures { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeBolt12InvoiceFeatures { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} + +use lightning::ln::features::BlindedHopFeatures as nativeBlindedHopFeaturesImport; +pub(crate) type nativeBlindedHopFeatures = nativeBlindedHopFeaturesImport; + +/// Features used within BOLT 4 encrypted_data_tlv and BOLT 12 blinded_payinfo +#[must_use] +#[repr(C)] +pub struct BlindedHopFeatures { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativeBlindedHopFeatures, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for BlindedHopFeatures { + fn drop(&mut self) { + if self.is_owned && !<*mut nativeBlindedHopFeatures>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the BlindedHopFeatures, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn BlindedHopFeatures_free(this_obj: BlindedHopFeatures) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn BlindedHopFeatures_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeBlindedHopFeatures) }; +} +#[allow(unused)] +impl BlindedHopFeatures { + pub(crate) fn get_native_ref(&self) -> &'static nativeBlindedHopFeatures { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeBlindedHopFeatures { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeBlindedHopFeatures { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} + use lightning::ln::features::ChannelTypeFeatures as nativeChannelTypeFeaturesImport; pub(crate) type nativeChannelTypeFeatures = nativeChannelTypeFeaturesImport; @@ -1682,6 +1956,40 @@ pub extern "C" fn InvoiceRequestFeatures_requires_unknown_bits(this_arg: &crate: ret } +/// Create a blank Features with no features set +#[must_use] +#[no_mangle] +pub extern "C" fn Bolt12InvoiceFeatures_empty() -> crate::lightning::ln::features::Bolt12InvoiceFeatures { + let mut ret = lightning::ln::features::Bolt12InvoiceFeatures::empty(); + crate::lightning::ln::features::Bolt12InvoiceFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Returns true if this `Features` object contains unknown feature flags which are set as +/// \"required\". +#[must_use] +#[no_mangle] +pub extern "C" fn Bolt12InvoiceFeatures_requires_unknown_bits(this_arg: &crate::lightning::ln::features::Bolt12InvoiceFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.requires_unknown_bits(); + ret +} + +/// Create a blank Features with no features set +#[must_use] +#[no_mangle] +pub extern "C" fn BlindedHopFeatures_empty() -> crate::lightning::ln::features::BlindedHopFeatures { + let mut ret = lightning::ln::features::BlindedHopFeatures::empty(); + crate::lightning::ln::features::BlindedHopFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Returns true if this `Features` object contains unknown feature flags which are set as +/// \"required\". +#[must_use] +#[no_mangle] +pub extern "C" fn BlindedHopFeatures_requires_unknown_bits(this_arg: &crate::lightning::ln::features::BlindedHopFeatures) -> bool { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.requires_unknown_bits(); + ret +} + /// Create a blank Features with no features set #[must_use] #[no_mangle] @@ -1764,50 +2072,34 @@ pub extern "C" fn InvoiceFeatures_read(ser: crate::c_types::u8slice) -> crate::c local_res } #[no_mangle] -/// Serialize the ChannelTypeFeatures object into a byte array which can be read by ChannelTypeFeatures_read -pub extern "C" fn ChannelTypeFeatures_write(obj: &crate::lightning::ln::features::ChannelTypeFeatures) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) -} -#[no_mangle] -pub(crate) extern "C" fn ChannelTypeFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelTypeFeatures) }) -} -#[no_mangle] -/// Read a ChannelTypeFeatures from a byte array, created by ChannelTypeFeatures_write -pub extern "C" fn ChannelTypeFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelTypeFeaturesDecodeErrorZ { - let res: Result = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::ChannelTypeFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; - local_res -} -#[no_mangle] -/// Serialize the OfferFeatures object into a byte array which can be read by OfferFeatures_read -pub extern "C" fn OfferFeatures_write(obj: &crate::lightning::ln::features::OfferFeatures) -> crate::c_types::derived::CVec_u8Z { +/// Serialize the BlindedHopFeatures object into a byte array which can be read by BlindedHopFeatures_read +pub extern "C" fn BlindedHopFeatures_write(obj: &crate::lightning::ln::features::BlindedHopFeatures) -> crate::c_types::derived::CVec_u8Z { crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] -pub(crate) extern "C" fn OfferFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeOfferFeatures) }) +pub(crate) extern "C" fn BlindedHopFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeBlindedHopFeatures) }) } #[no_mangle] -/// Read a OfferFeatures from a byte array, created by OfferFeatures_write -pub extern "C" fn OfferFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_OfferFeaturesDecodeErrorZ { - let res: Result = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::OfferFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; +/// Read a BlindedHopFeatures from a byte array, created by BlindedHopFeatures_write +pub extern "C" fn BlindedHopFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_BlindedHopFeaturesDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::BlindedHopFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } #[no_mangle] -/// Serialize the InvoiceRequestFeatures object into a byte array which can be read by InvoiceRequestFeatures_read -pub extern "C" fn InvoiceRequestFeatures_write(obj: &crate::lightning::ln::features::InvoiceRequestFeatures) -> crate::c_types::derived::CVec_u8Z { +/// Serialize the ChannelTypeFeatures object into a byte array which can be read by ChannelTypeFeatures_read +pub extern "C" fn ChannelTypeFeatures_write(obj: &crate::lightning::ln::features::ChannelTypeFeatures) -> crate::c_types::derived::CVec_u8Z { crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref()) } #[no_mangle] -pub(crate) extern "C" fn InvoiceRequestFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { - crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeInvoiceRequestFeatures) }) +pub(crate) extern "C" fn ChannelTypeFeatures_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeChannelTypeFeatures) }) } #[no_mangle] -/// Read a InvoiceRequestFeatures from a byte array, created by InvoiceRequestFeatures_write -pub extern "C" fn InvoiceRequestFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_InvoiceRequestFeaturesDecodeErrorZ { - let res: Result = crate::c_types::deserialize_obj(ser); - let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::InvoiceRequestFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; +/// Read a ChannelTypeFeatures from a byte array, created by ChannelTypeFeatures_write +pub extern "C" fn ChannelTypeFeatures_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ChannelTypeFeaturesDecodeErrorZ { + let res: Result = crate::c_types::deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::features::ChannelTypeFeatures { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } diff --git a/lightning-c-bindings/src/lightning/ln/inbound_payment.rs b/lightning-c-bindings/src/lightning/ln/inbound_payment.rs index 766cd24..6878fa2 100644 --- a/lightning-c-bindings/src/lightning/ln/inbound_payment.rs +++ b/lightning-c-bindings/src/lightning/ln/inbound_payment.rs @@ -21,9 +21,9 @@ use lightning::ln::inbound_payment::ExpandedKey as nativeExpandedKeyImport; pub(crate) type nativeExpandedKey = nativeExpandedKeyImport; /// A set of keys that were HKDF-expanded from an initial call to -/// [`KeysInterface::get_inbound_payment_key_material`]. +/// [`NodeSigner::get_inbound_payment_key_material`]. /// -/// [`KeysInterface::get_inbound_payment_key_material`]: crate::chain::keysinterface::KeysInterface::get_inbound_payment_key_material +/// [`NodeSigner::get_inbound_payment_key_material`]: crate::chain::keysinterface::NodeSigner::get_inbound_payment_key_material #[must_use] #[repr(C)] pub struct ExpandedKey { @@ -84,17 +84,22 @@ pub extern "C" fn ExpandedKey_new(key_material: *const [u8; 32]) -> crate::light /// `ChannelManager` is required. Useful for generating invoices for [phantom node payments] without /// a `ChannelManager`. /// -/// `keys` is generated by calling [`KeysInterface::get_inbound_payment_key_material`] and then +/// `keys` is generated by calling [`NodeSigner::get_inbound_payment_key_material`] and then /// calling [`ExpandedKey::new`] with its result. It is recommended to cache this value and not /// regenerate it for each new inbound payment. /// /// `current_time` is a Unix timestamp representing the current time. /// +/// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable +/// on versions of LDK prior to 0.0.114. +/// /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager +/// [`NodeSigner::get_inbound_payment_key_material`]: crate::chain::keysinterface::NodeSigner::get_inbound_payment_key_material #[no_mangle] -pub extern "C" fn create(keys: &crate::lightning::ln::inbound_payment::ExpandedKey, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, keys_manager: &crate::lightning::chain::keysinterface::KeysInterface, mut current_time: u64) -> crate::c_types::derived::CResult_C2Tuple_PaymentHashPaymentSecretZNoneZ { +pub extern "C" fn create(keys: &crate::lightning::ln::inbound_payment::ExpandedKey, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut invoice_expiry_delta_secs: u32, entropy_source: &crate::lightning::chain::keysinterface::EntropySource, mut current_time: u64, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_C2Tuple_PaymentHashPaymentSecretZNoneZ { let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None }; - let mut ret = lightning::ln::inbound_payment::create::(keys.get_native_ref(), local_min_value_msat, invoice_expiry_delta_secs, keys_manager, current_time); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = lightning::ln::inbound_payment::create::(keys.get_native_ref(), local_min_value_msat, invoice_expiry_delta_secs, entropy_source, current_time, local_min_final_cltv_expiry_delta); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let (mut orig_ret_0_0, mut orig_ret_0_1) = o; let mut local_ret_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0.0 }, crate::c_types::ThirtyTwoBytes { data: orig_ret_0_1.0 }).into(); local_ret_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -105,11 +110,15 @@ pub extern "C" fn create(keys: &crate::lightning::ln::inbound_payment::ExpandedK /// /// See [`create`] for information on the `keys` and `current_time` parameters. /// +/// Note that if `min_final_cltv_expiry_delta` is set to some value, then the payment will not be receivable +/// on versions of LDK prior to 0.0.114. +/// /// [phantom node payments]: crate::chain::keysinterface::PhantomKeysManager #[no_mangle] -pub extern "C" fn create_from_hash(keys: &crate::lightning::ln::inbound_payment::ExpandedKey, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut invoice_expiry_delta_secs: u32, mut current_time: u64) -> crate::c_types::derived::CResult_PaymentSecretNoneZ { +pub extern "C" fn create_from_hash(keys: &crate::lightning::ln::inbound_payment::ExpandedKey, mut min_value_msat: crate::c_types::derived::COption_u64Z, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut invoice_expiry_delta_secs: u32, mut current_time: u64, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_PaymentSecretNoneZ { let mut local_min_value_msat = if min_value_msat.is_some() { Some( { min_value_msat.take() }) } else { None }; - let mut ret = lightning::ln::inbound_payment::create_from_hash(keys.get_native_ref(), local_min_value_msat, ::lightning::ln::PaymentHash(payment_hash.data), invoice_expiry_delta_secs, current_time); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = lightning::ln::inbound_payment::create_from_hash(keys.get_native_ref(), local_min_value_msat, ::lightning::ln::PaymentHash(payment_hash.data), invoice_expiry_delta_secs, current_time, local_min_final_cltv_expiry_delta); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning/ln/mod.rs b/lightning-c-bindings/src/lightning/ln/mod.rs index 822c774..879ce5e 100644 --- a/lightning-c-bindings/src/lightning/ln/mod.rs +++ b/lightning-c-bindings/src/lightning/ln/mod.rs @@ -35,6 +35,7 @@ pub mod peer_handler; pub mod chan_utils; pub mod features; pub mod script; +pub mod outbound_payment; pub mod wire; mod peer_channel_encryptor { diff --git a/lightning-c-bindings/src/lightning/ln/msgs.rs b/lightning-c-bindings/src/lightning/ln/msgs.rs index a14c617..54269e6 100644 --- a/lightning-c-bindings/src/lightning/ln/msgs.rs +++ b/lightning-c-bindings/src/lightning/ln/msgs.rs @@ -11,12 +11,12 @@ //! For a normal node you probably don't need to use anything here, however, if you wish to split a //! node into an internet-facing route/message socket handling daemon and a separate daemon (or //! server entirely) which handles only channel-related messages you may wish to implement -//! ChannelMessageHandler yourself and use it to re-serialize messages and pass them across +//! [`ChannelMessageHandler`] yourself and use it to re-serialize messages and pass them across //! daemons/servers. //! //! Note that if you go with such an architecture (instead of passing raw socket events to a //! non-internet-facing system) you trust the frontend internet-facing system to not lie about the -//! source node_id of the message, however this does allow you to significantly reduce bandwidth +//! source `node_id` of the message, however this does allow you to significantly reduce bandwidth //! between the systems as routing messages can represent a significant chunk of bandwidth usage //! (especially for non-channel-publicly-announcing nodes). As an alternate design which avoids //! this issue, if you have sufficient bidirectional bandwidth between your systems, you may send @@ -37,19 +37,22 @@ use alloc::{vec::Vec, boxed::Box}; #[repr(C)] pub enum DecodeError { /// A version byte specified something we don't know how to handle. - /// Includes unknown realm byte in an OnionHopData packet + /// + /// Includes unknown realm byte in an onion hop data packet. UnknownVersion, - /// Unknown feature mandating we fail to parse message (eg TLV with an even, unknown type) + /// Unknown feature mandating we fail to parse message (e.g., TLV with an even, unknown type) UnknownRequiredFeature, - /// Value was invalid, eg a byte which was supposed to be a bool was something other than a 0 + /// Value was invalid. + /// + /// For example, a byte which was supposed to be a bool was something other than a 0 /// or 1, a public key/private key/signature was invalid, text wasn't UTF-8, TLV was - /// syntactically incorrect, etc + /// syntactically incorrect, etc. InvalidValue, - /// Buffer too short + /// The buffer to be read was too short. ShortRead, - /// A length descriptor in the packet didn't describe the later data correctly + /// A length descriptor in the packet didn't describe the later data correctly. BadLengthDescriptor, - /// Error from std::io + /// Error from [`std::io`]. Io( crate::c_types::IOError), /// The message included zlib-compressed values, which we don't support. @@ -173,7 +176,9 @@ pub extern "C" fn DecodeError_eq(a: &DecodeError, b: &DecodeError) -> bool { use lightning::ln::msgs::Init as nativeInitImport; pub(crate) type nativeInit = nativeInitImport; -/// An init message to be sent or received from a peer +/// An [`init`] message to be sent to or received from a peer. +/// +/// [`init`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-init-message #[must_use] #[repr(C)] pub struct Init { @@ -220,31 +225,35 @@ impl Init { ret } } -/// The relevant features which the sender supports +/// The relevant features which the sender supports. #[no_mangle] pub extern "C" fn Init_get_features(this_ptr: &Init) -> crate::lightning::ln::features::InitFeatures { let mut inner_val = &mut this_ptr.get_native_mut_ref().features; crate::lightning::ln::features::InitFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::ln::features::InitFeatures<>) as *mut _) }, is_owned: false } } -/// The relevant features which the sender supports +/// The relevant features which the sender supports. #[no_mangle] pub extern "C" fn Init_set_features(this_ptr: &mut Init, mut val: crate::lightning::ln::features::InitFeatures) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.features = *unsafe { Box::from_raw(val.take_inner()) }; } -/// The receipient's network address. This adds the option to report a remote IP address -/// back to a connecting peer using the init message. A node can decide to use that information -/// to discover a potential update to its public IPv4 address (NAT) and use -/// that for a node_announcement update message containing the new address. +/// The receipient's network address. +/// +/// This adds the option to report a remote IP address back to a connecting peer using the init +/// message. A node can decide to use that information to discover a potential update to its +/// public IPv4 address (NAT) and use that for a [`NodeAnnouncement`] update message containing +/// the new address. #[no_mangle] pub extern "C" fn Init_get_remote_network_address(this_ptr: &Init) -> crate::c_types::derived::COption_NetAddressZ { let mut inner_val = &mut this_ptr.get_native_mut_ref().remote_network_address; let mut local_inner_val = if inner_val.is_none() { crate::c_types::derived::COption_NetAddressZ::None } else { crate::c_types::derived::COption_NetAddressZ::Some(/* WARNING: CLONING CONVERSION HERE! &Option is otherwise un-expressable. */ { crate::lightning::ln::msgs::NetAddress::native_into(inner_val.clone().unwrap()) }) }; local_inner_val } -/// The receipient's network address. This adds the option to report a remote IP address -/// back to a connecting peer using the init message. A node can decide to use that information -/// to discover a potential update to its public IPv4 address (NAT) and use -/// that for a node_announcement update message containing the new address. +/// The receipient's network address. +/// +/// This adds the option to report a remote IP address back to a connecting peer using the init +/// message. A node can decide to use that information to discover a potential update to its +/// public IPv4 address (NAT) and use that for a [`NodeAnnouncement`] update message containing +/// the new address. #[no_mangle] pub extern "C" fn Init_set_remote_network_address(this_ptr: &mut Init, mut val: crate::c_types::derived::COption_NetAddressZ) { let mut local_val = { /* val*/ let val_opt = val; { } if val_opt.is_none() { None } else { Some({ val_opt.take().into_native() }) } }; @@ -292,7 +301,9 @@ pub extern "C" fn Init_eq(a: &Init, b: &Init) -> bool { use lightning::ln::msgs::ErrorMessage as nativeErrorMessageImport; pub(crate) type nativeErrorMessage = nativeErrorMessageImport; -/// An error message to be sent or received from a peer +/// An [`error`] message to be sent to or received from a peer. +/// +/// [`error`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-error-and-warning-messages #[must_use] #[repr(C)] pub struct ErrorMessage { @@ -357,8 +368,9 @@ pub extern "C" fn ErrorMessage_set_channel_id(this_ptr: &mut ErrorMessage, mut v unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_id = val.data; } /// A possibly human-readable error description. -/// The string should be sanitized before it is used (e.g. emitted to logs or printed to -/// stdout). Otherwise, a well crafted error message may trigger a security vulnerability in +/// +/// The string should be sanitized before it is used (e.g., emitted to logs or printed to +/// `stdout`). Otherwise, a well crafted error message may trigger a security vulnerability in /// the terminal emulator or the logging subsystem. #[no_mangle] pub extern "C" fn ErrorMessage_get_data(this_ptr: &ErrorMessage) -> crate::c_types::Str { @@ -366,8 +378,9 @@ pub extern "C" fn ErrorMessage_get_data(this_ptr: &ErrorMessage) -> crate::c_typ inner_val.as_str().into() } /// A possibly human-readable error description. -/// The string should be sanitized before it is used (e.g. emitted to logs or printed to -/// stdout). Otherwise, a well crafted error message may trigger a security vulnerability in +/// +/// The string should be sanitized before it is used (e.g., emitted to logs or printed to +/// `stdout`). Otherwise, a well crafted error message may trigger a security vulnerability in /// the terminal emulator or the logging subsystem. #[no_mangle] pub extern "C" fn ErrorMessage_set_data(this_ptr: &mut ErrorMessage, mut val: crate::c_types::Str) { @@ -414,7 +427,9 @@ pub extern "C" fn ErrorMessage_eq(a: &ErrorMessage, b: &ErrorMessage) -> bool { use lightning::ln::msgs::WarningMessage as nativeWarningMessageImport; pub(crate) type nativeWarningMessage = nativeWarningMessageImport; -/// A warning message to be sent or received from a peer +/// A [`warning`] message to be sent to or received from a peer. +/// +/// [`warning`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-error-and-warning-messages #[must_use] #[repr(C)] pub struct WarningMessage { @@ -477,6 +492,7 @@ pub extern "C" fn WarningMessage_set_channel_id(this_ptr: &mut WarningMessage, m unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_id = val.data; } /// A possibly human-readable warning description. +/// /// The string should be sanitized before it is used (e.g. emitted to logs or printed to /// stdout). Otherwise, a well crafted error message may trigger a security vulnerability in /// the terminal emulator or the logging subsystem. @@ -486,6 +502,7 @@ pub extern "C" fn WarningMessage_get_data(this_ptr: &WarningMessage) -> crate::c inner_val.as_str().into() } /// A possibly human-readable warning description. +/// /// The string should be sanitized before it is used (e.g. emitted to logs or printed to /// stdout). Otherwise, a well crafted error message may trigger a security vulnerability in /// the terminal emulator or the logging subsystem. @@ -534,7 +551,9 @@ pub extern "C" fn WarningMessage_eq(a: &WarningMessage, b: &WarningMessage) -> b use lightning::ln::msgs::Ping as nativePingImport; pub(crate) type nativePing = nativePingImport; -/// A ping message to be sent or received from a peer +/// A [`ping`] message to be sent to or received from a peer. +/// +/// [`ping`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-ping-and-pong-messages #[must_use] #[repr(C)] pub struct Ping { @@ -581,18 +600,19 @@ impl Ping { ret } } -/// The desired response length +/// The desired response length. #[no_mangle] pub extern "C" fn Ping_get_ponglen(this_ptr: &Ping) -> u16 { let mut inner_val = &mut this_ptr.get_native_mut_ref().ponglen; *inner_val } -/// The desired response length +/// The desired response length. #[no_mangle] pub extern "C" fn Ping_set_ponglen(this_ptr: &mut Ping, mut val: u16) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.ponglen = val; } /// The ping packet size. +/// /// This field is not sent on the wire. byteslen zeros are sent. #[no_mangle] pub extern "C" fn Ping_get_byteslen(this_ptr: &Ping) -> u16 { @@ -600,6 +620,7 @@ pub extern "C" fn Ping_get_byteslen(this_ptr: &Ping) -> u16 { *inner_val } /// The ping packet size. +/// /// This field is not sent on the wire. byteslen zeros are sent. #[no_mangle] pub extern "C" fn Ping_set_byteslen(this_ptr: &mut Ping, mut val: u16) { @@ -646,7 +667,9 @@ pub extern "C" fn Ping_eq(a: &Ping, b: &Ping) -> bool { use lightning::ln::msgs::Pong as nativePongImport; pub(crate) type nativePong = nativePongImport; -/// A pong message to be sent or received from a peer +/// A [`pong`] message to be sent to or received from a peer. +/// +/// [`pong`]: https://github.com/lightning/bolts/blob/master/01-messaging.md#the-ping-and-pong-messages #[must_use] #[repr(C)] pub struct Pong { @@ -694,6 +717,7 @@ impl Pong { } } /// The pong packet size. +/// /// This field is not sent on the wire. byteslen zeros are sent. #[no_mangle] pub extern "C" fn Pong_get_byteslen(this_ptr: &Pong) -> u16 { @@ -701,6 +725,7 @@ pub extern "C" fn Pong_get_byteslen(this_ptr: &Pong) -> u16 { *inner_val } /// The pong packet size. +/// /// This field is not sent on the wire. byteslen zeros are sent. #[no_mangle] pub extern "C" fn Pong_set_byteslen(this_ptr: &mut Pong, mut val: u16) { @@ -746,7 +771,9 @@ pub extern "C" fn Pong_eq(a: &Pong, b: &Pong) -> bool { use lightning::ln::msgs::OpenChannel as nativeOpenChannelImport; pub(crate) type nativeOpenChannel = nativeOpenChannelImport; -/// An open_channel message to be sent or received from a peer +/// An [`open_channel`] message to be sent to or received from a peer. +/// +/// [`open_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-open_channel-message #[must_use] #[repr(C)] pub struct OpenChannel { @@ -881,24 +908,28 @@ pub extern "C" fn OpenChannel_get_htlc_minimum_msat(this_ptr: &OpenChannel) -> u pub extern "C" fn OpenChannel_set_htlc_minimum_msat(this_ptr: &mut OpenChannel, mut val: u64) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_minimum_msat = val; } -/// The feerate per 1000-weight of sender generated transactions, until updated by update_fee +/// The feerate per 1000-weight of sender generated transactions, until updated by +/// [`UpdateFee`] #[no_mangle] pub extern "C" fn OpenChannel_get_feerate_per_kw(this_ptr: &OpenChannel) -> u32 { let mut inner_val = &mut this_ptr.get_native_mut_ref().feerate_per_kw; *inner_val } -/// The feerate per 1000-weight of sender generated transactions, until updated by update_fee +/// The feerate per 1000-weight of sender generated transactions, until updated by +/// [`UpdateFee`] #[no_mangle] pub extern "C" fn OpenChannel_set_feerate_per_kw(this_ptr: &mut OpenChannel, mut val: u32) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.feerate_per_kw = val; } -/// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction +/// The number of blocks which the counterparty will have to wait to claim on-chain funds if +/// they broadcast a commitment transaction #[no_mangle] pub extern "C" fn OpenChannel_get_to_self_delay(this_ptr: &OpenChannel) -> u16 { let mut inner_val = &mut this_ptr.get_native_mut_ref().to_self_delay; *inner_val } -/// The number of blocks which the counterparty will have to wait to claim on-chain funds if they broadcast a commitment transaction +/// The number of blocks which the counterparty will have to wait to claim on-chain funds if +/// they broadcast a commitment transaction #[no_mangle] pub extern "C" fn OpenChannel_set_to_self_delay(this_ptr: &mut OpenChannel, mut val: u16) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.to_self_delay = val; @@ -980,20 +1011,21 @@ pub extern "C" fn OpenChannel_get_first_per_commitment_point(this_ptr: &OpenChan pub extern "C" fn OpenChannel_set_first_per_commitment_point(this_ptr: &mut OpenChannel, mut val: crate::c_types::PublicKey) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.first_per_commitment_point = val.into_rust(); } -/// Channel flags +/// The channel flags to be used #[no_mangle] pub extern "C" fn OpenChannel_get_channel_flags(this_ptr: &OpenChannel) -> u8 { let mut inner_val = &mut this_ptr.get_native_mut_ref().channel_flags; *inner_val } -/// Channel flags +/// The channel flags to be used #[no_mangle] pub extern "C" fn OpenChannel_set_channel_flags(this_ptr: &mut OpenChannel, mut val: u8) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_flags = val; } -/// The channel type that this channel will represent. If none is set, we derive the channel -/// type from the intersection of our feature bits with our counterparty's feature bits from -/// the Init message. +/// The channel type that this channel will represent +/// +/// If this is `None`, we derive the channel type from the intersection of our +/// feature bits with our counterparty's feature bits from the [`Init`] message. /// /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[no_mangle] @@ -1002,9 +1034,10 @@ pub extern "C" fn OpenChannel_get_channel_type(this_ptr: &OpenChannel) -> crate: let mut local_inner_val = crate::lightning::ln::features::ChannelTypeFeatures { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::ln::features::ChannelTypeFeatures<>) as *mut _ }, is_owned: false }; local_inner_val } -/// The channel type that this channel will represent. If none is set, we derive the channel -/// type from the intersection of our feature bits with our counterparty's feature bits from -/// the Init message. +/// The channel type that this channel will represent +/// +/// If this is `None`, we derive the channel type from the intersection of our +/// feature bits with our counterparty's feature bits from the [`Init`] message. /// /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None #[no_mangle] @@ -1044,7 +1077,9 @@ pub extern "C" fn OpenChannel_eq(a: &OpenChannel, b: &OpenChannel) -> bool { use lightning::ln::msgs::AcceptChannel as nativeAcceptChannelImport; pub(crate) type nativeAcceptChannel = nativeAcceptChannelImport; -/// An accept_channel message to be sent or received from a peer +/// An [`accept_channel`] message to be sent to or received from a peer. +/// +/// [`accept_channel`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-accept_channel-message #[must_use] #[repr(C)] pub struct AcceptChannel { @@ -1245,10 +1280,10 @@ pub extern "C" fn AcceptChannel_get_first_per_commitment_point(this_ptr: &Accept pub extern "C" fn AcceptChannel_set_first_per_commitment_point(this_ptr: &mut AcceptChannel, mut val: crate::c_types::PublicKey) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.first_per_commitment_point = val.into_rust(); } -/// The channel type that this channel will represent. If none is set, we derive the channel -/// type from the intersection of our feature bits with our counterparty's feature bits from -/// the Init message. +/// The channel type that this channel will represent. /// +/// If this is `None`, we derive the channel type from the intersection of +/// our feature bits with our counterparty's feature bits from the [`Init`] message. /// This is required to match the equivalent field in [`OpenChannel::channel_type`]. /// /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None @@ -1258,10 +1293,10 @@ pub extern "C" fn AcceptChannel_get_channel_type(this_ptr: &AcceptChannel) -> cr let mut local_inner_val = crate::lightning::ln::features::ChannelTypeFeatures { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::ln::features::ChannelTypeFeatures<>) as *mut _ }, is_owned: false }; local_inner_val } -/// The channel type that this channel will represent. If none is set, we derive the channel -/// type from the intersection of our feature bits with our counterparty's feature bits from -/// the Init message. +/// The channel type that this channel will represent. /// +/// If this is `None`, we derive the channel type from the intersection of +/// our feature bits with our counterparty's feature bits from the [`Init`] message. /// This is required to match the equivalent field in [`OpenChannel::channel_type`]. /// /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None @@ -1302,7 +1337,9 @@ pub extern "C" fn AcceptChannel_eq(a: &AcceptChannel, b: &AcceptChannel) -> bool use lightning::ln::msgs::FundingCreated as nativeFundingCreatedImport; pub(crate) type nativeFundingCreated = nativeFundingCreatedImport; -/// A funding_created message to be sent or received from a peer +/// A [`funding_created`] message to be sent to or received from a peer. +/// +/// [`funding_created`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-funding_created-message #[must_use] #[repr(C)] pub struct FundingCreated { @@ -1436,7 +1473,9 @@ pub extern "C" fn FundingCreated_eq(a: &FundingCreated, b: &FundingCreated) -> b use lightning::ln::msgs::FundingSigned as nativeFundingSignedImport; pub(crate) type nativeFundingSigned = nativeFundingSignedImport; -/// A funding_signed message to be sent or received from a peer +/// A [`funding_signed`] message to be sent to or received from a peer. +/// +/// [`funding_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-funding_signed-message #[must_use] #[repr(C)] pub struct FundingSigned { @@ -1546,7 +1585,9 @@ pub extern "C" fn FundingSigned_eq(a: &FundingSigned, b: &FundingSigned) -> bool use lightning::ln::msgs::ChannelReady as nativeChannelReadyImport; pub(crate) type nativeChannelReady = nativeChannelReadyImport; -/// A channel_ready message to be sent or received from a peer +/// A [`channel_ready`] message to be sent to or received from a peer. +/// +/// [`channel_ready`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#the-channel_ready-message #[must_use] #[repr(C)] pub struct ChannelReady { @@ -1615,16 +1656,20 @@ pub extern "C" fn ChannelReady_get_next_per_commitment_point(this_ptr: &ChannelR pub extern "C" fn ChannelReady_set_next_per_commitment_point(this_ptr: &mut ChannelReady, mut val: crate::c_types::PublicKey) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.next_per_commitment_point = val.into_rust(); } -/// If set, provides a short_channel_id alias for this channel. The sender will accept payments -/// to be forwarded over this SCID and forward them to this messages' recipient. +/// If set, provides a `short_channel_id` alias for this channel. +/// +/// The sender will accept payments to be forwarded over this SCID and forward them to this +/// messages' recipient. #[no_mangle] pub extern "C" fn ChannelReady_get_short_channel_id_alias(this_ptr: &ChannelReady) -> crate::c_types::derived::COption_u64Z { let mut inner_val = &mut this_ptr.get_native_mut_ref().short_channel_id_alias; 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() }) }; local_inner_val } -/// If set, provides a short_channel_id alias for this channel. The sender will accept payments -/// to be forwarded over this SCID and forward them to this messages' recipient. +/// If set, provides a `short_channel_id` alias for this channel. +/// +/// The sender will accept payments to be forwarded over this SCID and forward them to this +/// messages' recipient. #[no_mangle] pub extern "C" fn ChannelReady_set_short_channel_id_alias(this_ptr: &mut ChannelReady, mut val: crate::c_types::derived::COption_u64Z) { let mut local_val = if val.is_some() { Some( { val.take() }) } else { None }; @@ -1673,7 +1718,9 @@ pub extern "C" fn ChannelReady_eq(a: &ChannelReady, b: &ChannelReady) -> bool { use lightning::ln::msgs::Shutdown as nativeShutdownImport; pub(crate) type nativeShutdown = nativeShutdownImport; -/// A shutdown message to be sent or received from a peer +/// A [`shutdown`] message to be sent to or received from a peer. +/// +/// [`shutdown`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-initiation-shutdown #[must_use] #[repr(C)] pub struct Shutdown { @@ -1732,14 +1779,16 @@ pub extern "C" fn Shutdown_set_channel_id(this_ptr: &mut Shutdown, mut val: crat unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channel_id = val.data; } /// The destination of this peer's funds on closing. -/// Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh. +/// +/// Must be in one of these forms: P2PKH, P2SH, P2WPKH, P2WSH, P2TR. #[no_mangle] pub extern "C" fn Shutdown_get_scriptpubkey(this_ptr: &Shutdown) -> crate::c_types::u8slice { let mut inner_val = &mut this_ptr.get_native_mut_ref().scriptpubkey; crate::c_types::u8slice::from_slice(&inner_val[..]) } /// The destination of this peer's funds on closing. -/// Must be in one of these forms: p2pkh, p2sh, p2wpkh, p2wsh. +/// +/// Must be in one of these forms: P2PKH, P2SH, P2WPKH, P2WSH, P2TR. #[no_mangle] pub extern "C" fn Shutdown_set_scriptpubkey(this_ptr: &mut Shutdown, mut val: crate::c_types::derived::CVec_u8Z) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.scriptpubkey = ::bitcoin::blockdata::script::Script::from(val.into_rust()); @@ -1786,6 +1835,7 @@ use lightning::ln::msgs::ClosingSignedFeeRange as nativeClosingSignedFeeRangeImp pub(crate) type nativeClosingSignedFeeRange = nativeClosingSignedFeeRangeImport; /// The minimum and maximum fees which the sender is willing to place on the closing transaction. +/// /// This is provided in [`ClosingSigned`] by both sides to indicate the fee range they are willing /// to use. #[must_use] @@ -1901,7 +1951,9 @@ pub extern "C" fn ClosingSignedFeeRange_eq(a: &ClosingSignedFeeRange, b: &Closin use lightning::ln::msgs::ClosingSigned as nativeClosingSignedImport; pub(crate) type nativeClosingSigned = nativeClosingSignedImport; -/// A closing_signed message to be sent or received from a peer +/// A [`closing_signed`] message to be sent to or received from a peer. +/// +/// [`closing_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#closing-negotiation-closing_signed #[must_use] #[repr(C)] pub struct ClosingSigned { @@ -2044,7 +2096,9 @@ pub extern "C" fn ClosingSigned_eq(a: &ClosingSigned, b: &ClosingSigned) -> bool use lightning::ln::msgs::UpdateAddHTLC as nativeUpdateAddHTLCImport; pub(crate) type nativeUpdateAddHTLC = nativeUpdateAddHTLCImport; -/// An update_add_htlc message to be sent or received from a peer +/// An [`update_add_htlc`] message to be sent to or received from a peer. +/// +/// [`update_add_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#adding-an-htlc-update_add_htlc #[must_use] #[repr(C)] pub struct UpdateAddHTLC { @@ -2178,7 +2232,8 @@ pub extern "C" fn UpdateAddHTLC_eq(a: &UpdateAddHTLC, b: &UpdateAddHTLC) -> bool use lightning::ln::msgs::OnionMessage as nativeOnionMessageImport; pub(crate) type nativeOnionMessage = nativeOnionMessageImport; -/// An onion message to be sent or received from a peer +/// An onion message to be sent to or received from a peer. +/// #[must_use] #[repr(C)] pub struct OnionMessage { @@ -2268,7 +2323,9 @@ pub extern "C" fn OnionMessage_eq(a: &OnionMessage, b: &OnionMessage) -> bool { use lightning::ln::msgs::UpdateFulfillHTLC as nativeUpdateFulfillHTLCImport; pub(crate) type nativeUpdateFulfillHTLC = nativeUpdateFulfillHTLCImport; -/// An update_fulfill_htlc message to be sent or received from a peer +/// An [`update_fulfill_htlc`] message to be sent to or received from a peer. +/// +/// [`update_fulfill_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc #[must_use] #[repr(C)] pub struct UpdateFulfillHTLC { @@ -2390,7 +2447,9 @@ pub extern "C" fn UpdateFulfillHTLC_eq(a: &UpdateFulfillHTLC, b: &UpdateFulfillH use lightning::ln::msgs::UpdateFailHTLC as nativeUpdateFailHTLCImport; pub(crate) type nativeUpdateFailHTLC = nativeUpdateFailHTLCImport; -/// An update_fail_htlc message to be sent or received from a peer +/// An [`update_fail_htlc`] message to be sent to or received from a peer. +/// +/// [`update_fail_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc #[must_use] #[repr(C)] pub struct UpdateFailHTLC { @@ -2491,7 +2550,9 @@ pub extern "C" fn UpdateFailHTLC_eq(a: &UpdateFailHTLC, b: &UpdateFailHTLC) -> b use lightning::ln::msgs::UpdateFailMalformedHTLC as nativeUpdateFailMalformedHTLCImport; pub(crate) type nativeUpdateFailMalformedHTLC = nativeUpdateFailMalformedHTLCImport; -/// An update_fail_malformed_htlc message to be sent or received from a peer +/// An [`update_fail_malformed_htlc`] message to be sent to or received from a peer. +/// +/// [`update_fail_malformed_htlc`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#removing-an-htlc-update_fulfill_htlc-update_fail_htlc-and-update_fail_malformed_htlc #[must_use] #[repr(C)] pub struct UpdateFailMalformedHTLC { @@ -2603,7 +2664,9 @@ pub extern "C" fn UpdateFailMalformedHTLC_eq(a: &UpdateFailMalformedHTLC, b: &Up use lightning::ln::msgs::CommitmentSigned as nativeCommitmentSignedImport; pub(crate) type nativeCommitmentSigned = nativeCommitmentSignedImport; -/// A commitment_signed message to be sent or received from a peer +/// A [`commitment_signed`] message to be sent to or received from a peer. +/// +/// [`commitment_signed`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#committing-updates-so-far-commitment_signed #[must_use] #[repr(C)] pub struct CommitmentSigned { @@ -2730,7 +2793,9 @@ pub extern "C" fn CommitmentSigned_eq(a: &CommitmentSigned, b: &CommitmentSigned use lightning::ln::msgs::RevokeAndACK as nativeRevokeAndACKImport; pub(crate) type nativeRevokeAndACK = nativeRevokeAndACKImport; -/// A revoke_and_ack message to be sent or received from a peer +/// A [`revoke_and_ack`] message to be sent to or received from a peer. +/// +/// [`revoke_and_ack`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#completing-the-transition-to-the-updated-state-revoke_and_ack #[must_use] #[repr(C)] pub struct RevokeAndACK { @@ -2852,7 +2917,9 @@ pub extern "C" fn RevokeAndACK_eq(a: &RevokeAndACK, b: &RevokeAndACK) -> bool { use lightning::ln::msgs::UpdateFee as nativeUpdateFeeImport; pub(crate) type nativeUpdateFee = nativeUpdateFeeImport; -/// An update_fee message to be sent or received from a peer +/// An [`update_fee`] message to be sent to or received from a peer +/// +/// [`update_fee`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#updating-fees-update_fee #[must_use] #[repr(C)] pub struct UpdateFee { @@ -2963,8 +3030,9 @@ use lightning::ln::msgs::DataLossProtect as nativeDataLossProtectImport; pub(crate) type nativeDataLossProtect = nativeDataLossProtectImport; /// Proof that the sender knows the per-commitment secret of the previous commitment transaction. +/// /// This is used to convince the recipient that the channel is at a certain commitment -/// number even if they lost that data due to a local failure. Of course, the peer may lie +/// number even if they lost that data due to a local failure. Of course, the peer may lie /// and even later commitments may have been revoked. #[must_use] #[repr(C)] @@ -3077,7 +3145,9 @@ pub extern "C" fn DataLossProtect_eq(a: &DataLossProtect, b: &DataLossProtect) - use lightning::ln::msgs::ChannelReestablish as nativeChannelReestablishImport; pub(crate) type nativeChannelReestablish = nativeChannelReestablishImport; -/// A channel_reestablish message to be sent or received from a peer +/// A [`channel_reestablish`] message to be sent to or received from a peer. +/// +/// [`channel_reestablish`]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md#message-retransmission #[must_use] #[repr(C)] pub struct ChannelReestablish { @@ -3189,7 +3259,9 @@ pub extern "C" fn ChannelReestablish_eq(a: &ChannelReestablish, b: &ChannelReest use lightning::ln::msgs::AnnouncementSignatures as nativeAnnouncementSignaturesImport; pub(crate) type nativeAnnouncementSignatures = nativeAnnouncementSignaturesImport; -/// An announcement_signatures message to be sent or received from a peer +/// An [`announcement_signatures`] message to be sent to or received from a peer. +/// +/// [`announcement_signatures`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-announcement_signatures-message #[must_use] #[repr(C)] pub struct AnnouncementSignatures { @@ -3319,7 +3391,7 @@ pub extern "C" fn AnnouncementSignatures_eq(a: &AnnouncementSignatures, b: &Anno if a.inner.is_null() || b.inner.is_null() { return false; } if a.get_native_ref() == b.get_native_ref() { true } else { false } } -/// An address which can be used to connect to a remote peer +/// An address which can be used to connect to a remote peer. #[derive(Clone)] #[must_use] #[repr(C)] @@ -3345,7 +3417,8 @@ pub enum NetAddress { OnionV2( crate::c_types::TwelveBytes), /// A new-style Tor onion address/port on which the peer is listening. - /// To create the human-readable \"hostname\", concatenate ed25519_pubkey, checksum, and version, + /// + /// To create the human-readable \"hostname\", concatenate the ED25519 pubkey, checksum, and version, /// wrap as base32 and append \".onion\". OnionV3 { /// The ed25519 long-term public key of the peer @@ -3601,11 +3674,147 @@ pub extern "C" fn NetAddress_read(ser: crate::c_types::u8slice) -> crate::c_type let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::NetAddress::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } +/// Represents the set of gossip messages that require a signature from a node's identity key. +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum UnsignedGossipMessage { + /// An unsigned channel announcement. + ChannelAnnouncement( + crate::lightning::ln::msgs::UnsignedChannelAnnouncement), + /// An unsigned channel update. + ChannelUpdate( + crate::lightning::ln::msgs::UnsignedChannelUpdate), + /// An unsigned node announcement. + NodeAnnouncement( + crate::lightning::ln::msgs::UnsignedNodeAnnouncement), +} +use lightning::ln::msgs::UnsignedGossipMessage as UnsignedGossipMessageImport; +pub(crate) type nativeUnsignedGossipMessage = UnsignedGossipMessageImport; + +impl UnsignedGossipMessage { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeUnsignedGossipMessage { + match self { + UnsignedGossipMessage::ChannelAnnouncement (ref a, ) => { + let mut a_nonref = Clone::clone(a); + nativeUnsignedGossipMessage::ChannelAnnouncement ( + *unsafe { Box::from_raw(a_nonref.take_inner()) }, + ) + }, + UnsignedGossipMessage::ChannelUpdate (ref a, ) => { + let mut a_nonref = Clone::clone(a); + nativeUnsignedGossipMessage::ChannelUpdate ( + *unsafe { Box::from_raw(a_nonref.take_inner()) }, + ) + }, + UnsignedGossipMessage::NodeAnnouncement (ref a, ) => { + let mut a_nonref = Clone::clone(a); + nativeUnsignedGossipMessage::NodeAnnouncement ( + *unsafe { Box::from_raw(a_nonref.take_inner()) }, + ) + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeUnsignedGossipMessage { + match self { + UnsignedGossipMessage::ChannelAnnouncement (mut a, ) => { + nativeUnsignedGossipMessage::ChannelAnnouncement ( + *unsafe { Box::from_raw(a.take_inner()) }, + ) + }, + UnsignedGossipMessage::ChannelUpdate (mut a, ) => { + nativeUnsignedGossipMessage::ChannelUpdate ( + *unsafe { Box::from_raw(a.take_inner()) }, + ) + }, + UnsignedGossipMessage::NodeAnnouncement (mut a, ) => { + nativeUnsignedGossipMessage::NodeAnnouncement ( + *unsafe { Box::from_raw(a.take_inner()) }, + ) + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeUnsignedGossipMessage) -> Self { + match native { + nativeUnsignedGossipMessage::ChannelAnnouncement (ref a, ) => { + let mut a_nonref = Clone::clone(a); + UnsignedGossipMessage::ChannelAnnouncement ( + crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, + ) + }, + nativeUnsignedGossipMessage::ChannelUpdate (ref a, ) => { + let mut a_nonref = Clone::clone(a); + UnsignedGossipMessage::ChannelUpdate ( + crate::lightning::ln::msgs::UnsignedChannelUpdate { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, + ) + }, + nativeUnsignedGossipMessage::NodeAnnouncement (ref a, ) => { + let mut a_nonref = Clone::clone(a); + UnsignedGossipMessage::NodeAnnouncement ( + crate::lightning::ln::msgs::UnsignedNodeAnnouncement { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, + ) + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeUnsignedGossipMessage) -> Self { + match native { + nativeUnsignedGossipMessage::ChannelAnnouncement (mut a, ) => { + UnsignedGossipMessage::ChannelAnnouncement ( + crate::lightning::ln::msgs::UnsignedChannelAnnouncement { inner: ObjOps::heap_alloc(a), is_owned: true }, + ) + }, + nativeUnsignedGossipMessage::ChannelUpdate (mut a, ) => { + UnsignedGossipMessage::ChannelUpdate ( + crate::lightning::ln::msgs::UnsignedChannelUpdate { inner: ObjOps::heap_alloc(a), is_owned: true }, + ) + }, + nativeUnsignedGossipMessage::NodeAnnouncement (mut a, ) => { + UnsignedGossipMessage::NodeAnnouncement ( + crate::lightning::ln::msgs::UnsignedNodeAnnouncement { inner: ObjOps::heap_alloc(a), is_owned: true }, + ) + }, + } + } +} +/// Frees any resources used by the UnsignedGossipMessage +#[no_mangle] +pub extern "C" fn UnsignedGossipMessage_free(this_ptr: UnsignedGossipMessage) { } +/// Creates a copy of the UnsignedGossipMessage +#[no_mangle] +pub extern "C" fn UnsignedGossipMessage_clone(orig: &UnsignedGossipMessage) -> UnsignedGossipMessage { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new ChannelAnnouncement-variant UnsignedGossipMessage +pub extern "C" fn UnsignedGossipMessage_channel_announcement(a: crate::lightning::ln::msgs::UnsignedChannelAnnouncement) -> UnsignedGossipMessage { + UnsignedGossipMessage::ChannelAnnouncement(a, ) +} +#[no_mangle] +/// Utility method to constructs a new ChannelUpdate-variant UnsignedGossipMessage +pub extern "C" fn UnsignedGossipMessage_channel_update(a: crate::lightning::ln::msgs::UnsignedChannelUpdate) -> UnsignedGossipMessage { + UnsignedGossipMessage::ChannelUpdate(a, ) +} +#[no_mangle] +/// Utility method to constructs a new NodeAnnouncement-variant UnsignedGossipMessage +pub extern "C" fn UnsignedGossipMessage_node_announcement(a: crate::lightning::ln::msgs::UnsignedNodeAnnouncement) -> UnsignedGossipMessage { + UnsignedGossipMessage::NodeAnnouncement(a, ) +} +#[no_mangle] +/// Serialize the UnsignedGossipMessage object into a byte array which can be read by UnsignedGossipMessage_read +pub extern "C" fn UnsignedGossipMessage_write(obj: &crate::lightning::ln::msgs::UnsignedGossipMessage) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(&unsafe { &*obj }.to_native()) +} use lightning::ln::msgs::UnsignedNodeAnnouncement as nativeUnsignedNodeAnnouncementImport; pub(crate) type nativeUnsignedNodeAnnouncement = nativeUnsignedNodeAnnouncementImport; -/// The unsigned part of a node_announcement +/// The unsigned part of a [`node_announcement`] message. +/// +/// [`node_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message #[must_use] #[repr(C)] pub struct UnsignedNodeAnnouncement { @@ -3674,18 +3883,18 @@ pub extern "C" fn UnsignedNodeAnnouncement_get_timestamp(this_ptr: &UnsignedNode pub extern "C" fn UnsignedNodeAnnouncement_set_timestamp(this_ptr: &mut UnsignedNodeAnnouncement, mut val: u32) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.timestamp = val; } -/// The node_id this announcement originated from (don't rebroadcast the node_announcement back +/// The `node_id` this announcement originated from (don't rebroadcast the `node_announcement` back /// to this node). #[no_mangle] -pub extern "C" fn UnsignedNodeAnnouncement_get_node_id(this_ptr: &UnsignedNodeAnnouncement) -> crate::c_types::PublicKey { +pub extern "C" fn UnsignedNodeAnnouncement_get_node_id(this_ptr: &UnsignedNodeAnnouncement) -> crate::lightning::routing::gossip::NodeId { let mut inner_val = &mut this_ptr.get_native_mut_ref().node_id; - crate::c_types::PublicKey::from_rust(&inner_val) + crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false } } -/// The node_id this announcement originated from (don't rebroadcast the node_announcement back +/// The `node_id` this announcement originated from (don't rebroadcast the `node_announcement` back /// to this node). #[no_mangle] -pub extern "C" fn UnsignedNodeAnnouncement_set_node_id(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::c_types::PublicKey) { - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id = val.into_rust(); +pub extern "C" fn UnsignedNodeAnnouncement_set_node_id(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::lightning::routing::gossip::NodeId) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id = *unsafe { Box::from_raw(val.take_inner()) }; } /// An RGB color for UI purposes #[no_mangle] @@ -3698,15 +3907,17 @@ pub extern "C" fn UnsignedNodeAnnouncement_get_rgb(this_ptr: &UnsignedNodeAnnoun pub extern "C" fn UnsignedNodeAnnouncement_set_rgb(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::c_types::ThreeBytes) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.rgb = val.data; } -/// An alias, for UI purposes. This should be sanitized before use. There is no guarantee -/// of uniqueness. +/// An alias, for UI purposes. +/// +/// This should be sanitized before use. There is no guarantee of uniqueness. #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_get_alias(this_ptr: &UnsignedNodeAnnouncement) -> *const [u8; 32] { let mut inner_val = &mut this_ptr.get_native_mut_ref().alias; inner_val } -/// An alias, for UI purposes. This should be sanitized before use. There is no guarantee -/// of uniqueness. +/// An alias, for UI purposes. +/// +/// This should be sanitized before use. There is no guarantee of uniqueness. #[no_mangle] pub extern "C" fn UnsignedNodeAnnouncement_set_alias(this_ptr: &mut UnsignedNodeAnnouncement, mut val: crate::c_types::ThirtyTwoBytes) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.alias = val.data; @@ -3758,7 +3969,9 @@ pub extern "C" fn UnsignedNodeAnnouncement_eq(a: &UnsignedNodeAnnouncement, b: & use lightning::ln::msgs::NodeAnnouncement as nativeNodeAnnouncementImport; pub(crate) type nativeNodeAnnouncement = nativeNodeAnnouncementImport; -/// A node_announcement message to be sent or received from a peer +/// A [`node_announcement`] message to be sent to or received from a peer. +/// +/// [`node_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-node_announcement-message #[must_use] #[repr(C)] pub struct NodeAnnouncement { @@ -3868,7 +4081,9 @@ pub extern "C" fn NodeAnnouncement_eq(a: &NodeAnnouncement, b: &NodeAnnouncement use lightning::ln::msgs::UnsignedChannelAnnouncement as nativeUnsignedChannelAnnouncementImport; pub(crate) type nativeUnsignedChannelAnnouncement = nativeUnsignedChannelAnnouncementImport; -/// The unsigned part of a channel_announcement +/// The unsigned part of a [`channel_announcement`] message. +/// +/// [`channel_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message #[must_use] #[repr(C)] pub struct UnsignedChannelAnnouncement { @@ -3948,49 +4163,49 @@ pub extern "C" fn UnsignedChannelAnnouncement_get_short_channel_id(this_ptr: &Un pub extern "C" fn UnsignedChannelAnnouncement_set_short_channel_id(this_ptr: &mut UnsignedChannelAnnouncement, mut val: u64) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.short_channel_id = val; } -/// One of the two node_ids which are endpoints of this channel +/// One of the two `node_id`s which are endpoints of this channel #[no_mangle] -pub extern "C" fn UnsignedChannelAnnouncement_get_node_id_1(this_ptr: &UnsignedChannelAnnouncement) -> crate::c_types::PublicKey { +pub extern "C" fn UnsignedChannelAnnouncement_get_node_id_1(this_ptr: &UnsignedChannelAnnouncement) -> crate::lightning::routing::gossip::NodeId { let mut inner_val = &mut this_ptr.get_native_mut_ref().node_id_1; - crate::c_types::PublicKey::from_rust(&inner_val) + crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false } } -/// One of the two node_ids which are endpoints of this channel +/// One of the two `node_id`s which are endpoints of this channel #[no_mangle] -pub extern "C" fn UnsignedChannelAnnouncement_set_node_id_1(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::PublicKey) { - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id_1 = val.into_rust(); +pub extern "C" fn UnsignedChannelAnnouncement_set_node_id_1(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::lightning::routing::gossip::NodeId) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id_1 = *unsafe { Box::from_raw(val.take_inner()) }; } -/// The other of the two node_ids which are endpoints of this channel +/// The other of the two `node_id`s which are endpoints of this channel #[no_mangle] -pub extern "C" fn UnsignedChannelAnnouncement_get_node_id_2(this_ptr: &UnsignedChannelAnnouncement) -> crate::c_types::PublicKey { +pub extern "C" fn UnsignedChannelAnnouncement_get_node_id_2(this_ptr: &UnsignedChannelAnnouncement) -> crate::lightning::routing::gossip::NodeId { let mut inner_val = &mut this_ptr.get_native_mut_ref().node_id_2; - crate::c_types::PublicKey::from_rust(&inner_val) + crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false } } -/// The other of the two node_ids which are endpoints of this channel +/// The other of the two `node_id`s which are endpoints of this channel #[no_mangle] -pub extern "C" fn UnsignedChannelAnnouncement_set_node_id_2(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::PublicKey) { - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id_2 = val.into_rust(); +pub extern "C" fn UnsignedChannelAnnouncement_set_node_id_2(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::lightning::routing::gossip::NodeId) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.node_id_2 = *unsafe { Box::from_raw(val.take_inner()) }; } /// The funding key for the first node #[no_mangle] -pub extern "C" fn UnsignedChannelAnnouncement_get_bitcoin_key_1(this_ptr: &UnsignedChannelAnnouncement) -> crate::c_types::PublicKey { +pub extern "C" fn UnsignedChannelAnnouncement_get_bitcoin_key_1(this_ptr: &UnsignedChannelAnnouncement) -> crate::lightning::routing::gossip::NodeId { let mut inner_val = &mut this_ptr.get_native_mut_ref().bitcoin_key_1; - crate::c_types::PublicKey::from_rust(&inner_val) + crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false } } /// The funding key for the first node #[no_mangle] -pub extern "C" fn UnsignedChannelAnnouncement_set_bitcoin_key_1(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::PublicKey) { - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.bitcoin_key_1 = val.into_rust(); +pub extern "C" fn UnsignedChannelAnnouncement_set_bitcoin_key_1(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::lightning::routing::gossip::NodeId) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.bitcoin_key_1 = *unsafe { Box::from_raw(val.take_inner()) }; } /// The funding key for the second node #[no_mangle] -pub extern "C" fn UnsignedChannelAnnouncement_get_bitcoin_key_2(this_ptr: &UnsignedChannelAnnouncement) -> crate::c_types::PublicKey { +pub extern "C" fn UnsignedChannelAnnouncement_get_bitcoin_key_2(this_ptr: &UnsignedChannelAnnouncement) -> crate::lightning::routing::gossip::NodeId { let mut inner_val = &mut this_ptr.get_native_mut_ref().bitcoin_key_2; - crate::c_types::PublicKey::from_rust(&inner_val) + crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false } } /// The funding key for the second node #[no_mangle] -pub extern "C" fn UnsignedChannelAnnouncement_set_bitcoin_key_2(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::c_types::PublicKey) { - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.bitcoin_key_2 = val.into_rust(); +pub extern "C" fn UnsignedChannelAnnouncement_set_bitcoin_key_2(this_ptr: &mut UnsignedChannelAnnouncement, mut val: crate::lightning::routing::gossip::NodeId) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.bitcoin_key_2 = *unsafe { Box::from_raw(val.take_inner()) }; } impl Clone for UnsignedChannelAnnouncement { fn clone(&self) -> Self { @@ -4024,7 +4239,9 @@ pub extern "C" fn UnsignedChannelAnnouncement_eq(a: &UnsignedChannelAnnouncement use lightning::ln::msgs::ChannelAnnouncement as nativeChannelAnnouncementImport; pub(crate) type nativeChannelAnnouncement = nativeChannelAnnouncementImport; -/// A channel_announcement message to be sent or received from a peer +/// A [`channel_announcement`] message to be sent to or received from a peer. +/// +/// [`channel_announcement`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_announcement-message #[must_use] #[repr(C)] pub struct ChannelAnnouncement { @@ -4170,7 +4387,9 @@ pub extern "C" fn ChannelAnnouncement_eq(a: &ChannelAnnouncement, b: &ChannelAnn use lightning::ln::msgs::UnsignedChannelUpdate as nativeUnsignedChannelUpdateImport; pub(crate) type nativeUnsignedChannelUpdate = nativeUnsignedChannelUpdateImport; -/// The unsigned part of a channel_update +/// The unsigned part of a [`channel_update`] message. +/// +/// [`channel_update`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message #[must_use] #[repr(C)] pub struct UnsignedChannelUpdate { @@ -4263,10 +4482,10 @@ pub extern "C" fn UnsignedChannelUpdate_set_flags(this_ptr: &mut UnsignedChannel } /// The number of blocks such that if: /// `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta` -/// then we need to fail the HTLC backwards. When forwarding an HTLC, cltv_expiry_delta determines -/// the outgoing HTLC's minimum cltv_expiry value -- so, if an incoming HTLC comes in with a -/// cltv_expiry of 100000, and the node we're forwarding to has a cltv_expiry_delta value of 10, -/// then we'll check that the outgoing HTLC's cltv_expiry value is at least 100010 before +/// then we need to fail the HTLC backwards. When forwarding an HTLC, `cltv_expiry_delta` determines +/// the outgoing HTLC's minimum `cltv_expiry` value -- so, if an incoming HTLC comes in with a +/// `cltv_expiry` of 100000, and the node we're forwarding to has a `cltv_expiry_delta` value of 10, +/// then we'll check that the outgoing HTLC's `cltv_expiry` value is at least 100010 before /// forwarding. Note that the HTLC sender is the one who originally sets this value when /// constructing the route. #[no_mangle] @@ -4276,10 +4495,10 @@ pub extern "C" fn UnsignedChannelUpdate_get_cltv_expiry_delta(this_ptr: &Unsigne } /// The number of blocks such that if: /// `incoming_htlc.cltv_expiry < outgoing_htlc.cltv_expiry + cltv_expiry_delta` -/// then we need to fail the HTLC backwards. When forwarding an HTLC, cltv_expiry_delta determines -/// the outgoing HTLC's minimum cltv_expiry value -- so, if an incoming HTLC comes in with a -/// cltv_expiry of 100000, and the node we're forwarding to has a cltv_expiry_delta value of 10, -/// then we'll check that the outgoing HTLC's cltv_expiry value is at least 100010 before +/// then we need to fail the HTLC backwards. When forwarding an HTLC, `cltv_expiry_delta` determines +/// the outgoing HTLC's minimum `cltv_expiry` value -- so, if an incoming HTLC comes in with a +/// `cltv_expiry` of 100000, and the node we're forwarding to has a `cltv_expiry_delta` value of 10, +/// then we'll check that the outgoing HTLC's `cltv_expiry` value is at least 100010 before /// forwarding. Note that the HTLC sender is the one who originally sets this value when /// constructing the route. #[no_mangle] @@ -4297,13 +4516,17 @@ pub extern "C" fn UnsignedChannelUpdate_get_htlc_minimum_msat(this_ptr: &Unsigne pub extern "C" fn UnsignedChannelUpdate_set_htlc_minimum_msat(this_ptr: &mut UnsignedChannelUpdate, mut val: u64) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_minimum_msat = val; } -/// The maximum HTLC value incoming to sender, in milli-satoshi. Used to be optional. +/// The maximum HTLC value incoming to sender, in milli-satoshi. +/// +/// This used to be optional. #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_get_htlc_maximum_msat(this_ptr: &UnsignedChannelUpdate) -> u64 { let mut inner_val = &mut this_ptr.get_native_mut_ref().htlc_maximum_msat; *inner_val } -/// The maximum HTLC value incoming to sender, in milli-satoshi. Used to be optional. +/// The maximum HTLC value incoming to sender, in milli-satoshi. +/// +/// This used to be optional. #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_htlc_maximum_msat(this_ptr: &mut UnsignedChannelUpdate, mut val: u64) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.htlc_maximum_msat = val; @@ -4331,8 +4554,9 @@ pub extern "C" fn UnsignedChannelUpdate_set_fee_proportional_millionths(this_ptr unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.fee_proportional_millionths = val; } /// Excess data which was signed as a part of the message which we do not (yet) understand how -/// to decode. This is stored to ensure forward-compatibility as new fields are added to the -/// lightning gossip +/// to decode. +/// +/// This is stored to ensure forward-compatibility as new fields are added to the lightning gossip protocol. /// /// Returns a copy of the field. #[no_mangle] @@ -4342,8 +4566,9 @@ pub extern "C" fn UnsignedChannelUpdate_get_excess_data(this_ptr: &UnsignedChann local_inner_val.into() } /// Excess data which was signed as a part of the message which we do not (yet) understand how -/// to decode. This is stored to ensure forward-compatibility as new fields are added to the -/// lightning gossip +/// to decode. +/// +/// This is stored to ensure forward-compatibility as new fields are added to the lightning gossip protocol. #[no_mangle] pub extern "C" fn UnsignedChannelUpdate_set_excess_data(this_ptr: &mut UnsignedChannelUpdate, mut val: crate::c_types::derived::CVec_u8Z) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item }); }; @@ -4399,7 +4624,9 @@ pub extern "C" fn UnsignedChannelUpdate_eq(a: &UnsignedChannelUpdate, b: &Unsign use lightning::ln::msgs::ChannelUpdate as nativeChannelUpdateImport; pub(crate) type nativeChannelUpdate = nativeChannelUpdateImport; -/// A channel_update message to be sent or received from a peer +/// A [`channel_update`] message to be sent to or received from a peer. +/// +/// [`channel_update`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message #[must_use] #[repr(C)] pub struct ChannelUpdate { @@ -4509,10 +4736,12 @@ pub extern "C" fn ChannelUpdate_eq(a: &ChannelUpdate, b: &ChannelUpdate) -> bool use lightning::ln::msgs::QueryChannelRange as nativeQueryChannelRangeImport; pub(crate) type nativeQueryChannelRange = nativeQueryChannelRangeImport; -/// A query_channel_range message is used to query a peer for channel +/// A [`query_channel_range`] message is used to query a peer for channel /// UTXOs in a range of blocks. The recipient of a query makes a best -/// effort to reply to the query using one or more reply_channel_range +/// effort to reply to the query using one or more [`ReplyChannelRange`] /// messages. +/// +/// [`query_channel_range`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_channel_range-and-reply_channel_range-messages #[must_use] #[repr(C)] pub struct QueryChannelRange { @@ -4634,13 +4863,17 @@ pub extern "C" fn QueryChannelRange_eq(a: &QueryChannelRange, b: &QueryChannelRa use lightning::ln::msgs::ReplyChannelRange as nativeReplyChannelRangeImport; pub(crate) type nativeReplyChannelRange = nativeReplyChannelRangeImport; -/// A reply_channel_range message is a reply to a query_channel_range -/// message. Multiple reply_channel_range messages can be sent in reply -/// to a single query_channel_range message. The query recipient makes a +/// A [`reply_channel_range`] message is a reply to a [`QueryChannelRange`] +/// message. +/// +/// Multiple `reply_channel_range` messages can be sent in reply +/// to a single [`QueryChannelRange`] message. The query recipient makes a /// best effort to respond based on their local network view which may -/// not be a perfect view of the network. The short_channel_ids in the -/// reply are encoded. We only support encoding_type=0 uncompressed -/// serialization and do not support encoding_type=1 zlib serialization. +/// not be a perfect view of the network. The `short_channel_id`s in the +/// reply are encoded. We only support `encoding_type=0` uncompressed +/// serialization and do not support `encoding_type=1` zlib serialization. +/// +/// [`reply_channel_range`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_channel_range-and-reply_channel_range-messages #[must_use] #[repr(C)] pub struct ReplyChannelRange { @@ -4731,7 +4964,7 @@ pub extern "C" fn ReplyChannelRange_get_sync_complete(this_ptr: &ReplyChannelRan pub extern "C" fn ReplyChannelRange_set_sync_complete(this_ptr: &mut ReplyChannelRange, mut val: bool) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.sync_complete = val; } -/// The short_channel_ids in the channel range +/// The `short_channel_id`s in the channel range /// /// Returns a copy of the field. #[no_mangle] @@ -4740,7 +4973,7 @@ pub extern "C" fn ReplyChannelRange_get_short_channel_ids(this_ptr: &ReplyChanne let mut local_inner_val = Vec::new(); for mut item in inner_val.drain(..) { local_inner_val.push( { item }); }; local_inner_val.into() } -/// The short_channel_ids in the channel range +/// The `short_channel_id`s in the channel range #[no_mangle] pub extern "C" fn ReplyChannelRange_set_short_channel_ids(this_ptr: &mut ReplyChannelRange, mut val: crate::c_types::derived::CVec_u64Z) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item }); }; @@ -4791,14 +5024,17 @@ pub extern "C" fn ReplyChannelRange_eq(a: &ReplyChannelRange, b: &ReplyChannelRa use lightning::ln::msgs::QueryShortChannelIds as nativeQueryShortChannelIdsImport; pub(crate) type nativeQueryShortChannelIds = nativeQueryShortChannelIdsImport; -/// A query_short_channel_ids message is used to query a peer for -/// routing gossip messages related to one or more short_channel_ids. +/// A [`query_short_channel_ids`] message is used to query a peer for +/// routing gossip messages related to one or more `short_channel_id`s. +/// /// The query recipient will reply with the latest, if available, -/// channel_announcement, channel_update and node_announcement messages -/// it maintains for the requested short_channel_ids followed by a -/// reply_short_channel_ids_end message. The short_channel_ids sent in -/// this query are encoded. We only support encoding_type=0 uncompressed -/// serialization and do not support encoding_type=1 zlib serialization. +/// [`ChannelAnnouncement`], [`ChannelUpdate`] and [`NodeAnnouncement`] messages +/// it maintains for the requested `short_channel_id`s followed by a +/// [`ReplyShortChannelIdsEnd`] message. The `short_channel_id`s sent in +/// this query are encoded. We only support `encoding_type=0` uncompressed +/// serialization and do not support `encoding_type=1` zlib serialization. +/// +/// [`query_short_channel_ids`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_short_channel_idsreply_short_channel_ids_end-messages #[must_use] #[repr(C)] pub struct QueryShortChannelIds { @@ -4913,10 +5149,12 @@ pub extern "C" fn QueryShortChannelIds_eq(a: &QueryShortChannelIds, b: &QuerySho use lightning::ln::msgs::ReplyShortChannelIdsEnd as nativeReplyShortChannelIdsEndImport; pub(crate) type nativeReplyShortChannelIdsEnd = nativeReplyShortChannelIdsEndImport; -/// A reply_short_channel_ids_end message is sent as a reply to a -/// query_short_channel_ids message. The query recipient makes a best +/// A [`reply_short_channel_ids_end`] message is sent as a reply to a +/// message. The query recipient makes a best /// effort to respond based on their local network view which may not be /// a perfect view of the network. +/// +/// [`reply_short_channel_ids_end`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-query_short_channel_idsreply_short_channel_ids_end-messages #[must_use] #[repr(C)] pub struct ReplyShortChannelIdsEnd { @@ -4975,14 +5213,14 @@ pub extern "C" fn ReplyShortChannelIdsEnd_set_chain_hash(this_ptr: &mut ReplySho unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.chain_hash = ::bitcoin::hash_types::BlockHash::from_slice(&val.data[..]).unwrap(); } /// Indicates if the query recipient maintains up-to-date channel -/// information for the chain_hash +/// information for the `chain_hash` #[no_mangle] pub extern "C" fn ReplyShortChannelIdsEnd_get_full_information(this_ptr: &ReplyShortChannelIdsEnd) -> bool { let mut inner_val = &mut this_ptr.get_native_mut_ref().full_information; *inner_val } /// Indicates if the query recipient maintains up-to-date channel -/// information for the chain_hash +/// information for the `chain_hash` #[no_mangle] pub extern "C" fn ReplyShortChannelIdsEnd_set_full_information(this_ptr: &mut ReplyShortChannelIdsEnd, mut val: bool) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.full_information = val; @@ -5028,9 +5266,11 @@ pub extern "C" fn ReplyShortChannelIdsEnd_eq(a: &ReplyShortChannelIdsEnd, b: &Re use lightning::ln::msgs::GossipTimestampFilter as nativeGossipTimestampFilterImport; pub(crate) type nativeGossipTimestampFilter = nativeGossipTimestampFilterImport; -/// A gossip_timestamp_filter message is used by a node to request +/// A [`gossip_timestamp_filter`] message is used by a node to request /// gossip relay for messages in the requested time range when the -/// gossip_queries feature has been negotiated. +/// `gossip_queries` feature has been negotiated. +/// +/// [`gossip_timestamp_filter`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-gossip_timestamp_filter-message #[must_use] #[repr(C)] pub struct GossipTimestampFilter { @@ -5148,7 +5388,7 @@ pub extern "C" fn GossipTimestampFilter_eq(a: &GossipTimestampFilter, b: &Gossip if a.inner.is_null() || b.inner.is_null() { return false; } if a.get_native_ref() == b.get_native_ref() { true } else { false } } -/// Used to put an error message in a LightningError +/// Used to put an error message in a [`LightningError`]. #[derive(Clone)] #[must_use] #[repr(C)] @@ -5464,7 +5704,7 @@ pub extern "C" fn LightningError_clone(orig: &LightningError) -> LightningError use lightning::ln::msgs::CommitmentUpdate as nativeCommitmentUpdateImport; pub(crate) type nativeCommitmentUpdate = nativeCommitmentUpdateImport; -/// Struct used to return values from revoke_and_ack messages, containing a bunch of commitment +/// Struct used to return values from [`RevokeAndACK`] messages, containing a bunch of commitment /// transaction updates if they were pending. #[must_use] #[repr(C)] @@ -5512,59 +5752,59 @@ impl CommitmentUpdate { ret } } -/// update_add_htlc messages which should be sent +/// `update_add_htlc` messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_get_update_add_htlcs(this_ptr: &CommitmentUpdate) -> crate::c_types::derived::CVec_UpdateAddHTLCZ { let mut inner_val = &mut this_ptr.get_native_mut_ref().update_add_htlcs; let mut local_inner_val = Vec::new(); for item in inner_val.iter() { local_inner_val.push( { crate::lightning::ln::msgs::UpdateAddHTLC { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const lightning::ln::msgs::UpdateAddHTLC<>) as *mut _) }, is_owned: false } }); }; local_inner_val.into() } -/// update_add_htlc messages which should be sent +/// `update_add_htlc` messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_set_update_add_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateAddHTLCZ) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_add_htlcs = local_val; } -/// update_fulfill_htlc messages which should be sent +/// `update_fulfill_htlc` messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_get_update_fulfill_htlcs(this_ptr: &CommitmentUpdate) -> crate::c_types::derived::CVec_UpdateFulfillHTLCZ { let mut inner_val = &mut this_ptr.get_native_mut_ref().update_fulfill_htlcs; let mut local_inner_val = Vec::new(); for item in inner_val.iter() { local_inner_val.push( { crate::lightning::ln::msgs::UpdateFulfillHTLC { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const lightning::ln::msgs::UpdateFulfillHTLC<>) as *mut _) }, is_owned: false } }); }; local_inner_val.into() } -/// update_fulfill_htlc messages which should be sent +/// `update_fulfill_htlc` messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_set_update_fulfill_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateFulfillHTLCZ) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_fulfill_htlcs = local_val; } -/// update_fail_htlc messages which should be sent +/// `update_fail_htlc` messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_get_update_fail_htlcs(this_ptr: &CommitmentUpdate) -> crate::c_types::derived::CVec_UpdateFailHTLCZ { let mut inner_val = &mut this_ptr.get_native_mut_ref().update_fail_htlcs; let mut local_inner_val = Vec::new(); for item in inner_val.iter() { local_inner_val.push( { crate::lightning::ln::msgs::UpdateFailHTLC { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const lightning::ln::msgs::UpdateFailHTLC<>) as *mut _) }, is_owned: false } }); }; local_inner_val.into() } -/// update_fail_htlc messages which should be sent +/// `update_fail_htlc` messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_set_update_fail_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateFailHTLCZ) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_fail_htlcs = local_val; } -/// update_fail_malformed_htlc messages which should be sent +/// `update_fail_malformed_htlc` messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_get_update_fail_malformed_htlcs(this_ptr: &CommitmentUpdate) -> crate::c_types::derived::CVec_UpdateFailMalformedHTLCZ { let mut inner_val = &mut this_ptr.get_native_mut_ref().update_fail_malformed_htlcs; let mut local_inner_val = Vec::new(); for item in inner_val.iter() { local_inner_val.push( { crate::lightning::ln::msgs::UpdateFailMalformedHTLC { inner: unsafe { ObjOps::nonnull_ptr_to_inner((item as *const lightning::ln::msgs::UpdateFailMalformedHTLC<>) as *mut _) }, is_owned: false } }); }; local_inner_val.into() } -/// update_fail_malformed_htlc messages which should be sent +/// `update_fail_malformed_htlc` messages which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_set_update_fail_malformed_htlcs(this_ptr: &mut CommitmentUpdate, mut val: crate::c_types::derived::CVec_UpdateFailMalformedHTLCZ) { let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_fail_malformed_htlcs = local_val; } -/// An update_fee message which should be sent +/// An `update_fee` message which should be sent /// /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[no_mangle] @@ -5573,7 +5813,7 @@ pub extern "C" fn CommitmentUpdate_get_update_fee(this_ptr: &CommitmentUpdate) - let mut local_inner_val = crate::lightning::ln::msgs::UpdateFee { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::ln::msgs::UpdateFee<>) as *mut _ }, is_owned: false }; local_inner_val } -/// An update_fee message which should be sent +/// An `update_fee` message which should be sent /// /// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None #[no_mangle] @@ -5581,13 +5821,13 @@ pub extern "C" fn CommitmentUpdate_set_update_fee(this_ptr: &mut CommitmentUpdat let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.update_fee = local_val; } -/// Finally, the commitment_signed message which should be sent +/// A `commitment_signed` message which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_get_commitment_signed(this_ptr: &CommitmentUpdate) -> crate::lightning::ln::msgs::CommitmentSigned { let mut inner_val = &mut this_ptr.get_native_mut_ref().commitment_signed; crate::lightning::ln::msgs::CommitmentSigned { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inner_val as *const lightning::ln::msgs::CommitmentSigned<>) as *mut _) }, is_owned: false } } -/// Finally, the commitment_signed message which should be sent +/// A `commitment_signed` message which should be sent #[no_mangle] pub extern "C" fn CommitmentUpdate_set_commitment_signed(this_ptr: &mut CommitmentUpdate, mut val: crate::lightning::ln::msgs::CommitmentSigned) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.commitment_signed = *unsafe { Box::from_raw(val.take_inner()) }; @@ -5640,63 +5880,57 @@ pub extern "C" fn CommitmentUpdate_eq(a: &CommitmentUpdate, b: &CommitmentUpdate } /// A trait to describe an object which can receive channel messages. /// -/// Messages MAY be called in parallel when they originate from different their_node_ids, however -/// they MUST NOT be called in parallel when the two calls have the same their_node_id. +/// Messages MAY be called in parallel when they originate from different `their_node_ids`, however +/// they MUST NOT be called in parallel when the two calls have the same `their_node_id`. #[repr(C)] pub struct ChannelMessageHandler { /// An opaque pointer which is passed to your function implementations as an argument. /// This has no meaning in the LDK, and can be NULL or any other value. pub this_arg: *mut c_void, - /// Handle an incoming open_channel message from the given peer. - pub handle_open_channel: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::OpenChannel), - /// Handle an incoming accept_channel message from the given peer. - pub handle_accept_channel: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::AcceptChannel), - /// Handle an incoming funding_created message from the given peer. + /// Handle an incoming `open_channel` message from the given peer. + pub handle_open_channel: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::OpenChannel), + /// Handle an incoming `accept_channel` message from the given peer. + pub handle_accept_channel: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AcceptChannel), + /// Handle an incoming `funding_created` message from the given peer. pub handle_funding_created: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingCreated), - /// Handle an incoming funding_signed message from the given peer. + /// Handle an incoming `funding_signed` message from the given peer. pub handle_funding_signed: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingSigned), - /// Handle an incoming channel_ready message from the given peer. + /// Handle an incoming `channel_ready` message from the given peer. pub handle_channel_ready: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReady), - /// Handle an incoming shutdown message from the given peer. - pub handle_shutdown: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, their_features: &crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::Shutdown), - /// Handle an incoming closing_signed message from the given peer. + /// Handle an incoming `shutdown` message from the given peer. + pub handle_shutdown: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Shutdown), + /// Handle an incoming `closing_signed` message from the given peer. pub handle_closing_signed: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ClosingSigned), - /// Handle an incoming update_add_htlc message from the given peer. + /// Handle an incoming `update_add_htlc` message from the given peer. pub handle_update_add_htlc: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateAddHTLC), - /// Handle an incoming update_fulfill_htlc message from the given peer. + /// Handle an incoming `update_fulfill_htlc` message from the given peer. pub handle_update_fulfill_htlc: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFulfillHTLC), - /// Handle an incoming update_fail_htlc message from the given peer. + /// Handle an incoming `update_fail_htlc` message from the given peer. pub handle_update_fail_htlc: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailHTLC), - /// Handle an incoming update_fail_malformed_htlc message from the given peer. + /// Handle an incoming `update_fail_malformed_htlc` message from the given peer. pub handle_update_fail_malformed_htlc: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFailMalformedHTLC), - /// Handle an incoming commitment_signed message from the given peer. + /// Handle an incoming `commitment_signed` message from the given peer. pub handle_commitment_signed: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::CommitmentSigned), - /// Handle an incoming revoke_and_ack message from the given peer. + /// Handle an incoming `revoke_and_ack` message from the given peer. pub handle_revoke_and_ack: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::RevokeAndACK), - /// Handle an incoming update_fee message from the given peer. + /// Handle an incoming `update_fee` message from the given peer. pub handle_update_fee: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::UpdateFee), - /// Handle an incoming announcement_signatures message from the given peer. + /// Handle an incoming `announcement_signatures` message from the given peer. pub handle_announcement_signatures: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AnnouncementSignatures), - /// Indicates a connection to the peer failed/an existing connection was lost. If no connection - /// is believed to be possible in the future (eg they're sending us messages we don't - /// understand or indicate they require unknown feature bits), no_connection_possible is set - /// and any outstanding channels should be failed. - /// - /// Note that in some rare cases this may be called without a corresponding - /// [`Self::peer_connected`]. - pub peer_disconnected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, no_connection_possible: bool), - /// Handle a peer reconnecting, possibly generating channel_reestablish message(s). + /// Indicates a connection to the peer failed/an existing connection was lost. + pub peer_disconnected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey), + /// Handle a peer reconnecting, possibly generating `channel_reestablish` message(s). /// /// May return an `Err(())` if the features the peer supports are not sufficient to communicate /// with us. Implementors should be somewhat conservative about doing so, however, as other /// message handlers may still wish to communicate with this peer. #[must_use] - pub peer_connected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Init) -> crate::c_types::derived::CResult_NoneNoneZ, - /// Handle an incoming channel_reestablish message from the given peer. + pub peer_connected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Init, inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ, + /// Handle an incoming `channel_reestablish` message from the given peer. pub handle_channel_reestablish: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReestablish), - /// Handle an incoming channel update from the given peer. + /// Handle an incoming `channel_update` message from the given peer. pub handle_channel_update: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelUpdate), - /// Handle an incoming error message from the given peer. + /// Handle an incoming `error` message from the given peer. pub handle_error: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ErrorMessage), /// Gets the node feature flags which this handler itself supports. All available handlers are /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`] @@ -5758,11 +5992,11 @@ impl lightning::util::events::MessageSendEventsProvider for ChannelMessageHandle use lightning::ln::msgs::ChannelMessageHandler as rustChannelMessageHandler; impl rustChannelMessageHandler for ChannelMessageHandler { - fn handle_open_channel(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut their_features: lightning::ln::features::InitFeatures, mut msg: &lightning::ln::msgs::OpenChannel) { - (self.handle_open_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(their_features), is_owned: true }, &crate::lightning::ln::msgs::OpenChannel { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::OpenChannel<>) as *mut _) }, is_owned: false }) + fn handle_open_channel(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::OpenChannel) { + (self.handle_open_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::OpenChannel { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::OpenChannel<>) as *mut _) }, is_owned: false }) } - fn handle_accept_channel(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut their_features: lightning::ln::features::InitFeatures, mut msg: &lightning::ln::msgs::AcceptChannel) { - (self.handle_accept_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), crate::lightning::ln::features::InitFeatures { inner: ObjOps::heap_alloc(their_features), is_owned: true }, &crate::lightning::ln::msgs::AcceptChannel { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::AcceptChannel<>) as *mut _) }, is_owned: false }) + fn handle_accept_channel(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::AcceptChannel) { + (self.handle_accept_channel)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::AcceptChannel { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::AcceptChannel<>) as *mut _) }, is_owned: false }) } fn handle_funding_created(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::FundingCreated) { (self.handle_funding_created)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::FundingCreated { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::FundingCreated<>) as *mut _) }, is_owned: false }) @@ -5773,8 +6007,8 @@ impl rustChannelMessageHandler for ChannelMessageHandler { fn handle_channel_ready(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::ChannelReady) { (self.handle_channel_ready)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ChannelReady { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::ChannelReady<>) as *mut _) }, is_owned: false }) } - fn handle_shutdown(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut their_features: &lightning::ln::features::InitFeatures, mut msg: &lightning::ln::msgs::Shutdown) { - (self.handle_shutdown)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::features::InitFeatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((their_features as *const lightning::ln::features::InitFeatures<>) as *mut _) }, is_owned: false }, &crate::lightning::ln::msgs::Shutdown { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::Shutdown<>) as *mut _) }, is_owned: false }) + fn handle_shutdown(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::Shutdown) { + (self.handle_shutdown)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Shutdown { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::Shutdown<>) as *mut _) }, is_owned: false }) } fn handle_closing_signed(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::ClosingSigned) { (self.handle_closing_signed)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::ClosingSigned { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::ClosingSigned<>) as *mut _) }, is_owned: false }) @@ -5803,11 +6037,11 @@ impl rustChannelMessageHandler for ChannelMessageHandler { fn handle_announcement_signatures(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::AnnouncementSignatures) { (self.handle_announcement_signatures)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::AnnouncementSignatures { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::AnnouncementSignatures<>) as *mut _) }, is_owned: false }) } - fn peer_disconnected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut no_connection_possible: bool) { - (self.peer_disconnected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), no_connection_possible) + fn peer_disconnected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey) { + (self.peer_disconnected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id)) } - fn peer_connected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::Init) -> Result<(), ()> { - let mut ret = (self.peer_connected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::Init<>) as *mut _) }, is_owned: false }); + fn peer_connected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::Init, mut inbound: bool) -> Result<(), ()> { + let mut ret = (self.peer_connected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::Init<>) as *mut _) }, is_owned: false }, inbound); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } @@ -5852,40 +6086,40 @@ impl Drop for ChannelMessageHandler { /// /// # Implementor DoS Warnings /// -/// For `gossip_queries` messages there are potential DoS vectors when handling -/// inbound queries. Implementors using an on-disk network graph should be aware of +/// For messages enabled with the `gossip_queries` feature there are potential DoS vectors when +/// handling inbound queries. Implementors using an on-disk network graph should be aware of /// repeated disk I/O for queries accessing different parts of the network graph. #[repr(C)] pub struct RoutingMessageHandler { /// An opaque pointer which is passed to your function implementations as an argument. /// This has no meaning in the LDK, and can be NULL or any other value. pub this_arg: *mut c_void, - /// Handle an incoming node_announcement message, returning true if it should be forwarded on, - /// false or returning an Err otherwise. + /// Handle an incoming `node_announcement` message, returning `true` if it should be forwarded on, + /// `false` or returning an `Err` otherwise. #[must_use] pub handle_node_announcement: extern "C" fn (this_arg: *const c_void, msg: &crate::lightning::ln::msgs::NodeAnnouncement) -> crate::c_types::derived::CResult_boolLightningErrorZ, - /// Handle a channel_announcement message, returning true if it should be forwarded on, false - /// or returning an Err otherwise. + /// Handle a `channel_announcement` message, returning `true` if it should be forwarded on, `false` + /// or returning an `Err` otherwise. #[must_use] pub handle_channel_announcement: extern "C" fn (this_arg: *const c_void, msg: &crate::lightning::ln::msgs::ChannelAnnouncement) -> crate::c_types::derived::CResult_boolLightningErrorZ, - /// Handle an incoming channel_update message, returning true if it should be forwarded on, - /// false or returning an Err otherwise. + /// Handle an incoming `channel_update` message, returning true if it should be forwarded on, + /// `false` or returning an `Err` otherwise. #[must_use] pub handle_channel_update: extern "C" fn (this_arg: *const c_void, msg: &crate::lightning::ln::msgs::ChannelUpdate) -> crate::c_types::derived::CResult_boolLightningErrorZ, /// Gets channel announcements and updates required to dump our routing table to a remote node, - /// starting at the short_channel_id indicated by starting_point and including announcements + /// starting at the `short_channel_id` indicated by `starting_point` and including announcements /// for a single channel. #[must_use] pub get_next_channel_announcement: extern "C" fn (this_arg: *const c_void, starting_point: u64) -> crate::c_types::derived::COption_C3Tuple_ChannelAnnouncementChannelUpdateChannelUpdateZZ, /// Gets a node announcement required to dump our routing table to a remote node, starting at /// the node *after* the provided pubkey and including up to one announcement immediately - /// higher (as defined by ::cmp) than starting_point. - /// If None is provided for starting_point, we start at the first node. + /// higher (as defined by `::cmp`) than `starting_point`. + /// If `None` is provided for `starting_point`, we start at the first node. /// /// Note that starting_point (or a relevant inner pointer) may be NULL or all-0s to represent None /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] - pub get_next_node_announcement: extern "C" fn (this_arg: *const c_void, starting_point: crate::c_types::PublicKey) -> crate::lightning::ln::msgs::NodeAnnouncement, + pub get_next_node_announcement: extern "C" fn (this_arg: *const c_void, starting_point: crate::lightning::routing::gossip::NodeId) -> crate::lightning::ln::msgs::NodeAnnouncement, /// Called when a connection is established with a peer. This can be used to /// perform routing table synchronization using a strategy defined by the /// implementor. @@ -5894,7 +6128,7 @@ pub struct RoutingMessageHandler { /// with us. Implementors should be somewhat conservative about doing so, however, as other /// message handlers may still wish to communicate with this peer. #[must_use] - pub peer_connected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init) -> crate::c_types::derived::CResult_NoneNoneZ, + pub peer_connected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init, inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ, /// Handles the reply of a query we initiated to learn about channels /// for a given range of blocks. We can expect to receive one or more /// replies to a single query. @@ -5906,14 +6140,20 @@ pub struct RoutingMessageHandler { /// gossip messages. #[must_use] pub handle_reply_short_channel_ids_end: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::ReplyShortChannelIdsEnd) -> crate::c_types::derived::CResult_NoneLightningErrorZ, - /// Handles when a peer asks us to send a list of short_channel_ids + /// Handles when a peer asks us to send a list of `short_channel_id`s /// for the requested range of blocks. #[must_use] pub handle_query_channel_range: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::QueryChannelRange) -> crate::c_types::derived::CResult_NoneLightningErrorZ, /// Handles when a peer asks us to send routing gossip messages for a - /// list of short_channel_ids. + /// list of `short_channel_id`s. #[must_use] pub handle_query_short_channel_ids: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::QueryShortChannelIds) -> crate::c_types::derived::CResult_NoneLightningErrorZ, + /// Indicates that there are a large number of [`ChannelAnnouncement`] (or other) messages + /// pending some async action. While there is no guarantee of the rate of future messages, the + /// caller should seek to reduce the rate of new gossip messages handled, especially + /// [`ChannelAnnouncement`]s. + #[must_use] + pub processing_queue_high: extern "C" fn (this_arg: *const c_void) -> bool, /// Gets the node feature flags which this handler itself supports. All available handlers are /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`] /// which are broadcasted in our [`NodeAnnouncement`] message. @@ -5948,6 +6188,7 @@ pub(crate) extern "C" fn RoutingMessageHandler_clone_fields(orig: &RoutingMessag handle_reply_short_channel_ids_end: Clone::clone(&orig.handle_reply_short_channel_ids_end), handle_query_channel_range: Clone::clone(&orig.handle_query_channel_range), handle_query_short_channel_ids: Clone::clone(&orig.handle_query_short_channel_ids), + processing_queue_high: Clone::clone(&orig.processing_queue_high), provided_node_features: Clone::clone(&orig.provided_node_features), provided_init_features: Clone::clone(&orig.provided_init_features), MessageSendEventsProvider: crate::lightning::util::events::MessageSendEventsProvider_clone_fields(&orig.MessageSendEventsProvider), @@ -5984,14 +6225,14 @@ impl rustRoutingMessageHandler for RoutingMessageHandler { let mut local_ret = if ret.is_some() { Some( { let (mut orig_ret_0_0, mut orig_ret_0_1, mut orig_ret_0_2) = ret.take().to_rust(); let mut local_orig_ret_0_1 = if orig_ret_0_1.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(orig_ret_0_1.take_inner()) } }) }; let mut local_orig_ret_0_2 = if orig_ret_0_2.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(orig_ret_0_2.take_inner()) } }) }; let mut local_ret_0 = (*unsafe { Box::from_raw(orig_ret_0_0.take_inner()) }, local_orig_ret_0_1, local_orig_ret_0_2); local_ret_0 }) } else { None }; local_ret } - fn get_next_node_announcement(&self, mut starting_point: Option<&bitcoin::secp256k1::PublicKey>) -> Option { - let mut local_starting_point = if starting_point.is_none() { crate::c_types::PublicKey::null() } else { { crate::c_types::PublicKey::from_rust(&(starting_point.unwrap())) } }; + fn get_next_node_announcement(&self, mut starting_point: Option<&lightning::routing::gossip::NodeId>) -> Option { + let mut local_starting_point = crate::lightning::routing::gossip::NodeId { inner: unsafe { (if starting_point.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (starting_point.unwrap()) }) } as *const lightning::routing::gossip::NodeId<>) as *mut _ }, is_owned: false }; let mut ret = (self.get_next_node_announcement)(self.this_arg, local_starting_point); let mut local_ret = if ret.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(ret.take_inner()) } }) }; local_ret } - fn peer_connected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut init: &lightning::ln::msgs::Init) -> Result<(), ()> { - let mut ret = (self.peer_connected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { ObjOps::nonnull_ptr_to_inner((init as *const lightning::ln::msgs::Init<>) as *mut _) }, is_owned: false }); + fn peer_connected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut init: &lightning::ln::msgs::Init, mut inbound: bool) -> Result<(), ()> { + let mut ret = (self.peer_connected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { ObjOps::nonnull_ptr_to_inner((init as *const lightning::ln::msgs::Init<>) as *mut _) }, is_owned: false }, inbound); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } @@ -6015,6 +6256,10 @@ impl rustRoutingMessageHandler for RoutingMessageHandler { let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } + fn processing_queue_high(&self) -> bool { + let mut ret = (self.processing_queue_high)(self.this_arg); + ret + } fn provided_node_features(&self) -> lightning::ln::features::NodeFeatures { let mut ret = (self.provided_node_features)(self.this_arg); *unsafe { Box::from_raw(ret.take_inner()) } @@ -6049,7 +6294,7 @@ pub struct OnionMessageHandler { /// An opaque pointer which is passed to your function implementations as an argument. /// This has no meaning in the LDK, and can be NULL or any other value. pub this_arg: *mut c_void, - /// Handle an incoming onion_message message from the given peer. + /// Handle an incoming `onion_message` message from the given peer. pub handle_onion_message: extern "C" fn (this_arg: *const c_void, peer_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::OnionMessage), /// Called when a connection is established with a peer. Can be used to track which peers /// advertise onion message support and are online. @@ -6058,13 +6303,10 @@ pub struct OnionMessageHandler { /// with us. Implementors should be somewhat conservative about doing so, however, as other /// message handlers may still wish to communicate with this peer. #[must_use] - pub peer_connected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init) -> crate::c_types::derived::CResult_NoneNoneZ, + pub peer_connected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init, inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ, /// Indicates a connection to the peer failed/an existing connection was lost. Allows handlers to /// drop and refuse to forward onion messages to this peer. - /// - /// Note that in some rare cases this may be called without a corresponding - /// [`Self::peer_connected`]. - pub peer_disconnected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey, no_connection_possible: bool), + pub peer_disconnected: extern "C" fn (this_arg: *const c_void, their_node_id: crate::c_types::PublicKey), /// Gets the node feature flags which this handler itself supports. All available handlers are /// queried similarly and their feature flags are OR'd together to form the [`NodeFeatures`] /// which are broadcasted in our [`NodeAnnouncement`] message. @@ -6111,13 +6353,13 @@ impl rustOnionMessageHandler for OnionMessageHandler { fn handle_onion_message(&self, mut peer_node_id: &bitcoin::secp256k1::PublicKey, mut msg: &lightning::ln::msgs::OnionMessage) { (self.handle_onion_message)(self.this_arg, crate::c_types::PublicKey::from_rust(&peer_node_id), &crate::lightning::ln::msgs::OnionMessage { inner: unsafe { ObjOps::nonnull_ptr_to_inner((msg as *const lightning::ln::msgs::OnionMessage<>) as *mut _) }, is_owned: false }) } - fn peer_connected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut init: &lightning::ln::msgs::Init) -> Result<(), ()> { - let mut ret = (self.peer_connected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { ObjOps::nonnull_ptr_to_inner((init as *const lightning::ln::msgs::Init<>) as *mut _) }, is_owned: false }); + fn peer_connected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut init: &lightning::ln::msgs::Init, mut inbound: bool) -> Result<(), ()> { + let mut ret = (self.peer_connected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), &crate::lightning::ln::msgs::Init { inner: unsafe { ObjOps::nonnull_ptr_to_inner((init as *const lightning::ln::msgs::Init<>) as *mut _) }, is_owned: false }, inbound); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) })*/ })}; local_ret } - fn peer_disconnected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey, mut no_connection_possible: bool) { - (self.peer_disconnected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id), no_connection_possible) + fn peer_disconnected(&self, mut their_node_id: &bitcoin::secp256k1::PublicKey) { + (self.peer_disconnected)(self.this_arg, crate::c_types::PublicKey::from_rust(&their_node_id)) } fn provided_node_features(&self) -> lightning::ln::features::NodeFeatures { let mut ret = (self.provided_node_features)(self.this_arg); @@ -6654,7 +6896,9 @@ pub extern "C" fn ReplyShortChannelIdsEnd_read(ser: crate::c_types::u8slice) -> let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::msgs::ReplyShortChannelIdsEnd { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } -///\n\t * Calculates the overflow safe ending block height for the query.\n\t * Overflow returns `0xffffffff`, otherwise returns `first_blocknum + number_of_blocks`\n\t +/// Calculates the overflow safe ending block height for the query. +/// +/// Overflow returns `0xffffffff`, otherwise returns `first_blocknum + number_of_blocks`. #[must_use] #[no_mangle] pub extern "C" fn QueryChannelRange_end_blocknum(this_arg: &crate::lightning::ln::msgs::QueryChannelRange) -> u32 { diff --git a/lightning-c-bindings/src/lightning/ln/outbound_payment.rs b/lightning-c-bindings/src/lightning/ln/outbound_payment.rs new file mode 100644 index 0000000..e7f0ff2 --- /dev/null +++ b/lightning-c-bindings/src/lightning/ln/outbound_payment.rs @@ -0,0 +1,475 @@ +// This file is Copyright its original authors, visible in version control +// history and in the source files from which this was generated. +// +// This file is licensed under the license available in the LICENSE or LICENSE.md +// file in the root of this repository or, if no such file exists, the same +// license as that which applies to the original source files from which this +// source was automatically generated. + +//! Utilities to send payments and manage outbound payment information. + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + +/// Strategies available to retry payment path failures. +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum Retry { + /// Max number of attempts to retry payment. + /// + /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a + /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and + /// were retried along a route from a single call to [`Router::find_route`]. + Attempts( + usize), + /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made; + /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time. + /// + /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time + Timeout( + u64), +} +use lightning::ln::outbound_payment::Retry as RetryImport; +pub(crate) type nativeRetry = RetryImport; + +impl Retry { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeRetry { + match self { + Retry::Attempts (ref a, ) => { + let mut a_nonref = Clone::clone(a); + nativeRetry::Attempts ( + a_nonref, + ) + }, + Retry::Timeout (ref a, ) => { + let mut a_nonref = Clone::clone(a); + nativeRetry::Timeout ( + core::time::Duration::from_secs(a_nonref), + ) + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeRetry { + match self { + Retry::Attempts (mut a, ) => { + nativeRetry::Attempts ( + a, + ) + }, + Retry::Timeout (mut a, ) => { + nativeRetry::Timeout ( + core::time::Duration::from_secs(a), + ) + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeRetry) -> Self { + match native { + nativeRetry::Attempts (ref a, ) => { + let mut a_nonref = Clone::clone(a); + Retry::Attempts ( + a_nonref, + ) + }, + nativeRetry::Timeout (ref a, ) => { + let mut a_nonref = Clone::clone(a); + Retry::Timeout ( + a_nonref.as_secs(), + ) + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeRetry) -> Self { + match native { + nativeRetry::Attempts (mut a, ) => { + Retry::Attempts ( + a, + ) + }, + nativeRetry::Timeout (mut a, ) => { + Retry::Timeout ( + a.as_secs(), + ) + }, + } + } +} +/// Frees any resources used by the Retry +#[no_mangle] +pub extern "C" fn Retry_free(this_ptr: Retry) { } +/// Creates a copy of the Retry +#[no_mangle] +pub extern "C" fn Retry_clone(orig: &Retry) -> Retry { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new Attempts-variant Retry +pub extern "C" fn Retry_attempts(a: usize) -> Retry { + Retry::Attempts(a, ) +} +#[no_mangle] +/// Utility method to constructs a new Timeout-variant Retry +pub extern "C" fn Retry_timeout(a: u64) -> Retry { + Retry::Timeout(a, ) +} +/// Checks if two Retrys contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +#[no_mangle] +pub extern "C" fn Retry_eq(a: &Retry, b: &Retry) -> bool { + if &a.to_native() == &b.to_native() { true } else { false } +} +/// Checks if two Retrys contain equal inner contents. +#[no_mangle] +pub extern "C" fn Retry_hash(o: &Retry) -> u64 { + // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core + #[allow(deprecated)] + let mut hasher = core::hash::SipHasher::new(); + core::hash::Hash::hash(&o.to_native(), &mut hasher); + core::hash::Hasher::finish(&hasher) +} +/// Indicates an immediate error on [`ChannelManager::send_payment_with_retry`]. Further errors +/// may be surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`]. +/// +/// [`ChannelManager::send_payment_with_retry`]: crate::ln::channelmanager::ChannelManager::send_payment_with_retry +/// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed +/// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum RetryableSendFailure { + /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note + /// that this error is *not* caused by [`Retry::Timeout`]. + /// + /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time + PaymentExpired, + /// We were unable to find a route to the destination. + RouteNotFound, + /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not + /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]). + /// + /// [`PaymentId`]: crate::ln::channelmanager::PaymentId + /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent + /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed + DuplicatePayment, +} +use lightning::ln::outbound_payment::RetryableSendFailure as RetryableSendFailureImport; +pub(crate) type nativeRetryableSendFailure = RetryableSendFailureImport; + +impl RetryableSendFailure { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeRetryableSendFailure { + match self { + RetryableSendFailure::PaymentExpired => nativeRetryableSendFailure::PaymentExpired, + RetryableSendFailure::RouteNotFound => nativeRetryableSendFailure::RouteNotFound, + RetryableSendFailure::DuplicatePayment => nativeRetryableSendFailure::DuplicatePayment, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeRetryableSendFailure { + match self { + RetryableSendFailure::PaymentExpired => nativeRetryableSendFailure::PaymentExpired, + RetryableSendFailure::RouteNotFound => nativeRetryableSendFailure::RouteNotFound, + RetryableSendFailure::DuplicatePayment => nativeRetryableSendFailure::DuplicatePayment, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeRetryableSendFailure) -> Self { + match native { + nativeRetryableSendFailure::PaymentExpired => RetryableSendFailure::PaymentExpired, + nativeRetryableSendFailure::RouteNotFound => RetryableSendFailure::RouteNotFound, + nativeRetryableSendFailure::DuplicatePayment => RetryableSendFailure::DuplicatePayment, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeRetryableSendFailure) -> Self { + match native { + nativeRetryableSendFailure::PaymentExpired => RetryableSendFailure::PaymentExpired, + nativeRetryableSendFailure::RouteNotFound => RetryableSendFailure::RouteNotFound, + nativeRetryableSendFailure::DuplicatePayment => RetryableSendFailure::DuplicatePayment, + } + } +} +/// Creates a copy of the RetryableSendFailure +#[no_mangle] +pub extern "C" fn RetryableSendFailure_clone(orig: &RetryableSendFailure) -> RetryableSendFailure { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new PaymentExpired-variant RetryableSendFailure +pub extern "C" fn RetryableSendFailure_payment_expired() -> RetryableSendFailure { + RetryableSendFailure::PaymentExpired} +#[no_mangle] +/// Utility method to constructs a new RouteNotFound-variant RetryableSendFailure +pub extern "C" fn RetryableSendFailure_route_not_found() -> RetryableSendFailure { + RetryableSendFailure::RouteNotFound} +#[no_mangle] +/// Utility method to constructs a new DuplicatePayment-variant RetryableSendFailure +pub extern "C" fn RetryableSendFailure_duplicate_payment() -> RetryableSendFailure { + RetryableSendFailure::DuplicatePayment} +/// If a payment fails to send with [`ChannelManager::send_payment`], it can be in one of several +/// states. This enum is returned as the Err() type describing which state the payment is in, see +/// the description of individual enum states for more. +/// +/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum PaymentSendFailure { + /// A parameter which was passed to send_payment was invalid, preventing us from attempting to + /// send the payment at all. + /// + /// You can freely resend the payment in full (with the parameter error fixed). + /// + /// Because the payment failed outright, no payment tracking is done and no + /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated. + /// + /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed + /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed + ParameterError( + crate::lightning::util::errors::APIError), + /// A parameter in a single path which was passed to send_payment was invalid, preventing us + /// from attempting to send the payment at all. + /// + /// You can freely resend the payment in full (with the parameter error fixed). + /// + /// Because the payment failed outright, no payment tracking is done and no + /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated. + /// + /// The results here are ordered the same as the paths in the route object which was passed to + /// send_payment. + /// + /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed + /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed + PathParameterError( + crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ), + /// All paths which were attempted failed to send, with no channel state change taking place. + /// You can freely resend the payment in full (though you probably want to do so over different + /// paths than the ones selected). + /// + /// Because the payment failed outright, no payment tracking is done and no + /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated. + /// + /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed + /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed + AllFailedResendSafe( + crate::c_types::derived::CVec_APIErrorZ), + /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not + /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]). + /// + /// [`PaymentId`]: crate::ln::channelmanager::PaymentId + /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent + /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed + DuplicatePayment, + /// Some paths that were attempted failed to send, though some paths may have succeeded. At least + /// some paths have irrevocably committed to the HTLC. + /// + /// The results here are ordered the same as the paths in the route object that was passed to + /// send_payment. + /// + /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a + /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id. + /// + /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed + PartialFailure { + /// The errors themselves, in the same order as the paths from the route. + results: crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ, + /// If some paths failed without irrevocably committing to the new HTLC(s), this will + /// contain a [`RouteParameters`] object for the failing paths. + /// + /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None + failed_paths_retry: crate::lightning::routing::router::RouteParameters, + /// The payment id for the payment, which is now at least partially pending. + payment_id: crate::c_types::ThirtyTwoBytes, + }, +} +use lightning::ln::outbound_payment::PaymentSendFailure as PaymentSendFailureImport; +pub(crate) type nativePaymentSendFailure = PaymentSendFailureImport; + +impl PaymentSendFailure { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativePaymentSendFailure { + match self { + PaymentSendFailure::ParameterError (ref a, ) => { + let mut a_nonref = Clone::clone(a); + nativePaymentSendFailure::ParameterError ( + a_nonref.into_native(), + ) + }, + PaymentSendFailure::PathParameterError (ref a, ) => { + let mut a_nonref = Clone::clone(a); + 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 }); }; + nativePaymentSendFailure::PathParameterError ( + local_a_nonref, + ) + }, + PaymentSendFailure::AllFailedResendSafe (ref a, ) => { + let mut a_nonref = Clone::clone(a); + let mut local_a_nonref = Vec::new(); for mut item in a_nonref.into_rust().drain(..) { local_a_nonref.push( { item.into_native() }); }; + nativePaymentSendFailure::AllFailedResendSafe ( + local_a_nonref, + ) + }, + PaymentSendFailure::DuplicatePayment => nativePaymentSendFailure::DuplicatePayment, + PaymentSendFailure::PartialFailure {ref results, ref failed_paths_retry, ref payment_id, } => { + let mut results_nonref = Clone::clone(results); + let mut local_results_nonref = Vec::new(); for mut item in results_nonref.into_rust().drain(..) { local_results_nonref.push( { let mut local_results_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_results_nonref_0 }); }; + let mut failed_paths_retry_nonref = Clone::clone(failed_paths_retry); + let mut local_failed_paths_retry_nonref = if failed_paths_retry_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(failed_paths_retry_nonref.take_inner()) } }) }; + let mut payment_id_nonref = Clone::clone(payment_id); + nativePaymentSendFailure::PartialFailure { + results: local_results_nonref, + failed_paths_retry: local_failed_paths_retry_nonref, + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data), + } + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativePaymentSendFailure { + match self { + PaymentSendFailure::ParameterError (mut a, ) => { + nativePaymentSendFailure::ParameterError ( + a.into_native(), + ) + }, + PaymentSendFailure::PathParameterError (mut a, ) => { + 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 }); }; + nativePaymentSendFailure::PathParameterError ( + local_a, + ) + }, + PaymentSendFailure::AllFailedResendSafe (mut a, ) => { + let mut local_a = Vec::new(); for mut item in a.into_rust().drain(..) { local_a.push( { item.into_native() }); }; + nativePaymentSendFailure::AllFailedResendSafe ( + local_a, + ) + }, + PaymentSendFailure::DuplicatePayment => nativePaymentSendFailure::DuplicatePayment, + PaymentSendFailure::PartialFailure {mut results, mut failed_paths_retry, mut payment_id, } => { + let mut local_results = Vec::new(); for mut item in results.into_rust().drain(..) { local_results.push( { let mut local_results_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_results_0 }); }; + let mut local_failed_paths_retry = if failed_paths_retry.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(failed_paths_retry.take_inner()) } }) }; + nativePaymentSendFailure::PartialFailure { + results: local_results, + failed_paths_retry: local_failed_paths_retry, + payment_id: ::lightning::ln::channelmanager::PaymentId(payment_id.data), + } + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativePaymentSendFailure) -> Self { + match native { + nativePaymentSendFailure::ParameterError (ref a, ) => { + let mut a_nonref = Clone::clone(a); + PaymentSendFailure::ParameterError ( + crate::lightning::util::errors::APIError::native_into(a_nonref), + ) + }, + nativePaymentSendFailure::PathParameterError (ref a, ) => { + let mut a_nonref = Clone::clone(a); + 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( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_nonref_0 }); }; + PaymentSendFailure::PathParameterError ( + local_a_nonref.into(), + ) + }, + nativePaymentSendFailure::AllFailedResendSafe (ref a, ) => { + let mut a_nonref = Clone::clone(a); + let mut local_a_nonref = Vec::new(); for mut item in a_nonref.drain(..) { local_a_nonref.push( { crate::lightning::util::errors::APIError::native_into(item) }); }; + PaymentSendFailure::AllFailedResendSafe ( + local_a_nonref.into(), + ) + }, + nativePaymentSendFailure::DuplicatePayment => PaymentSendFailure::DuplicatePayment, + nativePaymentSendFailure::PartialFailure {ref results, ref failed_paths_retry, ref payment_id, } => { + let mut results_nonref = Clone::clone(results); + let mut local_results_nonref = Vec::new(); for mut item in results_nonref.drain(..) { local_results_nonref.push( { let mut local_results_nonref_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_results_nonref_0 }); }; + let mut failed_paths_retry_nonref = Clone::clone(failed_paths_retry); + let mut local_failed_paths_retry_nonref = crate::lightning::routing::router::RouteParameters { inner: if failed_paths_retry_nonref.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((failed_paths_retry_nonref.unwrap())) } }, is_owned: true }; + let mut payment_id_nonref = Clone::clone(payment_id); + PaymentSendFailure::PartialFailure { + results: local_results_nonref.into(), + failed_paths_retry: local_failed_paths_retry_nonref, + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id_nonref.0 }, + } + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativePaymentSendFailure) -> Self { + match native { + nativePaymentSendFailure::ParameterError (mut a, ) => { + PaymentSendFailure::ParameterError ( + crate::lightning::util::errors::APIError::native_into(a), + ) + }, + nativePaymentSendFailure::PathParameterError (mut a, ) => { + 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( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_a_0 }); }; + PaymentSendFailure::PathParameterError ( + local_a.into(), + ) + }, + nativePaymentSendFailure::AllFailedResendSafe (mut a, ) => { + let mut local_a = Vec::new(); for mut item in a.drain(..) { local_a.push( { crate::lightning::util::errors::APIError::native_into(item) }); }; + PaymentSendFailure::AllFailedResendSafe ( + local_a.into(), + ) + }, + nativePaymentSendFailure::DuplicatePayment => PaymentSendFailure::DuplicatePayment, + nativePaymentSendFailure::PartialFailure {mut results, mut failed_paths_retry, mut payment_id, } => { + let mut local_results = Vec::new(); for mut item in results.drain(..) { local_results.push( { let mut local_results_0 = match item { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::util::errors::APIError::native_into(e) }).into() }; local_results_0 }); }; + let mut local_failed_paths_retry = crate::lightning::routing::router::RouteParameters { inner: if failed_paths_retry.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((failed_paths_retry.unwrap())) } }, is_owned: true }; + PaymentSendFailure::PartialFailure { + results: local_results.into(), + failed_paths_retry: local_failed_paths_retry, + payment_id: crate::c_types::ThirtyTwoBytes { data: payment_id.0 }, + } + }, + } + } +} +/// Frees any resources used by the PaymentSendFailure +#[no_mangle] +pub extern "C" fn PaymentSendFailure_free(this_ptr: PaymentSendFailure) { } +/// Creates a copy of the PaymentSendFailure +#[no_mangle] +pub extern "C" fn PaymentSendFailure_clone(orig: &PaymentSendFailure) -> PaymentSendFailure { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new ParameterError-variant PaymentSendFailure +pub extern "C" fn PaymentSendFailure_parameter_error(a: crate::lightning::util::errors::APIError) -> PaymentSendFailure { + PaymentSendFailure::ParameterError(a, ) +} +#[no_mangle] +/// Utility method to constructs a new PathParameterError-variant PaymentSendFailure +pub extern "C" fn PaymentSendFailure_path_parameter_error(a: crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ) -> PaymentSendFailure { + PaymentSendFailure::PathParameterError(a, ) +} +#[no_mangle] +/// Utility method to constructs a new AllFailedResendSafe-variant PaymentSendFailure +pub extern "C" fn PaymentSendFailure_all_failed_resend_safe(a: crate::c_types::derived::CVec_APIErrorZ) -> PaymentSendFailure { + PaymentSendFailure::AllFailedResendSafe(a, ) +} +#[no_mangle] +/// Utility method to constructs a new DuplicatePayment-variant PaymentSendFailure +pub extern "C" fn PaymentSendFailure_duplicate_payment() -> PaymentSendFailure { + PaymentSendFailure::DuplicatePayment} +#[no_mangle] +/// Utility method to constructs a new PartialFailure-variant PaymentSendFailure +pub extern "C" fn PaymentSendFailure_partial_failure(results: crate::c_types::derived::CVec_CResult_NoneAPIErrorZZ, failed_paths_retry: crate::lightning::routing::router::RouteParameters, payment_id: crate::c_types::ThirtyTwoBytes) -> PaymentSendFailure { + PaymentSendFailure::PartialFailure { + results, + failed_paths_retry, + payment_id, + } +} diff --git a/lightning-c-bindings/src/lightning/ln/peer_handler.rs b/lightning-c-bindings/src/lightning/ln/peer_handler.rs index 5417667..74fa42f 100644 --- a/lightning-c-bindings/src/lightning/ln/peer_handler.rs +++ b/lightning-c-bindings/src/lightning/ln/peer_handler.rs @@ -22,20 +22,27 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; -/// Handler for BOLT1-compliant messages. +/// A handler provided to [`PeerManager`] for reading and handling custom messages. +/// +/// [BOLT 1] specifies a custom message type range for use with experimental or application-specific +/// messages. `CustomMessageHandler` allows for user-defined handling of such types. See the +/// [`lightning_custom_message`] crate for tools useful in composing more than one custom handler. +/// +/// [BOLT 1]: https://github.com/lightning/bolts/blob/master/01-messaging.md +/// [`lightning_custom_message`]: https://docs.rs/lightning_custom_message/latest/lightning_custom_message #[repr(C)] pub struct CustomMessageHandler { /// An opaque pointer which is passed to your function implementations as an argument. /// This has no meaning in the LDK, and can be NULL or any other value. pub this_arg: *mut c_void, - /// Called with the message type that was received and the buffer to be read. - /// Can return a `MessageHandlingError` if the message could not be handled. + /// Handles the given message sent from `sender_node_id`, possibly producing messages for + /// [`CustomMessageHandler::get_and_clear_pending_msg`] to return and thus for [`PeerManager`] + /// to send. #[must_use] pub handle_custom_message: extern "C" fn (this_arg: *const c_void, msg: crate::lightning::ln::wire::Type, sender_node_id: crate::c_types::PublicKey) -> crate::c_types::derived::CResult_NoneLightningErrorZ, - /// Gets the list of pending messages which were generated by the custom message - /// handler, clearing the list in the process. The first tuple element must - /// correspond to the intended recipients node ids. If no connection to one of the - /// specified node does not exist, the message is simply not sent to it. + /// Returns the list of pending messages that were generated by the handler, clearing the list + /// in the process. Each message is paired with the node id of the intended recipient. If no + /// connection to the node exists, then the message is simply not sent. #[must_use] pub get_and_clear_pending_msg: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_C2Tuple_PublicKeyTypeZZ, /// Implementation of CustomMessageReader for this object. @@ -211,6 +218,7 @@ pub extern "C" fn IgnoringMessageHandler_as_RoutingMessageHandler(this_arg: &Ign handle_reply_short_channel_ids_end: IgnoringMessageHandler_RoutingMessageHandler_handle_reply_short_channel_ids_end, handle_query_channel_range: IgnoringMessageHandler_RoutingMessageHandler_handle_query_channel_range, handle_query_short_channel_ids: IgnoringMessageHandler_RoutingMessageHandler_handle_query_short_channel_ids, + processing_queue_high: IgnoringMessageHandler_RoutingMessageHandler_processing_queue_high, provided_node_features: IgnoringMessageHandler_RoutingMessageHandler_provided_node_features, provided_init_features: IgnoringMessageHandler_RoutingMessageHandler_provided_init_features, MessageSendEventsProvider: crate::lightning::util::events::MessageSendEventsProvider { @@ -246,15 +254,15 @@ extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_get_next_channel_anno local_ret } #[must_use] -extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_get_next_node_announcement(this_arg: *const c_void, mut starting_point: crate::c_types::PublicKey) -> crate::lightning::ln::msgs::NodeAnnouncement { - let mut local_starting_point_base = if starting_point.is_null() { None } else { Some( { starting_point.into_rust() }) }; let mut local_starting_point = local_starting_point_base.as_ref(); +extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_get_next_node_announcement(this_arg: *const c_void, mut starting_point: crate::lightning::routing::gossip::NodeId) -> crate::lightning::ln::msgs::NodeAnnouncement { + let mut local_starting_point = if starting_point.inner.is_null() { None } else { Some( { starting_point.get_native_ref() }) }; let mut ret = >::get_next_node_announcement(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, local_starting_point); let mut local_ret = crate::lightning::ln::msgs::NodeAnnouncement { inner: if ret.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((ret.unwrap())) } }, is_owned: true }; local_ret } #[must_use] -extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init) -> crate::c_types::derived::CResult_NoneNoneZ { - let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &their_node_id.into_rust(), init.get_native_ref()); +extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init, mut inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ { + let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &their_node_id.into_rust(), init.get_native_ref(), inbound); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -283,6 +291,11 @@ extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_handle_query_short_ch local_ret } #[must_use] +extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_processing_queue_high(this_arg: *const c_void) -> bool { + let mut ret = >::processing_queue_high(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, ); + ret +} +#[must_use] extern "C" fn IgnoringMessageHandler_RoutingMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures { let mut ret = >::provided_node_features(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, ); crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } @@ -355,13 +368,13 @@ extern "C" fn IgnoringMessageHandler_OnionMessageHandler_handle_onion_message(th >::handle_onion_message(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &peer_node_id.into_rust(), msg.get_native_ref()) } #[must_use] -extern "C" fn IgnoringMessageHandler_OnionMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init) -> crate::c_types::derived::CResult_NoneNoneZ { - let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &their_node_id.into_rust(), init.get_native_ref()); +extern "C" fn IgnoringMessageHandler_OnionMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init, mut inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ { + let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &their_node_id.into_rust(), init.get_native_ref(), inbound); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } -extern "C" fn IgnoringMessageHandler_OnionMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) { - >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &their_node_id.into_rust(), no_connection_possible) +extern "C" fn IgnoringMessageHandler_OnionMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) { + >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeIgnoringMessageHandler) }, &their_node_id.into_rust()) } #[must_use] extern "C" fn IgnoringMessageHandler_OnionMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures { @@ -617,11 +630,11 @@ pub extern "C" fn ErroringMessageHandler_as_ChannelMessageHandler(this_arg: &Err } } -extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::OpenChannel) { - >::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, msg.get_native_ref()) +extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_open_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::OpenChannel) { + >::handle_open_channel(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut their_features: crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::AcceptChannel) { - >::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), *unsafe { Box::from_raw(their_features.take_inner()) }, msg.get_native_ref()) +extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_accept_channel(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AcceptChannel) { + >::handle_accept_channel(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_funding_created(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::FundingCreated) { >::handle_funding_created(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) @@ -632,8 +645,8 @@ extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_funding_signed extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_channel_ready(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ChannelReady) { >::handle_channel_ready(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, their_features: &crate::lightning::ln::features::InitFeatures, msg: &crate::lightning::ln::msgs::Shutdown) { - >::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), their_features.get_native_ref(), msg.get_native_ref()) +extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_shutdown(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Shutdown) { + >::handle_shutdown(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_closing_signed(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::ClosingSigned) { >::handle_closing_signed(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) @@ -662,12 +675,12 @@ extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_update_fee(thi extern "C" fn ErroringMessageHandler_ChannelMessageHandler_handle_announcement_signatures(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::AnnouncementSignatures) { >::handle_announcement_signatures(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()) } -extern "C" fn ErroringMessageHandler_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) { - >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), no_connection_possible) +extern "C" fn ErroringMessageHandler_ChannelMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) { + >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust()) } #[must_use] -extern "C" fn ErroringMessageHandler_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Init) -> crate::c_types::derived::CResult_NoneNoneZ { - let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref()); +extern "C" fn ErroringMessageHandler_ChannelMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, msg: &crate::lightning::ln::msgs::Init, mut inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ { + let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeErroringMessageHandler) }, &their_node_id.into_rust(), msg.get_native_ref(), inbound); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -970,35 +983,11 @@ impl PeerHandleError { ret } } -/// Used to indicate that we probably can't make any future connections to this peer (e.g. -/// because we required features that our peer was missing, or vice versa). -/// -/// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close -/// any channels with this peer or check for new versions of LDK. -/// -/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager -#[no_mangle] -pub extern "C" fn PeerHandleError_get_no_connection_possible(this_ptr: &PeerHandleError) -> bool { - let mut inner_val = &mut this_ptr.get_native_mut_ref().no_connection_possible; - *inner_val -} -/// Used to indicate that we probably can't make any future connections to this peer (e.g. -/// because we required features that our peer was missing, or vice versa). -/// -/// While LDK's [`ChannelManager`] will not do it automatically, you likely wish to force-close -/// any channels with this peer or check for new versions of LDK. -/// -/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager -#[no_mangle] -pub extern "C" fn PeerHandleError_set_no_connection_possible(this_ptr: &mut PeerHandleError, mut val: bool) { - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.no_connection_possible = val; -} /// Constructs a new PeerHandleError given each field #[must_use] #[no_mangle] -pub extern "C" fn PeerHandleError_new(mut no_connection_possible_arg: bool) -> PeerHandleError { +pub extern "C" fn PeerHandleError_new() -> PeerHandleError { PeerHandleError { inner: ObjOps::heap_alloc(nativePeerHandleError { - no_connection_possible: no_connection_possible_arg, }), is_owned: true } } impl Clone for PeerHandleError { @@ -1022,7 +1011,7 @@ pub extern "C" fn PeerHandleError_clone(orig: &PeerHandleError) -> PeerHandleErr } use lightning::ln::peer_handler::PeerManager as nativePeerManagerImport; -pub(crate) type nativePeerManager = nativePeerManagerImport; +pub(crate) type nativePeerManager = nativePeerManagerImport; /// A PeerManager manages a set of peers, described by their [`SocketDescriptor`] and marshalls /// socket events into messages which it passes on to its [`MessageHandler`]. @@ -1099,25 +1088,30 @@ impl PeerManager { /// minute should suffice. #[must_use] #[no_mangle] -pub extern "C" fn PeerManager_new(mut message_handler: crate::lightning::ln::peer_handler::MessageHandler, mut our_node_secret: crate::c_types::SecretKey, mut current_time: u32, ephemeral_random_data: *const [u8; 32], mut logger: crate::lightning::util::logger::Logger, mut custom_message_handler: crate::lightning::ln::peer_handler::CustomMessageHandler) -> crate::lightning::ln::peer_handler::PeerManager { - let mut ret = lightning::ln::peer_handler::PeerManager::new(*unsafe { Box::from_raw(message_handler.take_inner()) }, our_node_secret.into_rust(), current_time, unsafe { &*ephemeral_random_data}, logger, custom_message_handler); +pub extern "C" fn PeerManager_new(mut message_handler: crate::lightning::ln::peer_handler::MessageHandler, mut current_time: u32, ephemeral_random_data: *const [u8; 32], mut logger: crate::lightning::util::logger::Logger, mut custom_message_handler: crate::lightning::ln::peer_handler::CustomMessageHandler, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner) -> crate::lightning::ln::peer_handler::PeerManager { + let mut ret = lightning::ln::peer_handler::PeerManager::new(*unsafe { Box::from_raw(message_handler.take_inner()) }, current_time, unsafe { &*ephemeral_random_data}, logger, custom_message_handler, node_signer); crate::lightning::ln::peer_handler::PeerManager { inner: ObjOps::heap_alloc(ret), is_owned: true } } -/// Get the list of node ids for peers which have completed the initial handshake. +/// Get a list of tuples mapping from node id to network addresses for peers which have +/// completed the initial handshake. +/// +/// For outbound connections, the [`PublicKey`] will be the same as the `their_node_id` parameter +/// passed in to [`Self::new_outbound_connection`], however entries will only appear once the initial +/// handshake has completed and we are sure the remote peer has the private key for the given +/// [`PublicKey`]. /// -/// For outbound connections, this will be the same as the their_node_id parameter passed in to -/// new_outbound_connection, however entries will only appear once the initial handshake has -/// completed and we are sure the remote peer has the private key for the given node_id. +/// The returned `Option`s will only be `Some` if an address had been previously given via +/// [`Self::new_outbound_connection`] or [`Self::new_inbound_connection`]. #[must_use] #[no_mangle] -pub extern "C" fn PeerManager_get_peer_node_ids(this_arg: &crate::lightning::ln::peer_handler::PeerManager) -> crate::c_types::derived::CVec_PublicKeyZ { +pub extern "C" fn PeerManager_get_peer_node_ids(this_arg: &crate::lightning::ln::peer_handler::PeerManager) -> crate::c_types::derived::CVec_C2Tuple_PublicKeyCOption_NetAddressZZZ { let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_peer_node_ids(); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::c_types::PublicKey::from_rust(&item) }); }; + let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { let (mut orig_ret_0_0, mut orig_ret_0_1) = item; let mut local_orig_ret_0_1 = if orig_ret_0_1.is_none() { crate::c_types::derived::COption_NetAddressZ::None } else { crate::c_types::derived::COption_NetAddressZ::Some( { crate::lightning::ln::msgs::NetAddress::native_into(orig_ret_0_1.unwrap()) }) }; let mut local_ret_0 = (crate::c_types::PublicKey::from_rust(&orig_ret_0_0), local_orig_ret_0_1).into(); local_ret_0 }); }; local_ret.into() } -/// Indicates a new outbound connection has been established to a node with the given node_id +/// Indicates a new outbound connection has been established to a node with the given `node_id` /// and an optional remote network address. /// /// The remote network address adds the option to report a remote IP address back to a connecting @@ -1197,6 +1191,9 @@ pub extern "C" fn PeerManager_write_buffer_space_avail(this_arg: &crate::lightni /// [`send_data`] call on this descriptor has `resume_read` set (preventing DoS issues in the /// send buffer). /// +/// In order to avoid processing too many messages at once per peer, `data` should be on the +/// order of 4KiB. +/// /// [`send_data`]: SocketDescriptor::send_data /// [`process_events`]: PeerManager::process_events #[must_use] @@ -1237,16 +1234,13 @@ pub extern "C" fn PeerManager_socket_disconnected(this_arg: &crate::lightning::l /// Disconnect a peer given its node id. /// -/// Set `no_connection_possible` to true to prevent any further connection with this peer, -/// force-closing any channels we have with it. -/// /// If a peer is connected, this will call [`disconnect_socket`] on the descriptor for the /// peer. Thus, be very careful about reentrancy issues. /// /// [`disconnect_socket`]: SocketDescriptor::disconnect_socket #[no_mangle] -pub extern "C" fn PeerManager_disconnect_by_node_id(this_arg: &crate::lightning::ln::peer_handler::PeerManager, mut node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) { - unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.disconnect_by_node_id(node_id.into_rust(), no_connection_possible) +pub extern "C" fn PeerManager_disconnect_by_node_id(this_arg: &crate::lightning::ln::peer_handler::PeerManager, mut node_id: crate::c_types::PublicKey) { + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.disconnect_by_node_id(node_id.into_rust()) } /// Disconnects all currently-connected peers. This is useful on platforms where there may be diff --git a/lightning-c-bindings/src/lightning/mod.rs b/lightning-c-bindings/src/lightning/mod.rs index 240ef3f..dc497c5 100644 --- a/lightning-c-bindings/src/lightning/mod.rs +++ b/lightning-c-bindings/src/lightning/mod.rs @@ -58,6 +58,17 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; +mod invoice { + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + +} mod invoice_request { use alloc::str::FromStr; @@ -101,6 +112,17 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; +mod sealed { + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + +} } mod payer { @@ -112,6 +134,17 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; +} +mod refund { + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + } } mod io_extras { @@ -146,4 +179,26 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; +mod fairrwlock { + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + +} +mod ext_impl { + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + +} } diff --git a/lightning-c-bindings/src/lightning/onion_message/blinded_path.rs b/lightning-c-bindings/src/lightning/onion_message/blinded_path.rs index 883db0a..9051d24 100644 --- a/lightning-c-bindings/src/lightning/onion_message/blinded_path.rs +++ b/lightning-c-bindings/src/lightning/onion_message/blinded_path.rs @@ -164,9 +164,9 @@ pub extern "C" fn BlindedHop_clone(orig: &BlindedHop) -> BlindedHop { /// Errors if less than two hops are provided or if `node_pk`(s) are invalid. #[must_use] #[no_mangle] -pub extern "C" fn BlindedPath_new(mut node_pks: crate::c_types::derived::CVec_PublicKeyZ, keys_manager: &crate::lightning::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_BlindedPathNoneZ { +pub extern "C" fn BlindedPath_new(mut node_pks: crate::c_types::derived::CVec_PublicKeyZ, entropy_source: &crate::lightning::chain::keysinterface::EntropySource) -> crate::c_types::derived::CResult_BlindedPathNoneZ { let mut local_node_pks = Vec::new(); for mut item in node_pks.into_rust().drain(..) { local_node_pks.push( { item.into_rust() }); }; - let mut ret = lightning::onion_message::blinded_path::BlindedPath::new(&local_node_pks[..], keys_manager, secp256k1::global::SECP256K1); + let mut ret = lightning::onion_message::blinded_path::BlindedPath::new(&local_node_pks[..], entropy_source, secp256k1::global::SECP256K1); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::onion_message::blinded_path::BlindedPath { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning/onion_message/messenger.rs b/lightning-c-bindings/src/lightning/onion_message/messenger.rs index e9ac8b3..fec6c76 100644 --- a/lightning-c-bindings/src/lightning/onion_message/messenger.rs +++ b/lightning-c-bindings/src/lightning/onion_message/messenger.rs @@ -19,7 +19,7 @@ use alloc::{vec::Vec, boxed::Box}; use lightning::onion_message::messenger::OnionMessenger as nativeOnionMessengerImport; -pub(crate) type nativeOnionMessenger = nativeOnionMessengerImport; +pub(crate) type nativeOnionMessenger = nativeOnionMessengerImport; /// A sender, receiver and forwarder of onion messages. In upcoming releases, this object will be /// used to retrieve invoices and fulfill invoice requests from [offers]. Currently, only sending @@ -31,16 +31,16 @@ pub(crate) type nativeOnionMessenger = nativeOnionMessengerImport crate::lightning::onion_message::messenger::OnionMessenger { - let mut ret = lightning::onion_message::messenger::OnionMessenger::new(keys_manager, logger, custom_handler); +pub extern "C" fn OnionMessenger_new(mut entropy_source: crate::lightning::chain::keysinterface::EntropySource, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut custom_handler: crate::lightning::onion_message::messenger::CustomOnionMessageHandler) -> crate::lightning::onion_message::messenger::OnionMessenger { + let mut ret = lightning::onion_message::messenger::OnionMessenger::new(entropy_source, node_signer, logger, custom_handler); crate::lightning::onion_message::messenger::OnionMessenger { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -517,13 +517,13 @@ extern "C" fn OnionMessenger_OnionMessageHandler_handle_onion_message(this_arg: >::handle_onion_message(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &peer_node_id.into_rust(), msg.get_native_ref()) } #[must_use] -extern "C" fn OnionMessenger_OnionMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init) -> crate::c_types::derived::CResult_NoneNoneZ { - let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust(), init.get_native_ref()); +extern "C" fn OnionMessenger_OnionMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init, mut inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ { + let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust(), init.get_native_ref(), inbound); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } -extern "C" fn OnionMessenger_OnionMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, mut no_connection_possible: bool) { - >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust(), no_connection_possible) +extern "C" fn OnionMessenger_OnionMessageHandler_peer_disconnected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey) { + >::peer_disconnected(unsafe { &mut *(this_arg as *mut nativeOnionMessenger) }, &their_node_id.into_rust()) } #[must_use] extern "C" fn OnionMessenger_OnionMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures { diff --git a/lightning-c-bindings/src/lightning/routing/gossip.rs b/lightning-c-bindings/src/lightning/routing/gossip.rs index a035af6..6284e6c 100644 --- a/lightning-c-bindings/src/lightning/routing/gossip.rs +++ b/lightning-c-bindings/src/lightning/routing/gossip.rs @@ -6,7 +6,7 @@ // license as that which applies to the original source files from which this // source was automatically generated. -//! The top-level network map tracking logic lives here. +//! The [`NetworkGraph`] stores the network gossip and [`P2PGossipSync`] fetches it from peers use alloc::str::FromStr; use core::ffi::c_void; @@ -418,7 +418,7 @@ pub extern "C" fn NetworkUpdate_read(ser: crate::c_types::u8slice) -> crate::c_t } use lightning::routing::gossip::P2PGossipSync as nativeP2PGossipSyncImport; -pub(crate) type nativeP2PGossipSync = nativeP2PGossipSyncImport<&'static lightning::routing::gossip::NetworkGraph, crate::lightning::chain::Access, crate::lightning::util::logger::Logger>; +pub(crate) type nativeP2PGossipSync = nativeP2PGossipSyncImport<&'static lightning::routing::gossip::NetworkGraph, crate::lightning::routing::utxo::UtxoLookup, crate::lightning::util::logger::Logger>; /// Receives and validates network updates from peers, /// stores authentic and relevant data as a network graph. @@ -473,14 +473,13 @@ impl P2PGossipSync { } /// Creates a new tracker of the actual state of the network of channels and nodes, /// assuming an existing Network Graph. -/// Chain monitor is used to make sure announced channels exist on-chain, -/// channel data is correct, and that the announcement is signed with -/// channel owners' keys. +/// UTXO lookup is used to make sure announced channels exist on-chain, channel data is +/// correct, and the announcement is signed with channel owners' keys. #[must_use] #[no_mangle] -pub extern "C" fn P2PGossipSync_new(network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut chain_access: crate::c_types::derived::COption_AccessZ, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::routing::gossip::P2PGossipSync { - let mut local_chain_access = { /* chain_access*/ let chain_access_opt = chain_access; { } if chain_access_opt.is_none() { None } else { Some({ chain_access_opt.take() }) } }; - let mut ret = lightning::routing::gossip::P2PGossipSync::new(network_graph.get_native_ref(), local_chain_access, logger); +pub extern "C" fn P2PGossipSync_new(network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut utxo_lookup: crate::c_types::derived::COption_UtxoLookupZ, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::routing::gossip::P2PGossipSync { + let mut local_utxo_lookup = { /* utxo_lookup*/ let utxo_lookup_opt = utxo_lookup; { } if utxo_lookup_opt.is_none() { None } else { Some({ utxo_lookup_opt.take() }) } }; + let mut ret = lightning::routing::gossip::P2PGossipSync::new(network_graph.get_native_ref(), local_utxo_lookup, logger); crate::lightning::routing::gossip::P2PGossipSync { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -488,9 +487,9 @@ pub extern "C" fn P2PGossipSync_new(network_graph: &crate::lightning::routing::g /// existing announcements unless they are updated. /// Add, update or remove the provider would replace the current one. #[no_mangle] -pub extern "C" fn P2PGossipSync_add_chain_access(this_arg: &mut crate::lightning::routing::gossip::P2PGossipSync, mut chain_access: crate::c_types::derived::COption_AccessZ) { - let mut local_chain_access = { /* chain_access*/ let chain_access_opt = chain_access; { } if chain_access_opt.is_none() { None } else { Some({ chain_access_opt.take() }) } }; - unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::gossip::nativeP2PGossipSync)) }.add_chain_access(local_chain_access) +pub extern "C" fn P2PGossipSync_add_utxo_lookup(this_arg: &mut crate::lightning::routing::gossip::P2PGossipSync, mut utxo_lookup: crate::c_types::derived::COption_UtxoLookupZ) { + let mut local_utxo_lookup = { /* utxo_lookup*/ let utxo_lookup_opt = utxo_lookup; { } if utxo_lookup_opt.is_none() { None } else { Some({ utxo_lookup_opt.take() }) } }; + unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::gossip::nativeP2PGossipSync)) }.add_utxo_lookup(local_utxo_lookup) } /// Handles any network updates originating from [`Event`]s. @@ -528,6 +527,7 @@ pub extern "C" fn P2PGossipSync_as_RoutingMessageHandler(this_arg: &P2PGossipSyn handle_reply_short_channel_ids_end: P2PGossipSync_RoutingMessageHandler_handle_reply_short_channel_ids_end, handle_query_channel_range: P2PGossipSync_RoutingMessageHandler_handle_query_channel_range, handle_query_short_channel_ids: P2PGossipSync_RoutingMessageHandler_handle_query_short_channel_ids, + processing_queue_high: P2PGossipSync_RoutingMessageHandler_processing_queue_high, provided_node_features: P2PGossipSync_RoutingMessageHandler_provided_node_features, provided_init_features: P2PGossipSync_RoutingMessageHandler_provided_init_features, MessageSendEventsProvider: crate::lightning::util::events::MessageSendEventsProvider { @@ -563,15 +563,15 @@ extern "C" fn P2PGossipSync_RoutingMessageHandler_get_next_channel_announcement( local_ret } #[must_use] -extern "C" fn P2PGossipSync_RoutingMessageHandler_get_next_node_announcement(this_arg: *const c_void, mut starting_point: crate::c_types::PublicKey) -> crate::lightning::ln::msgs::NodeAnnouncement { - let mut local_starting_point_base = if starting_point.is_null() { None } else { Some( { starting_point.into_rust() }) }; let mut local_starting_point = local_starting_point_base.as_ref(); +extern "C" fn P2PGossipSync_RoutingMessageHandler_get_next_node_announcement(this_arg: *const c_void, mut starting_point: crate::lightning::routing::gossip::NodeId) -> crate::lightning::ln::msgs::NodeAnnouncement { + let mut local_starting_point = if starting_point.inner.is_null() { None } else { Some( { starting_point.get_native_ref() }) }; let mut ret = >::get_next_node_announcement(unsafe { &mut *(this_arg as *mut nativeP2PGossipSync) }, local_starting_point); let mut local_ret = crate::lightning::ln::msgs::NodeAnnouncement { inner: if ret.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((ret.unwrap())) } }, is_owned: true }; local_ret } #[must_use] -extern "C" fn P2PGossipSync_RoutingMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init) -> crate::c_types::derived::CResult_NoneNoneZ { - let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeP2PGossipSync) }, &their_node_id.into_rust(), init.get_native_ref()); +extern "C" fn P2PGossipSync_RoutingMessageHandler_peer_connected(this_arg: *const c_void, mut their_node_id: crate::c_types::PublicKey, init: &crate::lightning::ln::msgs::Init, mut inbound: bool) -> crate::c_types::derived::CResult_NoneNoneZ { + let mut ret = >::peer_connected(unsafe { &mut *(this_arg as *mut nativeP2PGossipSync) }, &their_node_id.into_rust(), init.get_native_ref(), inbound); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { () /*e*/ }).into() }; local_ret } @@ -600,6 +600,11 @@ extern "C" fn P2PGossipSync_RoutingMessageHandler_handle_query_short_channel_ids local_ret } #[must_use] +extern "C" fn P2PGossipSync_RoutingMessageHandler_processing_queue_high(this_arg: *const c_void) -> bool { + let mut ret = >::processing_queue_high(unsafe { &mut *(this_arg as *mut nativeP2PGossipSync) }, ); + ret +} +#[must_use] extern "C" fn P2PGossipSync_RoutingMessageHandler_provided_node_features(this_arg: *const c_void) -> crate::lightning::ln::features::NodeFeatures { let mut ret = >::provided_node_features(unsafe { &mut *(this_arg as *mut nativeP2PGossipSync) }, ); crate::lightning::ln::features::NodeFeatures { inner: ObjOps::heap_alloc(ret), is_owned: true } @@ -1389,13 +1394,13 @@ impl RoutingFees { ret } } -/// Flat routing fee in satoshis +/// Flat routing fee in millisatoshis. #[no_mangle] pub extern "C" fn RoutingFees_get_base_msat(this_ptr: &RoutingFees) -> u32 { let mut inner_val = &mut this_ptr.get_native_mut_ref().base_msat; *inner_val } -/// Flat routing fee in satoshis +/// Flat routing fee in millisatoshis. #[no_mangle] pub extern "C" fn RoutingFees_set_base_msat(this_ptr: &mut RoutingFees, mut val: u32) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_msat = val; @@ -1855,27 +1860,6 @@ pub extern "C" fn NodeInfo_set_channels(this_ptr: &mut NodeInfo, mut val: crate: let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item }); }; unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.channels = local_val; } -/// Lowest fees enabling routing via any of the enabled, known channels to a node. -/// The two fields (flat and proportional fee) are independent, -/// meaning they don't have to refer to the same channel. -/// -/// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None -#[no_mangle] -pub extern "C" fn NodeInfo_get_lowest_inbound_channel_fees(this_ptr: &NodeInfo) -> crate::lightning::routing::gossip::RoutingFees { - let mut inner_val = &mut this_ptr.get_native_mut_ref().lowest_inbound_channel_fees; - let mut local_inner_val = crate::lightning::routing::gossip::RoutingFees { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::routing::gossip::RoutingFees<>) as *mut _ }, is_owned: false }; - local_inner_val -} -/// Lowest fees enabling routing via any of the enabled, known channels to a node. -/// The two fields (flat and proportional fee) are independent, -/// meaning they don't have to refer to the same channel. -/// -/// Note that val (or a relevant inner pointer) may be NULL or all-0s to represent None -#[no_mangle] -pub extern "C" fn NodeInfo_set_lowest_inbound_channel_fees(this_ptr: &mut NodeInfo, mut val: crate::lightning::routing::gossip::RoutingFees) { - let mut local_val = if val.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(val.take_inner()) } }) }; - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.lowest_inbound_channel_fees = local_val; -} /// More information about a node from node_announcement. /// Optional because we store a Node entry after learning about it from /// a channel announcement, but before receiving a node announcement. @@ -1900,13 +1884,11 @@ pub extern "C" fn NodeInfo_set_announcement_info(this_ptr: &mut NodeInfo, mut va /// Constructs a new NodeInfo given each field #[must_use] #[no_mangle] -pub extern "C" fn NodeInfo_new(mut channels_arg: crate::c_types::derived::CVec_u64Z, mut lowest_inbound_channel_fees_arg: crate::lightning::routing::gossip::RoutingFees, mut announcement_info_arg: crate::lightning::routing::gossip::NodeAnnouncementInfo) -> NodeInfo { +pub extern "C" fn NodeInfo_new(mut channels_arg: crate::c_types::derived::CVec_u64Z, mut announcement_info_arg: crate::lightning::routing::gossip::NodeAnnouncementInfo) -> NodeInfo { let mut local_channels_arg = Vec::new(); for mut item in channels_arg.into_rust().drain(..) { local_channels_arg.push( { item }); }; - let mut local_lowest_inbound_channel_fees_arg = if lowest_inbound_channel_fees_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(lowest_inbound_channel_fees_arg.take_inner()) } }) }; let mut local_announcement_info_arg = if announcement_info_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(announcement_info_arg.take_inner()) } }) }; NodeInfo { inner: ObjOps::heap_alloc(nativeNodeInfo { channels: local_channels_arg, - lowest_inbound_channel_fees: local_lowest_inbound_channel_fees_arg, announcement_info: local_announcement_info_arg, }), is_owned: true } } @@ -1974,8 +1956,8 @@ pub extern "C" fn NetworkGraph_read(ser: crate::c_types::u8slice, arg: crate::li /// Creates a new, empty, network graph. #[must_use] #[no_mangle] -pub extern "C" fn NetworkGraph_new(mut genesis_hash: crate::c_types::ThirtyTwoBytes, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::routing::gossip::NetworkGraph { - let mut ret = lightning::routing::gossip::NetworkGraph::new(::bitcoin::hash_types::BlockHash::from_slice(&genesis_hash.data[..]).unwrap(), logger); +pub extern "C" fn NetworkGraph_new(mut network: crate::bitcoin::network::Network, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::routing::gossip::NetworkGraph { + let mut ret = lightning::routing::gossip::NetworkGraph::new(network.into_bitcoin(), logger); crate::lightning::routing::gossip::NetworkGraph { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -2036,13 +2018,13 @@ pub extern "C" fn NetworkGraph_update_node_from_unsigned_announcement(this_arg: /// RoutingMessageHandler implementation to call it indirectly. This may be useful to accept /// routing messages from a source using a protocol other than the lightning P2P protocol. /// -/// If a `chain::Access` object is provided via `chain_access`, it will be called to verify +/// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify /// the corresponding UTXO exists on chain and is correctly-formatted. #[must_use] #[no_mangle] -pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &crate::lightning::routing::gossip::NetworkGraph, msg: &crate::lightning::ln::msgs::ChannelAnnouncement, mut chain_access: crate::c_types::derived::COption_AccessZ) -> crate::c_types::derived::CResult_NoneLightningErrorZ { - let mut local_chain_access = { /* chain_access*/ let chain_access_opt = chain_access; { } if chain_access_opt.is_none() { None } else { Some({ chain_access_opt.take() }) } }; - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_channel_from_announcement(msg.get_native_ref(), &local_chain_access); +pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &crate::lightning::routing::gossip::NetworkGraph, msg: &crate::lightning::ln::msgs::ChannelAnnouncement, mut utxo_lookup: crate::c_types::derived::COption_UtxoLookupZ) -> crate::c_types::derived::CResult_NoneLightningErrorZ { + let mut local_utxo_lookup = { /* utxo_lookup*/ let utxo_lookup_opt = utxo_lookup; { } if utxo_lookup_opt.is_none() { None } else { Some({ utxo_lookup_opt.take() }) } }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_channel_from_announcement(msg.get_native_ref(), &local_utxo_lookup); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } @@ -2051,13 +2033,13 @@ pub extern "C" fn NetworkGraph_update_channel_from_announcement(this_arg: &crate /// signatures. Because we aren't given the associated signatures here we cannot relay the /// channel announcement to any of our peers. /// -/// If a `chain::Access` object is provided via `chain_access`, it will be called to verify +/// If a [`UtxoLookup`] object is provided via `utxo_lookup`, it will be called to verify /// the corresponding UTXO exists on chain and is correctly-formatted. #[must_use] #[no_mangle] -pub extern "C" fn NetworkGraph_update_channel_from_unsigned_announcement(this_arg: &crate::lightning::routing::gossip::NetworkGraph, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement, mut chain_access: crate::c_types::derived::COption_AccessZ) -> crate::c_types::derived::CResult_NoneLightningErrorZ { - let mut local_chain_access = { /* chain_access*/ let chain_access_opt = chain_access; { } if chain_access_opt.is_none() { None } else { Some({ chain_access_opt.take() }) } }; - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_channel_from_unsigned_announcement(msg.get_native_ref(), &local_chain_access); +pub extern "C" fn NetworkGraph_update_channel_from_unsigned_announcement(this_arg: &crate::lightning::routing::gossip::NetworkGraph, msg: &crate::lightning::ln::msgs::UnsignedChannelAnnouncement, mut utxo_lookup: crate::c_types::derived::COption_UtxoLookupZ) -> crate::c_types::derived::CResult_NoneLightningErrorZ { + let mut local_utxo_lookup = { /* utxo_lookup*/ let utxo_lookup_opt = utxo_lookup; { } if utxo_lookup_opt.is_none() { None } else { Some({ utxo_lookup_opt.take() }) } }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_channel_from_unsigned_announcement(msg.get_native_ref(), &local_utxo_lookup); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning/routing/mod.rs b/lightning-c-bindings/src/lightning/routing/mod.rs index 153f9df..d010ca5 100644 --- a/lightning-c-bindings/src/lightning/routing/mod.rs +++ b/lightning-c-bindings/src/lightning/routing/mod.rs @@ -16,6 +16,7 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; +pub mod utxo; pub mod gossip; pub mod router; pub mod scoring; diff --git a/lightning-c-bindings/src/lightning/routing/router.rs b/lightning-c-bindings/src/lightning/routing/router.rs index d2f7a30..cacfc22 100644 --- a/lightning-c-bindings/src/lightning/routing/router.rs +++ b/lightning-c-bindings/src/lightning/routing/router.rs @@ -6,10 +6,7 @@ // license as that which applies to the original source files from which this // source was automatically generated. -//! The top-level routing/network map tracking logic lives here. -//! -//! You probably want to create a P2PGossipSync and use that as your RoutingMessageHandler and then -//! interrogate it to get routes for your own payments. +//! The router finds paths within a [`NetworkGraph`] for a payment. use alloc::str::FromStr; use core::ffi::c_void; @@ -97,43 +94,23 @@ pub extern "C" fn DefaultRouter_as_Router(this_arg: &DefaultRouter) -> crate::li free: None, find_route: DefaultRouter_Router_find_route, find_route_with_id: DefaultRouter_Router_find_route_with_id, - notify_payment_path_failed: DefaultRouter_Router_notify_payment_path_failed, - notify_payment_path_successful: DefaultRouter_Router_notify_payment_path_successful, - notify_payment_probe_successful: DefaultRouter_Router_notify_payment_probe_successful, - notify_payment_probe_failed: DefaultRouter_Router_notify_payment_probe_failed, } } #[must_use] -extern "C" fn DefaultRouter_Router_find_route(this_arg: *const c_void, mut payer: crate::c_types::PublicKey, route_params: &crate::lightning::routing::router::RouteParameters, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, mut inflight_htlcs: crate::lightning::routing::router::InFlightHtlcs) -> crate::c_types::derived::CResult_RouteLightningErrorZ { +extern "C" fn DefaultRouter_Router_find_route(this_arg: *const c_void, mut payer: crate::c_types::PublicKey, route_params: &crate::lightning::routing::router::RouteParameters, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, inflight_htlcs: &crate::lightning::routing::router::InFlightHtlcs) -> crate::c_types::derived::CResult_RouteLightningErrorZ { let mut local_first_hops_base = if first_hops == core::ptr::null_mut() { None } else { Some( { let mut local_first_hops_0 = Vec::new(); for mut item in unsafe { &mut *first_hops }.as_slice().iter() { local_first_hops_0.push( { item.get_native_ref() }); }; local_first_hops_0 }) }; let mut local_first_hops = local_first_hops_base.as_ref().map(|a| &a[..]); - let mut ret = >::find_route(unsafe { &mut *(this_arg as *mut nativeDefaultRouter) }, &payer.into_rust(), route_params.get_native_ref(), local_first_hops, *unsafe { Box::from_raw(inflight_htlcs.take_inner()) }); + let mut ret = >::find_route(unsafe { &mut *(this_arg as *mut nativeDefaultRouter) }, &payer.into_rust(), route_params.get_native_ref(), local_first_hops, inflight_htlcs.get_native_ref()); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::Route { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } #[must_use] -extern "C" fn DefaultRouter_Router_find_route_with_id(this_arg: *const c_void, mut payer: crate::c_types::PublicKey, route_params: &crate::lightning::routing::router::RouteParameters, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, mut inflight_htlcs: crate::lightning::routing::router::InFlightHtlcs, mut _payment_hash: crate::c_types::ThirtyTwoBytes, mut _payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_RouteLightningErrorZ { +extern "C" fn DefaultRouter_Router_find_route_with_id(this_arg: *const c_void, mut payer: crate::c_types::PublicKey, route_params: &crate::lightning::routing::router::RouteParameters, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, inflight_htlcs: &crate::lightning::routing::router::InFlightHtlcs, mut _payment_hash: crate::c_types::ThirtyTwoBytes, mut _payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_RouteLightningErrorZ { let mut local_first_hops_base = if first_hops == core::ptr::null_mut() { None } else { Some( { let mut local_first_hops_0 = Vec::new(); for mut item in unsafe { &mut *first_hops }.as_slice().iter() { local_first_hops_0.push( { item.get_native_ref() }); }; local_first_hops_0 }) }; let mut local_first_hops = local_first_hops_base.as_ref().map(|a| &a[..]); - let mut ret = >::find_route_with_id(unsafe { &mut *(this_arg as *mut nativeDefaultRouter) }, &payer.into_rust(), route_params.get_native_ref(), local_first_hops, *unsafe { Box::from_raw(inflight_htlcs.take_inner()) }, ::lightning::ln::PaymentHash(_payment_hash.data), ::lightning::ln::channelmanager::PaymentId(_payment_id.data)); + let mut ret = >::find_route_with_id(unsafe { &mut *(this_arg as *mut nativeDefaultRouter) }, &payer.into_rust(), route_params.get_native_ref(), local_first_hops, inflight_htlcs.get_native_ref(), ::lightning::ln::PaymentHash(_payment_hash.data), ::lightning::ln::channelmanager::PaymentId(_payment_id.data)); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::Route { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() }; local_ret } -extern "C" fn DefaultRouter_Router_notify_payment_path_failed(this_arg: *const c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) { - let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); }; - >::notify_payment_path_failed(unsafe { &mut *(this_arg as *mut nativeDefaultRouter) }, &local_path[..], short_channel_id) -} -extern "C" fn DefaultRouter_Router_notify_payment_path_successful(this_arg: *const c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) { - let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); }; - >::notify_payment_path_successful(unsafe { &mut *(this_arg as *mut nativeDefaultRouter) }, &local_path[..]) -} -extern "C" fn DefaultRouter_Router_notify_payment_probe_successful(this_arg: *const c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) { - let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); }; - >::notify_payment_probe_successful(unsafe { &mut *(this_arg as *mut nativeDefaultRouter) }, &local_path[..]) -} -extern "C" fn DefaultRouter_Router_notify_payment_probe_failed(this_arg: *const c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) { - let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); }; - >::notify_payment_probe_failed(unsafe { &mut *(this_arg as *mut nativeDefaultRouter) }, &local_path[..], short_channel_id) -} /// A trait defining behavior for routing a payment. #[repr(C)] @@ -145,21 +122,13 @@ pub struct Router { /// /// Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] - pub find_route: extern "C" fn (this_arg: *const c_void, payer: crate::c_types::PublicKey, route_params: &crate::lightning::routing::router::RouteParameters, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, inflight_htlcs: crate::lightning::routing::router::InFlightHtlcs) -> crate::c_types::derived::CResult_RouteLightningErrorZ, + pub find_route: extern "C" fn (this_arg: *const c_void, payer: crate::c_types::PublicKey, route_params: &crate::lightning::routing::router::RouteParameters, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, inflight_htlcs: &crate::lightning::routing::router::InFlightHtlcs) -> crate::c_types::derived::CResult_RouteLightningErrorZ, /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment. /// /// Note that first_hops (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] - pub find_route_with_id: extern "C" fn (this_arg: *const c_void, payer: crate::c_types::PublicKey, route_params: &crate::lightning::routing::router::RouteParameters, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, inflight_htlcs: crate::lightning::routing::router::InFlightHtlcs, _payment_hash: crate::c_types::ThirtyTwoBytes, _payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_RouteLightningErrorZ, - /// Lets the router know that payment through a specific path has failed. - pub notify_payment_path_failed: extern "C" fn (this_arg: *const c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64), - /// Lets the router know that payment through a specific path was successful. - pub notify_payment_path_successful: extern "C" fn (this_arg: *const c_void, path: crate::c_types::derived::CVec_RouteHopZ), - /// Lets the router know that a payment probe was successful. - pub notify_payment_probe_successful: extern "C" fn (this_arg: *const c_void, path: crate::c_types::derived::CVec_RouteHopZ), - /// Lets the router know that a payment probe failed. - pub notify_payment_probe_failed: extern "C" fn (this_arg: *const c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64), + pub find_route_with_id: extern "C" fn (this_arg: *const c_void, payer: crate::c_types::PublicKey, route_params: &crate::lightning::routing::router::RouteParameters, first_hops: *mut crate::c_types::derived::CVec_ChannelDetailsZ, inflight_htlcs: &crate::lightning::routing::router::InFlightHtlcs, _payment_hash: crate::c_types::ThirtyTwoBytes, _payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_RouteLightningErrorZ, /// Frees any resources associated with this object given its this_arg pointer. /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. pub free: Option, @@ -172,44 +141,24 @@ pub(crate) extern "C" fn Router_clone_fields(orig: &Router) -> Router { this_arg: orig.this_arg, find_route: Clone::clone(&orig.find_route), find_route_with_id: Clone::clone(&orig.find_route_with_id), - notify_payment_path_failed: Clone::clone(&orig.notify_payment_path_failed), - notify_payment_path_successful: Clone::clone(&orig.notify_payment_path_successful), - notify_payment_probe_successful: Clone::clone(&orig.notify_payment_probe_successful), - notify_payment_probe_failed: Clone::clone(&orig.notify_payment_probe_failed), free: Clone::clone(&orig.free), } } use lightning::routing::router::Router as rustRouter; impl rustRouter for Router { - fn find_route(&self, mut payer: &bitcoin::secp256k1::PublicKey, mut route_params: &lightning::routing::router::RouteParameters, mut first_hops: Option<&[&lightning::ln::channelmanager::ChannelDetails]>, mut inflight_htlcs: lightning::routing::router::InFlightHtlcs) -> Result { + fn find_route(&self, mut payer: &bitcoin::secp256k1::PublicKey, mut route_params: &lightning::routing::router::RouteParameters, mut first_hops: Option<&[&lightning::ln::channelmanager::ChannelDetails]>, mut inflight_htlcs: &lightning::routing::router::InFlightHtlcs) -> Result { let mut local_first_hops_base = if first_hops.is_none() { SmartPtr::null() } else { SmartPtr::from_obj( { let mut local_first_hops_0 = Vec::new(); for item in (first_hops.unwrap()).iter() { local_first_hops_0.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::ln::channelmanager::ChannelDetails<>) as *mut _) }, is_owned: false } }); }; local_first_hops_0.into() }) }; let mut local_first_hops = *local_first_hops_base; - let mut ret = (self.find_route)(self.this_arg, crate::c_types::PublicKey::from_rust(&payer), &crate::lightning::routing::router::RouteParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route_params as *const lightning::routing::router::RouteParameters<>) as *mut _) }, is_owned: false }, local_first_hops, crate::lightning::routing::router::InFlightHtlcs { inner: ObjOps::heap_alloc(inflight_htlcs), is_owned: true }); + let mut ret = (self.find_route)(self.this_arg, crate::c_types::PublicKey::from_rust(&payer), &crate::lightning::routing::router::RouteParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route_params as *const lightning::routing::router::RouteParameters<>) as *mut _) }, is_owned: false }, local_first_hops, &crate::lightning::routing::router::InFlightHtlcs { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inflight_htlcs as *const lightning::routing::router::InFlightHtlcs<>) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).take_inner()) } }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } - fn find_route_with_id(&self, mut payer: &bitcoin::secp256k1::PublicKey, mut route_params: &lightning::routing::router::RouteParameters, mut first_hops: Option<&[&lightning::ln::channelmanager::ChannelDetails]>, mut inflight_htlcs: lightning::routing::router::InFlightHtlcs, mut _payment_hash: lightning::ln::PaymentHash, mut _payment_id: lightning::ln::channelmanager::PaymentId) -> Result { + fn find_route_with_id(&self, mut payer: &bitcoin::secp256k1::PublicKey, mut route_params: &lightning::routing::router::RouteParameters, mut first_hops: Option<&[&lightning::ln::channelmanager::ChannelDetails]>, mut inflight_htlcs: &lightning::routing::router::InFlightHtlcs, mut _payment_hash: lightning::ln::PaymentHash, mut _payment_id: lightning::ln::channelmanager::PaymentId) -> Result { let mut local_first_hops_base = if first_hops.is_none() { SmartPtr::null() } else { SmartPtr::from_obj( { let mut local_first_hops_0 = Vec::new(); for item in (first_hops.unwrap()).iter() { local_first_hops_0.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::ln::channelmanager::ChannelDetails<>) as *mut _) }, is_owned: false } }); }; local_first_hops_0.into() }) }; let mut local_first_hops = *local_first_hops_base; - let mut ret = (self.find_route_with_id)(self.this_arg, crate::c_types::PublicKey::from_rust(&payer), &crate::lightning::routing::router::RouteParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route_params as *const lightning::routing::router::RouteParameters<>) as *mut _) }, is_owned: false }, local_first_hops, crate::lightning::routing::router::InFlightHtlcs { inner: ObjOps::heap_alloc(inflight_htlcs), is_owned: true }, crate::c_types::ThirtyTwoBytes { data: _payment_hash.0 }, crate::c_types::ThirtyTwoBytes { data: _payment_id.0 }); + let mut ret = (self.find_route_with_id)(self.this_arg, crate::c_types::PublicKey::from_rust(&payer), &crate::lightning::routing::router::RouteParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route_params as *const lightning::routing::router::RouteParameters<>) as *mut _) }, is_owned: false }, local_first_hops, &crate::lightning::routing::router::InFlightHtlcs { inner: unsafe { ObjOps::nonnull_ptr_to_inner((inflight_htlcs as *const lightning::routing::router::InFlightHtlcs<>) as *mut _) }, is_owned: false }, crate::c_types::ThirtyTwoBytes { data: _payment_hash.0 }, crate::c_types::ThirtyTwoBytes { data: _payment_id.0 }); let mut local_ret = match ret.result_ok { true => Ok( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) }).take_inner()) } }), false => Err( { *unsafe { Box::from_raw((*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).take_inner()) } })}; local_ret } - fn notify_payment_path_failed(&self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) { - let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); }; - (self.notify_payment_path_failed)(self.this_arg, local_path.into(), short_channel_id) - } - fn notify_payment_path_successful(&self, mut path: &[&lightning::routing::router::RouteHop]) { - let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); }; - (self.notify_payment_path_successful)(self.this_arg, local_path.into()) - } - fn notify_payment_probe_successful(&self, mut path: &[&lightning::routing::router::RouteHop]) { - let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); }; - (self.notify_payment_probe_successful)(self.this_arg, local_path.into()) - } - fn notify_payment_probe_failed(&self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) { - let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); }; - (self.notify_payment_probe_failed)(self.this_arg, local_path.into(), short_channel_id) - } } // We're essentially a pointer already, or at least a set of pointers, so allow us to be used @@ -232,7 +181,7 @@ impl Drop for Router { } use lightning::routing::router::ScorerAccountingForInFlightHtlcs as nativeScorerAccountingForInFlightHtlcsImport; -pub(crate) type nativeScorerAccountingForInFlightHtlcs = nativeScorerAccountingForInFlightHtlcsImport; +pub(crate) type nativeScorerAccountingForInFlightHtlcs = nativeScorerAccountingForInFlightHtlcsImport<'static, crate::lightning::routing::scoring::Score>; /// [`Score`] implementation that factors in in-flight HTLC liquidity. /// @@ -289,8 +238,8 @@ impl ScorerAccountingForInFlightHtlcs { /// Initialize a new `ScorerAccountingForInFlightHtlcs`. #[must_use] #[no_mangle] -pub extern "C" fn ScorerAccountingForInFlightHtlcs_new(mut scorer: crate::lightning::routing::scoring::Score, mut inflight_htlcs: crate::lightning::routing::router::InFlightHtlcs) -> crate::lightning::routing::router::ScorerAccountingForInFlightHtlcs { - let mut ret = lightning::routing::router::ScorerAccountingForInFlightHtlcs::new(scorer, *unsafe { Box::from_raw(inflight_htlcs.take_inner()) }); +pub extern "C" fn ScorerAccountingForInFlightHtlcs_new(mut scorer: crate::lightning::routing::scoring::Score, inflight_htlcs: &crate::lightning::routing::router::InFlightHtlcs) -> crate::lightning::routing::router::ScorerAccountingForInFlightHtlcs { + let mut ret = lightning::routing::router::ScorerAccountingForInFlightHtlcs::new(scorer, inflight_htlcs.get_native_ref()); crate::lightning::routing::router::ScorerAccountingForInFlightHtlcs { inner: ObjOps::heap_alloc(ret), is_owned: true } } @@ -839,7 +788,7 @@ pub(crate) type nativeRouteParameters = nativeRouteParametersImport; /// Parameters needed to find a [`Route`]. /// /// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in -/// [`Event::PaymentPathFailed`] for retrying a failed payment path. +/// [`Event::PaymentPathFailed`]. /// /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed #[must_use] @@ -910,25 +859,13 @@ pub extern "C" fn RouteParameters_get_final_value_msat(this_ptr: &RouteParameter pub extern "C" fn RouteParameters_set_final_value_msat(this_ptr: &mut RouteParameters, mut val: u64) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.final_value_msat = val; } -/// The CLTV on the final hop of the failed payment path. -#[no_mangle] -pub extern "C" fn RouteParameters_get_final_cltv_expiry_delta(this_ptr: &RouteParameters) -> u32 { - let mut inner_val = &mut this_ptr.get_native_mut_ref().final_cltv_expiry_delta; - *inner_val -} -/// The CLTV on the final hop of the failed payment path. -#[no_mangle] -pub extern "C" fn RouteParameters_set_final_cltv_expiry_delta(this_ptr: &mut RouteParameters, mut val: u32) { - unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.final_cltv_expiry_delta = val; -} /// Constructs a new RouteParameters given each field #[must_use] #[no_mangle] -pub extern "C" fn RouteParameters_new(mut payment_params_arg: crate::lightning::routing::router::PaymentParameters, mut final_value_msat_arg: u64, mut final_cltv_expiry_delta_arg: u32) -> RouteParameters { +pub extern "C" fn RouteParameters_new(mut payment_params_arg: crate::lightning::routing::router::PaymentParameters, mut final_value_msat_arg: u64) -> RouteParameters { RouteParameters { inner: ObjOps::heap_alloc(nativeRouteParameters { payment_params: *unsafe { Box::from_raw(payment_params_arg.take_inner()) }, final_value_msat: final_value_msat_arg, - final_cltv_expiry_delta: final_cltv_expiry_delta_arg, }), is_owned: true } } impl Clone for RouteParameters { @@ -950,6 +887,15 @@ pub(crate) extern "C" fn RouteParameters_clone_void(this_ptr: *const c_void) -> pub extern "C" fn RouteParameters_clone(orig: &RouteParameters) -> RouteParameters { orig.clone() } +/// Checks if two RouteParameterss contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +/// Two objects with NULL inner values will be considered "equal" here. +#[no_mangle] +pub extern "C" fn RouteParameters_eq(a: &RouteParameters, b: &RouteParameters) -> bool { + if a.inner == b.inner { return true; } + if a.inner.is_null() || b.inner.is_null() { return false; } + if a.get_native_ref() == b.get_native_ref() { true } else { false } +} #[no_mangle] /// Serialize the RouteParameters object into a byte array which can be read by RouteParameters_read pub extern "C" fn RouteParameters_write(obj: &crate::lightning::routing::router::RouteParameters) -> crate::c_types::derived::CVec_u8Z { @@ -1169,10 +1115,21 @@ pub extern "C" fn PaymentParameters_set_previously_failed_channels(this_ptr: &mu let mut local_val = Vec::new(); for mut item in val.into_rust().drain(..) { local_val.push( { item }); }; unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.previously_failed_channels = local_val; } +/// The minimum CLTV delta at the end of the route. This value must not be zero. +#[no_mangle] +pub extern "C" fn PaymentParameters_get_final_cltv_expiry_delta(this_ptr: &PaymentParameters) -> u32 { + let mut inner_val = &mut this_ptr.get_native_mut_ref().final_cltv_expiry_delta; + *inner_val +} +/// The minimum CLTV delta at the end of the route. This value must not be zero. +#[no_mangle] +pub extern "C" fn PaymentParameters_set_final_cltv_expiry_delta(this_ptr: &mut PaymentParameters, mut val: u32) { + unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.final_cltv_expiry_delta = val; +} /// Constructs a new PaymentParameters given each field #[must_use] #[no_mangle] -pub extern "C" fn PaymentParameters_new(mut payee_pubkey_arg: crate::c_types::PublicKey, mut features_arg: crate::lightning::ln::features::InvoiceFeatures, mut route_hints_arg: crate::c_types::derived::CVec_RouteHintZ, mut expiry_time_arg: crate::c_types::derived::COption_u64Z, mut max_total_cltv_expiry_delta_arg: u32, mut max_path_count_arg: u8, mut max_channel_saturation_power_of_half_arg: u8, mut previously_failed_channels_arg: crate::c_types::derived::CVec_u64Z) -> PaymentParameters { +pub extern "C" fn PaymentParameters_new(mut payee_pubkey_arg: crate::c_types::PublicKey, mut features_arg: crate::lightning::ln::features::InvoiceFeatures, mut route_hints_arg: crate::c_types::derived::CVec_RouteHintZ, mut expiry_time_arg: crate::c_types::derived::COption_u64Z, mut max_total_cltv_expiry_delta_arg: u32, mut max_path_count_arg: u8, mut max_channel_saturation_power_of_half_arg: u8, mut previously_failed_channels_arg: crate::c_types::derived::CVec_u64Z, mut final_cltv_expiry_delta_arg: u32) -> PaymentParameters { let mut local_features_arg = if features_arg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(features_arg.take_inner()) } }) }; let mut local_route_hints_arg = Vec::new(); for mut item in route_hints_arg.into_rust().drain(..) { local_route_hints_arg.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; let mut local_expiry_time_arg = if expiry_time_arg.is_some() { Some( { expiry_time_arg.take() }) } else { None }; @@ -1186,6 +1143,7 @@ pub extern "C" fn PaymentParameters_new(mut payee_pubkey_arg: crate::c_types::Pu max_path_count: max_path_count_arg, max_channel_saturation_power_of_half: max_channel_saturation_power_of_half_arg, previously_failed_channels: local_previously_failed_channels_arg, + final_cltv_expiry_delta: final_cltv_expiry_delta_arg, }), is_owned: true } } impl Clone for PaymentParameters { @@ -1237,24 +1195,31 @@ pub(crate) extern "C" fn PaymentParameters_write_void(obj: *const c_void) -> cra } #[no_mangle] /// Read a PaymentParameters from a byte array, created by PaymentParameters_write -pub extern "C" fn PaymentParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_PaymentParametersDecodeErrorZ { - let res: Result = crate::c_types::deserialize_obj(ser); +pub extern "C" fn PaymentParameters_read(ser: crate::c_types::u8slice, arg: u32) -> crate::c_types::derived::CResult_PaymentParametersDecodeErrorZ { + let arg_conv = arg; + let res: Result = crate::c_types::deserialize_obj_arg(ser, arg_conv); let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::router::PaymentParameters { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } /// Creates a payee with the node id of the given `pubkey`. +/// +/// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has +/// provided. #[must_use] #[no_mangle] -pub extern "C" fn PaymentParameters_from_node_id(mut payee_pubkey: crate::c_types::PublicKey) -> crate::lightning::routing::router::PaymentParameters { - let mut ret = lightning::routing::router::PaymentParameters::from_node_id(payee_pubkey.into_rust()); +pub extern "C" fn PaymentParameters_from_node_id(mut payee_pubkey: crate::c_types::PublicKey, mut final_cltv_expiry_delta: u32) -> crate::lightning::routing::router::PaymentParameters { + let mut ret = lightning::routing::router::PaymentParameters::from_node_id(payee_pubkey.into_rust(), final_cltv_expiry_delta); crate::lightning::routing::router::PaymentParameters { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Creates a payee with the node id of the given `pubkey` to use for keysend payments. +/// +/// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has +/// provided. #[must_use] #[no_mangle] -pub extern "C" fn PaymentParameters_for_keysend(mut payee_pubkey: crate::c_types::PublicKey) -> crate::lightning::routing::router::PaymentParameters { - let mut ret = lightning::routing::router::PaymentParameters::for_keysend(payee_pubkey.into_rust()); +pub extern "C" fn PaymentParameters_for_keysend(mut payee_pubkey: crate::c_types::PublicKey, mut final_cltv_expiry_delta: u32) -> crate::lightning::routing::router::PaymentParameters { + let mut ret = lightning::routing::router::PaymentParameters::for_keysend(payee_pubkey.into_rust(), final_cltv_expiry_delta); crate::lightning::routing::router::PaymentParameters { inner: ObjOps::heap_alloc(ret), is_owned: true } } diff --git a/lightning-c-bindings/src/lightning/routing/scoring.rs b/lightning-c-bindings/src/lightning/routing/scoring.rs index 9fe4268..2c2980a 100644 --- a/lightning-c-bindings/src/lightning/routing/scoring.rs +++ b/lightning-c-bindings/src/lightning/routing/scoring.rs @@ -19,7 +19,7 @@ //! # use lightning::routing::gossip::NetworkGraph; //! # use lightning::routing::router::{RouteParameters, find_route}; //! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters}; -//! # use lightning::chain::keysinterface::{KeysManager, KeysInterface}; +//! # use lightning::chain::keysinterface::KeysManager; //! # use lightning::util::logger::{Logger, Record}; //! # use bitcoin::secp256k1::PublicKey; //! # @@ -1309,6 +1309,35 @@ pub extern "C" fn ProbabilisticScorer_estimated_channel_liquidity_range(this_arg local_ret } +/// Query the historical estimated minimum and maximum liquidity available for sending a +/// payment over the channel with `scid` towards the given `target` node. +/// +/// Returns two sets of 8 buckets. The first set describes the octiles for lower-bound +/// liquidity estimates, the second set describes the octiles for upper-bound liquidity +/// estimates. Each bucket describes the relative frequency at which we've seen a liquidity +/// bound in the octile relative to the channel's total capacity, on an arbitrary scale. +/// Because the values are slowly decayed, more recent data points are weighted more heavily +/// than older datapoints. +/// +/// When scoring, the estimated probability that an upper-/lower-bound lies in a given octile +/// relative to the channel's total capacity is calculated by dividing that bucket's value with +/// the total of all buckets for the given bound. +/// +/// For example, a value of `[0, 0, 0, 0, 0, 0, 32]` indicates that we believe the probability +/// of a bound being in the top octile to be 100%, and have never (recently) seen it in any +/// other octiles. A value of `[31, 0, 0, 0, 0, 0, 0, 32]` indicates we've seen the bound being +/// both in the top and bottom octile, and roughly with similar (recent) frequency. +/// +/// Because the datapoints are decayed slowly over time, values will eventually return to +/// `Some(([0; 8], [0; 8]))`. +#[must_use] +#[no_mangle] +pub extern "C" fn ProbabilisticScorer_historical_estimated_channel_liquidity_probabilities(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer, mut scid: u64, target: &crate::lightning::routing::gossip::NodeId) -> crate::c_types::derived::COption_C2Tuple_EightU16sEightU16sZZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.historical_estimated_channel_liquidity_probabilities(scid, target.get_native_ref()); + let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_C2Tuple_EightU16sEightU16sZZ::None } else { crate::c_types::derived::COption_C2Tuple_EightU16sEightU16sZZ::Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (ret.unwrap()); let mut local_ret_0 = (crate::c_types::EightU16s { data: orig_ret_0_0 }, crate::c_types::EightU16s { data: orig_ret_0_1 }).into(); local_ret_0 }) }; + local_ret +} + /// Marks the node with the given `node_id` as banned, i.e., /// it will be avoided during path finding. #[no_mangle] diff --git a/lightning-c-bindings/src/lightning/routing/utxo.rs b/lightning-c-bindings/src/lightning/routing/utxo.rs new file mode 100644 index 0000000..c9ed695 --- /dev/null +++ b/lightning-c-bindings/src/lightning/routing/utxo.rs @@ -0,0 +1,358 @@ +// This file is Copyright its original authors, visible in version control +// history and in the source files from which this was generated. +// +// This file is licensed under the license available in the LICENSE or LICENSE.md +// file in the root of this repository or, if no such file exists, the same +// license as that which applies to the original source files from which this +// source was automatically generated. + +//! This module contains traits for LDK to access UTXOs to check gossip data is correct. +//! +//! When lightning nodes gossip channel information, they resist DoS attacks by checking that each +//! channel matches a UTXO on-chain, requiring at least some marginal on-chain transacting in +//! order to announce a channel. This module handles that checking. + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + +/// An error when accessing the chain via [`UtxoLookup`]. +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum UtxoLookupError { + /// The requested chain is unknown. + UnknownChain, + /// The requested transaction doesn't exist or hasn't confirmed. + UnknownTx, +} +use lightning::routing::utxo::UtxoLookupError as UtxoLookupErrorImport; +pub(crate) type nativeUtxoLookupError = UtxoLookupErrorImport; + +impl UtxoLookupError { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeUtxoLookupError { + match self { + UtxoLookupError::UnknownChain => nativeUtxoLookupError::UnknownChain, + UtxoLookupError::UnknownTx => nativeUtxoLookupError::UnknownTx, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeUtxoLookupError { + match self { + UtxoLookupError::UnknownChain => nativeUtxoLookupError::UnknownChain, + UtxoLookupError::UnknownTx => nativeUtxoLookupError::UnknownTx, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeUtxoLookupError) -> Self { + match native { + nativeUtxoLookupError::UnknownChain => UtxoLookupError::UnknownChain, + nativeUtxoLookupError::UnknownTx => UtxoLookupError::UnknownTx, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeUtxoLookupError) -> Self { + match native { + nativeUtxoLookupError::UnknownChain => UtxoLookupError::UnknownChain, + nativeUtxoLookupError::UnknownTx => UtxoLookupError::UnknownTx, + } + } +} +/// Creates a copy of the UtxoLookupError +#[no_mangle] +pub extern "C" fn UtxoLookupError_clone(orig: &UtxoLookupError) -> UtxoLookupError { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new UnknownChain-variant UtxoLookupError +pub extern "C" fn UtxoLookupError_unknown_chain() -> UtxoLookupError { + UtxoLookupError::UnknownChain} +#[no_mangle] +/// Utility method to constructs a new UnknownTx-variant UtxoLookupError +pub extern "C" fn UtxoLookupError_unknown_tx() -> UtxoLookupError { + UtxoLookupError::UnknownTx} +/// The result of a [`UtxoLookup::get_utxo`] call. A call may resolve either synchronously, +/// returning the `Sync` variant, or asynchronously, returning an [`UtxoFuture`] in the `Async` +/// variant. +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum UtxoResult { + /// A result which was resolved synchronously. It either includes a [`TxOut`] for the output + /// requested or a [`UtxoLookupError`]. + Sync( + crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ), + /// A result which will be resolved asynchronously. It includes a [`UtxoFuture`], a `clone` of + /// which you must keep locally and call [`UtxoFuture::resolve`] on once the lookup completes. + /// + /// Note that in order to avoid runaway memory usage, the number of parallel checks is limited, + /// but only fairly loosely. Because a pending checks block all message processing, leaving + /// checks pending for an extended time may cause DoS of other functions. It is recommended you + /// keep a tight timeout on lookups, on the order of a few seconds. + Async( + crate::lightning::routing::utxo::UtxoFuture), +} +use lightning::routing::utxo::UtxoResult as UtxoResultImport; +pub(crate) type nativeUtxoResult = UtxoResultImport; + +impl UtxoResult { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativeUtxoResult { + match self { + UtxoResult::Sync (ref a, ) => { + let mut a_nonref = Clone::clone(a); + let mut local_a_nonref = match a_nonref.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut a_nonref.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut a_nonref.contents.err)) }).into_native() })}; + nativeUtxoResult::Sync ( + local_a_nonref, + ) + }, + UtxoResult::Async (ref a, ) => { + let mut a_nonref = Clone::clone(a); + nativeUtxoResult::Async ( + *unsafe { Box::from_raw(a_nonref.take_inner()) }, + ) + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativeUtxoResult { + match self { + UtxoResult::Sync (mut a, ) => { + let mut local_a = match a.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut a.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut a.contents.err)) }).into_native() })}; + nativeUtxoResult::Sync ( + local_a, + ) + }, + UtxoResult::Async (mut a, ) => { + nativeUtxoResult::Async ( + *unsafe { Box::from_raw(a.take_inner()) }, + ) + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativeUtxoResult) -> Self { + match native { + nativeUtxoResult::Sync (ref a, ) => { + let mut a_nonref = Clone::clone(a); + let mut local_a_nonref = match a_nonref { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::TxOut::from_rust(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::routing::utxo::UtxoLookupError::native_into(e) }).into() }; + UtxoResult::Sync ( + local_a_nonref, + ) + }, + nativeUtxoResult::Async (ref a, ) => { + let mut a_nonref = Clone::clone(a); + UtxoResult::Async ( + crate::lightning::routing::utxo::UtxoFuture { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, + ) + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativeUtxoResult) -> Self { + match native { + nativeUtxoResult::Sync (mut a, ) => { + let mut local_a = match a { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::TxOut::from_rust(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::routing::utxo::UtxoLookupError::native_into(e) }).into() }; + UtxoResult::Sync ( + local_a, + ) + }, + nativeUtxoResult::Async (mut a, ) => { + UtxoResult::Async ( + crate::lightning::routing::utxo::UtxoFuture { inner: ObjOps::heap_alloc(a), is_owned: true }, + ) + }, + } + } +} +/// Frees any resources used by the UtxoResult +#[no_mangle] +pub extern "C" fn UtxoResult_free(this_ptr: UtxoResult) { } +/// Creates a copy of the UtxoResult +#[no_mangle] +pub extern "C" fn UtxoResult_clone(orig: &UtxoResult) -> UtxoResult { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new Sync-variant UtxoResult +pub extern "C" fn UtxoResult_sync(a: crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ) -> UtxoResult { + UtxoResult::Sync(a, ) +} +#[no_mangle] +/// Utility method to constructs a new Async-variant UtxoResult +pub extern "C" fn UtxoResult_async(a: crate::lightning::routing::utxo::UtxoFuture) -> UtxoResult { + UtxoResult::Async(a, ) +} +/// The `UtxoLookup` trait defines behavior for accessing on-chain UTXOs. +#[repr(C)] +pub struct UtxoLookup { + /// An opaque pointer which is passed to your function implementations as an argument. + /// This has no meaning in the LDK, and can be NULL or any other value. + pub this_arg: *mut c_void, + /// Returns the transaction output of a funding transaction encoded by [`short_channel_id`]. + /// Returns an error if `genesis_hash` is for a different chain or if such a transaction output + /// is unknown. + /// + /// [`short_channel_id`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#definition-of-short_channel_id + #[must_use] + pub get_utxo: extern "C" fn (this_arg: *const c_void, genesis_hash: *const [u8; 32], short_channel_id: u64) -> crate::lightning::routing::utxo::UtxoResult, + /// Frees any resources associated with this object given its this_arg pointer. + /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. + pub free: Option, +} +unsafe impl Send for UtxoLookup {} +unsafe impl Sync for UtxoLookup {} +#[no_mangle] +pub(crate) extern "C" fn UtxoLookup_clone_fields(orig: &UtxoLookup) -> UtxoLookup { + UtxoLookup { + this_arg: orig.this_arg, + get_utxo: Clone::clone(&orig.get_utxo), + free: Clone::clone(&orig.free), + } +} + +use lightning::routing::utxo::UtxoLookup as rustUtxoLookup; +impl rustUtxoLookup for UtxoLookup { + fn get_utxo(&self, mut genesis_hash: &bitcoin::BlockHash, mut short_channel_id: u64) -> lightning::routing::utxo::UtxoResult { + let mut ret = (self.get_utxo)(self.this_arg, genesis_hash.as_inner(), short_channel_id); + ret.into_native() + } +} + +// We're essentially a pointer already, or at least a set of pointers, so allow us to be used +// directly as a Deref trait in higher-level structs: +impl core::ops::Deref for UtxoLookup { + type Target = Self; + fn deref(&self) -> &Self { + self + } +} +/// Calls the free function if one is set +#[no_mangle] +pub extern "C" fn UtxoLookup_free(this_ptr: UtxoLookup) { } +impl Drop for UtxoLookup { + fn drop(&mut self) { + if let Some(f) = self.free { + f(self.this_arg); + } + } +} + +use lightning::routing::utxo::UtxoFuture as nativeUtxoFutureImport; +pub(crate) type nativeUtxoFuture = nativeUtxoFutureImport; + +/// Represents a future resolution of a [`UtxoLookup::get_utxo`] query resolving async. +/// +/// See [`UtxoResult::Async`] and [`UtxoFuture::resolve`] for more info. +#[must_use] +#[repr(C)] +pub struct UtxoFuture { + /// A pointer to the opaque Rust object. + + /// Nearly everywhere, inner must be non-null, however in places where + /// the Rust equivalent takes an Option, it may be set to null to indicate None. + pub inner: *mut nativeUtxoFuture, + /// Indicates that this is the only struct which contains the same pointer. + + /// Rust functions which take ownership of an object provided via an argument require + /// this to be true and invalidate the object pointed to by inner. + pub is_owned: bool, +} + +impl Drop for UtxoFuture { + fn drop(&mut self) { + if self.is_owned && !<*mut nativeUtxoFuture>::is_null(self.inner) { + let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; + } + } +} +/// Frees any resources used by the UtxoFuture, if is_owned is set and inner is non-NULL. +#[no_mangle] +pub extern "C" fn UtxoFuture_free(this_obj: UtxoFuture) { } +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn UtxoFuture_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeUtxoFuture) }; +} +#[allow(unused)] +impl UtxoFuture { + pub(crate) fn get_native_ref(&self) -> &'static nativeUtxoFuture { + unsafe { &*ObjOps::untweak_ptr(self.inner) } + } + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeUtxoFuture { + unsafe { &mut *ObjOps::untweak_ptr(self.inner) } + } + /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy + pub(crate) fn take_inner(mut self) -> *mut nativeUtxoFuture { + assert!(self.is_owned); + let ret = ObjOps::untweak_ptr(self.inner); + self.inner = core::ptr::null_mut(); + ret + } +} +impl Clone for UtxoFuture { + fn clone(&self) -> Self { + Self { + inner: if <*mut nativeUtxoFuture>::is_null(self.inner) { core::ptr::null_mut() } else { + ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, + is_owned: true, + } + } +} +#[allow(unused)] +/// Used only if an object of this type is returned as a trait impl by a method +pub(crate) extern "C" fn UtxoFuture_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeUtxoFuture)).clone() })) as *mut c_void +} +#[no_mangle] +/// Creates a copy of the UtxoFuture +pub extern "C" fn UtxoFuture_clone(orig: &UtxoFuture) -> UtxoFuture { + orig.clone() +} +/// Builds a new future for later resolution. +#[must_use] +#[no_mangle] +pub extern "C" fn UtxoFuture_new() -> crate::lightning::routing::utxo::UtxoFuture { + let mut ret = lightning::routing::utxo::UtxoFuture::new(); + crate::lightning::routing::utxo::UtxoFuture { inner: ObjOps::heap_alloc(ret), is_owned: true } +} + +/// Resolves this future against the given `graph` and with the given `result`. +/// +/// This is identical to calling [`UtxoFuture::resolve`] with a dummy `gossip`, disabling +/// forwarding the validated gossip message onwards to peers. +/// +/// Because this may cause the [`NetworkGraph`]'s [`processing_queue_high`] to flip, in order +/// to allow us to interact with peers again, you should call [`PeerManager::process_events`] +/// after this. +/// +/// [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high +/// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events +#[no_mangle] +pub extern "C" fn UtxoFuture_resolve_without_forwarding(this_arg: &crate::lightning::routing::utxo::UtxoFuture, graph: &crate::lightning::routing::gossip::NetworkGraph, mut result: crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ) { + let mut local_result = match result.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut result.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut result.contents.err)) }).into_native() })}; + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.resolve_without_forwarding(graph.get_native_ref(), local_result) +} + +/// Resolves this future against the given `graph` and with the given `result`. +/// +/// The given `gossip` is used to broadcast any validated messages onwards to all peers which +/// have available buffer space. +/// +/// Because this may cause the [`NetworkGraph`]'s [`processing_queue_high`] to flip, in order +/// to allow us to interact with peers again, you should call [`PeerManager::process_events`] +/// after this. +/// +/// [`processing_queue_high`]: crate::ln::msgs::RoutingMessageHandler::processing_queue_high +/// [`PeerManager::process_events`]: crate::ln::peer_handler::PeerManager::process_events +#[no_mangle] +pub extern "C" fn UtxoFuture_resolve(this_arg: &crate::lightning::routing::utxo::UtxoFuture, graph: &crate::lightning::routing::gossip::NetworkGraph, gossip: &crate::lightning::routing::gossip::P2PGossipSync, mut result: crate::c_types::derived::CResult_TxOutUtxoLookupErrorZ) { + let mut local_result = match result.result_ok { true => Ok( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut result.contents.result)) }).into_rust() }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut result.contents.err)) }).into_native() })}; + unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.resolve(graph.get_native_ref(), gossip.get_native_ref(), local_result) +} + diff --git a/lightning-c-bindings/src/lightning/util/config.rs b/lightning-c-bindings/src/lightning/util/config.rs index 6830ed0..1b93b9a 100644 --- a/lightning-c-bindings/src/lightning/util/config.rs +++ b/lightning-c-bindings/src/lightning/util/config.rs @@ -308,11 +308,11 @@ pub extern "C" fn ChannelHandshakeConfig_set_announced_channel(this_ptr: &mut Ch /// any attacker who is able to take control of a channel can just as easily send the funds via /// lightning payments, so we never require that our counterparties support this option. /// -/// The upfront key committed is provided from [`KeysInterface::get_shutdown_scriptpubkey`]. +/// The upfront key committed is provided from [`SignerProvider::get_shutdown_scriptpubkey`]. /// /// Default value: true. /// -/// [`KeysInterface::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::KeysInterface::get_shutdown_scriptpubkey +/// [`SignerProvider::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::SignerProvider::get_shutdown_scriptpubkey #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_get_commit_upfront_shutdown_pubkey(this_ptr: &ChannelHandshakeConfig) -> bool { let mut inner_val = &mut this_ptr.get_native_mut_ref().commit_upfront_shutdown_pubkey; @@ -326,11 +326,11 @@ pub extern "C" fn ChannelHandshakeConfig_get_commit_upfront_shutdown_pubkey(this /// any attacker who is able to take control of a channel can just as easily send the funds via /// lightning payments, so we never require that our counterparties support this option. /// -/// The upfront key committed is provided from [`KeysInterface::get_shutdown_scriptpubkey`]. +/// The upfront key committed is provided from [`SignerProvider::get_shutdown_scriptpubkey`]. /// /// Default value: true. /// -/// [`KeysInterface::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::KeysInterface::get_shutdown_scriptpubkey +/// [`SignerProvider::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::SignerProvider::get_shutdown_scriptpubkey #[no_mangle] pub extern "C" fn ChannelHandshakeConfig_set_commit_upfront_shutdown_pubkey(this_ptr: &mut ChannelHandshakeConfig, mut val: bool) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.commit_upfront_shutdown_pubkey = val; @@ -436,7 +436,7 @@ pub(crate) type nativeChannelHandshakeLimits = nativeChannelHandshakeLimitsImpor /// /// These limits are only applied to our counterparty's limits, not our own. /// -/// Use 0/::max_value() as appropriate to skip checking. +/// Use 0/`::max_value()` as appropriate to skip checking. /// /// Provides sane defaults for most configurations. /// diff --git a/lightning-c-bindings/src/lightning/util/errors.rs b/lightning-c-bindings/src/lightning/util/errors.rs index 91ce973..ff0f416 100644 --- a/lightning-c-bindings/src/lightning/util/errors.rs +++ b/lightning-c-bindings/src/lightning/util/errors.rs @@ -59,13 +59,13 @@ pub enum APIError { /// [`chain::Watch::update_channel`]: crate::chain::Watch::update_channel /// [`ChannelMonitorUpdateStatus::InProgress`]: crate::chain::ChannelMonitorUpdateStatus::InProgress MonitorUpdateInProgress, - /// [`KeysInterface::get_shutdown_scriptpubkey`] returned a shutdown scriptpubkey incompatible + /// [`SignerProvider::get_shutdown_scriptpubkey`] returned a shutdown scriptpubkey incompatible /// with the channel counterparty as negotiated in [`InitFeatures`]. /// /// Using a SegWit v0 script should resolve this issue. If you cannot, you won't be able to open /// a channel or cooperatively close one with this peer (and will have to force-close instead). /// - /// [`KeysInterface::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::KeysInterface::get_shutdown_scriptpubkey + /// [`SignerProvider::get_shutdown_scriptpubkey`]: crate::chain::keysinterface::SignerProvider::get_shutdown_scriptpubkey /// [`InitFeatures`]: crate::ln::features::InitFeatures IncompatibleShutdownScript { /// The incompatible shutdown script. @@ -96,7 +96,7 @@ impl APIError { APIError::InvalidRoute {ref err, } => { let mut err_nonref = Clone::clone(err); nativeAPIError::InvalidRoute { - err: err_nonref.into_str(), + err: err_nonref.into_string(), } }, APIError::ChannelUnavailable {ref err, } => { @@ -130,7 +130,7 @@ impl APIError { }, APIError::InvalidRoute {mut err, } => { nativeAPIError::InvalidRoute { - err: err.into_str(), + err: err.into_string(), } }, APIError::ChannelUnavailable {mut err, } => { @@ -271,3 +271,15 @@ pub extern "C" fn APIError_incompatible_shutdown_script(script: crate::lightning pub extern "C" fn APIError_eq(a: &APIError, b: &APIError) -> bool { if &a.to_native() == &b.to_native() { true } else { false } } +#[no_mangle] +/// Serialize the APIError object into a byte array which can be read by APIError_read +pub extern "C" fn APIError_write(obj: &crate::lightning::util::errors::APIError) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(&unsafe { &*obj }.to_native()) +} +#[no_mangle] +/// Read a APIError from a byte array, created by APIError_write +pub extern "C" fn APIError_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_COption_APIErrorZDecodeErrorZ { + let res: Result, lightning::ln::msgs::DecodeError> = crate::c_types::maybe_deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_res_0 = if o.is_none() { crate::c_types::derived::COption_APIErrorZ::None } else { crate::c_types::derived::COption_APIErrorZ::Some( { crate::lightning::util::errors::APIError::native_into(o.unwrap()) }) }; local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} diff --git a/lightning-c-bindings/src/lightning/util/events.rs b/lightning-c-bindings/src/lightning/util/events.rs index 07db22c..2d280f1 100644 --- a/lightning-c-bindings/src/lightning/util/events.rs +++ b/lightning-c-bindings/src/lightning/util/events.rs @@ -155,6 +155,12 @@ pub extern "C" fn PaymentPurpose_invoice_payment(payment_preimage: crate::c_type pub extern "C" fn PaymentPurpose_spontaneous_payment(a: crate::c_types::ThirtyTwoBytes) -> PaymentPurpose { PaymentPurpose::SpontaneousPayment(a, ) } +/// Checks if two PaymentPurposes contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +#[no_mangle] +pub extern "C" fn PaymentPurpose_eq(a: &PaymentPurpose, b: &PaymentPurpose) -> bool { + if &a.to_native() == &b.to_native() { true } else { false } +} #[no_mangle] /// Serialize the PaymentPurpose object into a byte array which can be read by PaymentPurpose_read pub extern "C" fn PaymentPurpose_write(obj: &crate::lightning::util::events::PaymentPurpose) -> crate::c_types::derived::CVec_u8Z { @@ -167,6 +173,144 @@ pub extern "C" fn PaymentPurpose_read(ser: crate::c_types::u8slice) -> crate::c_ let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::util::events::PaymentPurpose::native_into(o) }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; local_res } +/// When the payment path failure took place and extra details about it. [`PathFailure::OnPath`] may +/// contain a [`NetworkUpdate`] that needs to be applied to the [`NetworkGraph`]. +/// +/// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate +/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph +#[derive(Clone)] +#[must_use] +#[repr(C)] +pub enum PathFailure { + /// We failed to initially send the payment and no HTLC was committed to. Contains the relevant + /// error. + InitialSend { + /// The error surfaced from initial send. + err: crate::lightning::util::errors::APIError, + }, + /// A hop on the path failed to forward our payment. + OnPath { + /// If present, this [`NetworkUpdate`] should be applied to the [`NetworkGraph`] so that routing + /// decisions can take into account the update. + /// + /// [`NetworkUpdate`]: crate::routing::gossip::NetworkUpdate + /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph + network_update: crate::c_types::derived::COption_NetworkUpdateZ, + }, +} +use lightning::util::events::PathFailure as PathFailureImport; +pub(crate) type nativePathFailure = PathFailureImport; + +impl PathFailure { + #[allow(unused)] + pub(crate) fn to_native(&self) -> nativePathFailure { + match self { + PathFailure::InitialSend {ref err, } => { + let mut err_nonref = Clone::clone(err); + nativePathFailure::InitialSend { + err: err_nonref.into_native(), + } + }, + PathFailure::OnPath {ref network_update, } => { + let mut network_update_nonref = Clone::clone(network_update); + let mut local_network_update_nonref = { /* network_update_nonref*/ let network_update_nonref_opt = network_update_nonref; { } if network_update_nonref_opt.is_none() { None } else { Some({ network_update_nonref_opt.take().into_native() }) } }; + nativePathFailure::OnPath { + network_update: local_network_update_nonref, + } + }, + } + } + #[allow(unused)] + pub(crate) fn into_native(self) -> nativePathFailure { + match self { + PathFailure::InitialSend {mut err, } => { + nativePathFailure::InitialSend { + err: err.into_native(), + } + }, + PathFailure::OnPath {mut network_update, } => { + let mut local_network_update = { /* network_update*/ let network_update_opt = network_update; { } if network_update_opt.is_none() { None } else { Some({ network_update_opt.take().into_native() }) } }; + nativePathFailure::OnPath { + network_update: local_network_update, + } + }, + } + } + #[allow(unused)] + pub(crate) fn from_native(native: &nativePathFailure) -> Self { + match native { + nativePathFailure::InitialSend {ref err, } => { + let mut err_nonref = Clone::clone(err); + PathFailure::InitialSend { + err: crate::lightning::util::errors::APIError::native_into(err_nonref), + } + }, + nativePathFailure::OnPath {ref network_update, } => { + let mut network_update_nonref = Clone::clone(network_update); + let mut local_network_update_nonref = if network_update_nonref.is_none() { crate::c_types::derived::COption_NetworkUpdateZ::None } else { crate::c_types::derived::COption_NetworkUpdateZ::Some( { crate::lightning::routing::gossip::NetworkUpdate::native_into(network_update_nonref.unwrap()) }) }; + PathFailure::OnPath { + network_update: local_network_update_nonref, + } + }, + } + } + #[allow(unused)] + pub(crate) fn native_into(native: nativePathFailure) -> Self { + match native { + nativePathFailure::InitialSend {mut err, } => { + PathFailure::InitialSend { + err: crate::lightning::util::errors::APIError::native_into(err), + } + }, + nativePathFailure::OnPath {mut network_update, } => { + let mut local_network_update = if network_update.is_none() { crate::c_types::derived::COption_NetworkUpdateZ::None } else { crate::c_types::derived::COption_NetworkUpdateZ::Some( { crate::lightning::routing::gossip::NetworkUpdate::native_into(network_update.unwrap()) }) }; + PathFailure::OnPath { + network_update: local_network_update, + } + }, + } + } +} +/// Frees any resources used by the PathFailure +#[no_mangle] +pub extern "C" fn PathFailure_free(this_ptr: PathFailure) { } +/// Creates a copy of the PathFailure +#[no_mangle] +pub extern "C" fn PathFailure_clone(orig: &PathFailure) -> PathFailure { + orig.clone() +} +#[no_mangle] +/// Utility method to constructs a new InitialSend-variant PathFailure +pub extern "C" fn PathFailure_initial_send(err: crate::lightning::util::errors::APIError) -> PathFailure { + PathFailure::InitialSend { + err, + } +} +#[no_mangle] +/// Utility method to constructs a new OnPath-variant PathFailure +pub extern "C" fn PathFailure_on_path(network_update: crate::c_types::derived::COption_NetworkUpdateZ) -> PathFailure { + PathFailure::OnPath { + network_update, + } +} +/// Checks if two PathFailures contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +#[no_mangle] +pub extern "C" fn PathFailure_eq(a: &PathFailure, b: &PathFailure) -> bool { + if &a.to_native() == &b.to_native() { true } else { false } +} +#[no_mangle] +/// Serialize the PathFailure object into a byte array which can be read by PathFailure_read +pub extern "C" fn PathFailure_write(obj: &crate::lightning::util::events::PathFailure) -> crate::c_types::derived::CVec_u8Z { + crate::c_types::serialize_obj(&unsafe { &*obj }.to_native()) +} +#[no_mangle] +/// Read a PathFailure from a byte array, created by PathFailure_write +pub extern "C" fn PathFailure_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_COption_PathFailureZDecodeErrorZ { + let res: Result, lightning::ln::msgs::DecodeError> = crate::c_types::maybe_deserialize_obj(ser); + let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_res_0 = if o.is_none() { crate::c_types::derived::COption_PathFailureZ::None } else { crate::c_types::derived::COption_PathFailureZ::Some( { crate::lightning::util::events::PathFailure::native_into(o.unwrap()) }) }; local_res_0 }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() }; + local_res +} /// The reason the channel was closed. See individual variants more details. #[derive(Clone)] #[must_use] @@ -638,10 +782,10 @@ pub enum Event { /// [`ChannelManager::claim_funds`] with the preimage given in [`PaymentPurpose`]. /// /// Note that if the preimage is not known, you should call - /// [`ChannelManager::fail_htlc_backwards`] to free up resources for this HTLC and avoid - /// network congestion. - /// If you fail to call either [`ChannelManager::claim_funds`] or - /// [`ChannelManager::fail_htlc_backwards`] within the HTLC's timeout, the HTLC will be + /// [`ChannelManager::fail_htlc_backwards`] or [`ChannelManager::fail_htlc_backwards_with_reason`] + /// to free up resources for this HTLC and avoid network congestion. + /// If you fail to call either [`ChannelManager::claim_funds`], [`ChannelManager::fail_htlc_backwards`], + /// or [`ChannelManager::fail_htlc_backwards_with_reason`] within the HTLC's timeout, the HTLC will be /// automatically failed. /// /// # Note @@ -653,6 +797,7 @@ pub enum Event { /// /// [`ChannelManager::claim_funds`]: crate::ln::channelmanager::ChannelManager::claim_funds /// [`ChannelManager::fail_htlc_backwards`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards + /// [`ChannelManager::fail_htlc_backwards_with_reason`]: crate::ln::channelmanager::ChannelManager::fail_htlc_backwards_with_reason PaymentClaimable { /// The node that will receive the payment after it has been claimed. /// This is useful to identify payments received via [phantom nodes]. @@ -717,11 +862,9 @@ pub enum Event { /// Note for MPP payments: in rare cases, this event may be preceded by a `PaymentPathFailed` /// event. In this situation, you SHOULD treat this payment as having succeeded. PaymentSent { - /// The id returned by [`ChannelManager::send_payment`] and used with - /// [`ChannelManager::retry_payment`]. + /// The id returned by [`ChannelManager::send_payment`]. /// /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment - /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment /// /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None payment_id: crate::c_types::ThirtyTwoBytes, @@ -745,19 +888,19 @@ pub enum Event { fee_paid_msat: crate::c_types::derived::COption_u64Z, }, /// Indicates an outbound payment failed. Individual [`Event::PaymentPathFailed`] events - /// provide failure information for each MPP part in the payment. + /// provide failure information for each path attempt in the payment, including retries. /// /// This event is provided once there are no further pending HTLCs for the payment and the - /// payment is no longer retryable due to [`ChannelManager::abandon_payment`] having been - /// called for the corresponding payment. + /// payment is no longer retryable, due either to the [`Retry`] provided or + /// [`ChannelManager::abandon_payment`] having been called for the corresponding payment. /// + /// [`Retry`]: crate::ln::channelmanager::Retry /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment PaymentFailed { /// The id returned by [`ChannelManager::send_payment`] and used with - /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`]. + /// [`ChannelManager::abandon_payment`]. /// /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment - /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment payment_id: crate::c_types::ThirtyTwoBytes, /// The hash that was given to [`ChannelManager::send_payment`]. @@ -770,11 +913,9 @@ pub enum Event { /// Always generated after [`Event::PaymentSent`] and thus useful for scoring channels. See /// [`Event::PaymentSent`] for obtaining the payment preimage. PaymentPathSuccessful { - /// The id returned by [`ChannelManager::send_payment`] and used with - /// [`ChannelManager::retry_payment`]. + /// The id returned by [`ChannelManager::send_payment`]. /// /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment - /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment payment_id: crate::c_types::ThirtyTwoBytes, /// The hash that was given to [`ChannelManager::send_payment`]. /// @@ -787,24 +928,21 @@ pub enum Event { /// May contain a closed channel if the HTLC sent along the path was fulfilled on chain. path: crate::c_types::derived::CVec_RouteHopZ, }, - /// Indicates an outbound HTLC we sent failed. Probably some intermediary node dropped - /// something. You may wish to retry with a different route. - /// - /// If you have given up retrying this payment and wish to fail it, you MUST call - /// [`ChannelManager::abandon_payment`] at least once for a given [`PaymentId`] or memory - /// related to payment tracking will leak. + /// Indicates an outbound HTLC we sent failed, likely due to an intermediary node being unable to + /// handle the HTLC. /// /// Note that this does *not* indicate that all paths for an MPP payment have failed, see - /// [`Event::PaymentFailed`] and [`all_paths_failed`]. + /// [`Event::PaymentFailed`]. + /// + /// See [`ChannelManager::abandon_payment`] for giving up on this payment before its retries have + /// been exhausted. /// /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment - /// [`all_paths_failed`]: Self::PaymentPathFailed::all_paths_failed PaymentPathFailed { /// The id returned by [`ChannelManager::send_payment`] and used with - /// [`ChannelManager::retry_payment`] and [`ChannelManager::abandon_payment`]. + /// [`ChannelManager::abandon_payment`]. /// /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment - /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment /// /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None @@ -814,35 +952,14 @@ pub enum Event { /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment payment_hash: crate::c_types::ThirtyTwoBytes, /// Indicates the payment was rejected for some reason by the recipient. This implies that - /// the payment has failed, not just the route in question. If this is not set, you may - /// retry the payment via a different route. + /// the payment has failed, not just the route in question. If this is not set, the payment may + /// be retried via a different route. payment_failed_permanently: bool, - /// Any failure information conveyed via the Onion return packet by a node along the failed - /// payment route. - /// - /// Should be applied to the [`NetworkGraph`] so that routing decisions can take into - /// account the update. + /// Extra error details based on the failure type. May contain an update that needs to be + /// applied to the [`NetworkGraph`]. /// /// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph - network_update: crate::c_types::derived::COption_NetworkUpdateZ, - /// For both single-path and multi-path payments, this is set if all paths of the payment have - /// failed. This will be set to false if (1) this is an MPP payment and (2) other parts of the - /// larger MPP payment were still in flight when this event was generated. - /// - /// Note that if you are retrying individual MPP parts, using this value to determine if a - /// payment has fully failed is race-y. Because multiple failures can happen prior to events - /// being processed, you may retry in response to a first failure, with a second failure - /// (with `all_paths_failed` set) still pending. Then, when the second failure is processed - /// you will see `all_paths_failed` set even though the retry of the first failure still - /// has an associated in-flight HTLC. See (1) for an example of such a failure. - /// - /// If you wish to retry individual MPP parts and learn when a payment has failed, you must - /// call [`ChannelManager::abandon_payment`] and wait for a [`Event::PaymentFailed`] event. - /// - /// (1) - /// - /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment - all_paths_failed: bool, + failure: crate::lightning::util::events::PathFailure, /// The payment path that failed. path: crate::c_types::derived::CVec_RouteHopZ, /// The channel responsible for the failed payment path. @@ -854,12 +971,9 @@ pub enum Event { /// If this is `Some`, then the corresponding channel should be avoided when the payment is /// retried. May be `None` for older [`Event`] serializations. short_channel_id: crate::c_types::derived::COption_u64Z, - /// Parameters needed to compute a new [`Route`] when retrying the failed payment path. - /// - /// See [`find_route`] for details. + /// Parameters used by LDK to compute a new [`Route`] when retrying the failed payment path. /// /// [`Route`]: crate::routing::router::Route - /// [`find_route`]: crate::routing::router::find_route /// /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None retry: crate::lightning::routing::router::RouteParameters, @@ -1186,14 +1300,12 @@ impl Event { path: local_path_nonref, } }, - Event::PaymentPathFailed {ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref path, ref short_channel_id, ref retry, } => { + Event::PaymentPathFailed {ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure, ref path, ref short_channel_id, ref retry, } => { let mut payment_id_nonref = Clone::clone(payment_id); let mut local_payment_id_nonref = if payment_id_nonref.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentId(payment_id_nonref.data) }) }; let mut payment_hash_nonref = Clone::clone(payment_hash); let mut payment_failed_permanently_nonref = Clone::clone(payment_failed_permanently); - let mut network_update_nonref = Clone::clone(network_update); - let mut local_network_update_nonref = { /* network_update_nonref*/ let network_update_nonref_opt = network_update_nonref; { } if network_update_nonref_opt.is_none() { None } else { Some({ network_update_nonref_opt.take().into_native() }) } }; - let mut all_paths_failed_nonref = Clone::clone(all_paths_failed); + let mut failure_nonref = Clone::clone(failure); let mut path_nonref = Clone::clone(path); let mut local_path_nonref = Vec::new(); for mut item in path_nonref.into_rust().drain(..) { local_path_nonref.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; let mut short_channel_id_nonref = Clone::clone(short_channel_id); @@ -1204,8 +1316,7 @@ impl Event { payment_id: local_payment_id_nonref, payment_hash: ::lightning::ln::PaymentHash(payment_hash_nonref.data), payment_failed_permanently: payment_failed_permanently_nonref, - network_update: local_network_update_nonref, - all_paths_failed: all_paths_failed_nonref, + failure: failure_nonref.into_native(), path: local_path_nonref, short_channel_id: local_short_channel_id_nonref, retry: local_retry_nonref, @@ -1391,9 +1502,8 @@ impl Event { path: local_path, } }, - Event::PaymentPathFailed {mut payment_id, mut payment_hash, mut payment_failed_permanently, mut network_update, mut all_paths_failed, mut path, mut short_channel_id, mut retry, } => { + Event::PaymentPathFailed {mut payment_id, mut payment_hash, mut payment_failed_permanently, mut failure, mut path, mut short_channel_id, mut retry, } => { let mut local_payment_id = if payment_id.data == [0; 32] { None } else { Some( { ::lightning::ln::channelmanager::PaymentId(payment_id.data) }) }; - let mut local_network_update = { /* network_update*/ let network_update_opt = network_update; { } if network_update_opt.is_none() { None } else { Some({ network_update_opt.take().into_native() }) } }; let mut local_path = Vec::new(); for mut item in path.into_rust().drain(..) { local_path.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; let mut local_short_channel_id = if short_channel_id.is_some() { Some( { short_channel_id.take() }) } else { None }; let mut local_retry = if retry.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(retry.take_inner()) } }) }; @@ -1401,8 +1511,7 @@ impl Event { payment_id: local_payment_id, payment_hash: ::lightning::ln::PaymentHash(payment_hash.data), payment_failed_permanently: payment_failed_permanently, - network_update: local_network_update, - all_paths_failed: all_paths_failed, + failure: failure.into_native(), path: local_path, short_channel_id: local_short_channel_id, retry: local_retry, @@ -1578,14 +1687,12 @@ impl Event { path: local_path_nonref.into(), } }, - nativeEvent::PaymentPathFailed {ref payment_id, ref payment_hash, ref payment_failed_permanently, ref network_update, ref all_paths_failed, ref path, ref short_channel_id, ref retry, } => { + nativeEvent::PaymentPathFailed {ref payment_id, ref payment_hash, ref payment_failed_permanently, ref failure, ref path, ref short_channel_id, ref retry, } => { let mut payment_id_nonref = Clone::clone(payment_id); let mut local_payment_id_nonref = if payment_id_nonref.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (payment_id_nonref.unwrap()).0 } } }; let mut payment_hash_nonref = Clone::clone(payment_hash); let mut payment_failed_permanently_nonref = Clone::clone(payment_failed_permanently); - let mut network_update_nonref = Clone::clone(network_update); - let mut local_network_update_nonref = if network_update_nonref.is_none() { crate::c_types::derived::COption_NetworkUpdateZ::None } else { crate::c_types::derived::COption_NetworkUpdateZ::Some( { crate::lightning::routing::gossip::NetworkUpdate::native_into(network_update_nonref.unwrap()) }) }; - let mut all_paths_failed_nonref = Clone::clone(all_paths_failed); + let mut failure_nonref = Clone::clone(failure); let mut path_nonref = Clone::clone(path); let mut local_path_nonref = Vec::new(); for mut item in path_nonref.drain(..) { local_path_nonref.push( { crate::lightning::routing::router::RouteHop { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; let mut short_channel_id_nonref = Clone::clone(short_channel_id); @@ -1596,8 +1703,7 @@ impl Event { payment_id: local_payment_id_nonref, payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash_nonref.0 }, payment_failed_permanently: payment_failed_permanently_nonref, - network_update: local_network_update_nonref, - all_paths_failed: all_paths_failed_nonref, + failure: crate::lightning::util::events::PathFailure::native_into(failure_nonref), path: local_path_nonref.into(), short_channel_id: local_short_channel_id_nonref, retry: local_retry_nonref, @@ -1783,9 +1889,8 @@ impl Event { path: local_path.into(), } }, - nativeEvent::PaymentPathFailed {mut payment_id, mut payment_hash, mut payment_failed_permanently, mut network_update, mut all_paths_failed, mut path, mut short_channel_id, mut retry, } => { + nativeEvent::PaymentPathFailed {mut payment_id, mut payment_hash, mut payment_failed_permanently, mut failure, mut path, mut short_channel_id, mut retry, } => { let mut local_payment_id = if payment_id.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (payment_id.unwrap()).0 } } }; - let mut local_network_update = if network_update.is_none() { crate::c_types::derived::COption_NetworkUpdateZ::None } else { crate::c_types::derived::COption_NetworkUpdateZ::Some( { crate::lightning::routing::gossip::NetworkUpdate::native_into(network_update.unwrap()) }) }; let mut local_path = Vec::new(); for mut item in path.drain(..) { local_path.push( { crate::lightning::routing::router::RouteHop { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; let mut local_short_channel_id = if short_channel_id.is_none() { crate::c_types::derived::COption_u64Z::None } else { crate::c_types::derived::COption_u64Z::Some( { short_channel_id.unwrap() }) }; let mut local_retry = crate::lightning::routing::router::RouteParameters { inner: if retry.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((retry.unwrap())) } }, is_owned: true }; @@ -1793,8 +1898,7 @@ impl Event { payment_id: local_payment_id, payment_hash: crate::c_types::ThirtyTwoBytes { data: payment_hash.0 }, payment_failed_permanently: payment_failed_permanently, - network_update: local_network_update, - all_paths_failed: all_paths_failed, + failure: crate::lightning::util::events::PathFailure::native_into(failure), path: local_path.into(), short_channel_id: local_short_channel_id, retry: local_retry, @@ -1958,13 +2062,12 @@ pub extern "C" fn Event_payment_path_successful(payment_id: crate::c_types::Thir } #[no_mangle] /// Utility method to constructs a new PaymentPathFailed-variant Event -pub extern "C" fn Event_payment_path_failed(payment_id: crate::c_types::ThirtyTwoBytes, payment_hash: crate::c_types::ThirtyTwoBytes, payment_failed_permanently: bool, network_update: crate::c_types::derived::COption_NetworkUpdateZ, all_paths_failed: bool, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: crate::c_types::derived::COption_u64Z, retry: crate::lightning::routing::router::RouteParameters) -> Event { +pub extern "C" fn Event_payment_path_failed(payment_id: crate::c_types::ThirtyTwoBytes, payment_hash: crate::c_types::ThirtyTwoBytes, payment_failed_permanently: bool, failure: crate::lightning::util::events::PathFailure, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: crate::c_types::derived::COption_u64Z, retry: crate::lightning::routing::router::RouteParameters) -> Event { Event::PaymentPathFailed { payment_id, payment_hash, payment_failed_permanently, - network_update, - all_paths_failed, + failure, path, short_channel_id, retry, @@ -2070,6 +2173,12 @@ pub extern "C" fn Event_htlchandling_failed(prev_channel_id: crate::c_types::Thi failed_next_destination, } } +/// Checks if two Events contain equal inner contents. +/// This ignores pointers and is_owned flags and looks at the values in fields. +#[no_mangle] +pub extern "C" fn Event_eq(a: &Event, b: &Event) -> bool { + if &a.to_native() == &b.to_native() { true } else { false } +} #[no_mangle] /// Serialize the Event object into a byte array which can be read by Event_read pub extern "C" fn Event_write(obj: &crate::lightning::util::events::Event) -> crate::c_types::derived::CVec_u8Z { @@ -2193,6 +2302,8 @@ pub enum MessageSendEvent { /// The channel_announcement which should be sent. msg: crate::lightning::ln::msgs::ChannelAnnouncement, /// The followup channel_update which should be sent. + /// + /// Note that this (or a relevant inner pointer) may be NULL or all-0s to represent None update_msg: crate::lightning::ln::msgs::ChannelUpdate, }, /// Used to indicate that a channel_update should be broadcast to all peers. @@ -2200,6 +2311,11 @@ pub enum MessageSendEvent { /// The channel_update which should be sent. msg: crate::lightning::ln::msgs::ChannelUpdate, }, + /// Used to indicate that a node_announcement should be broadcast to all peers. + BroadcastNodeAnnouncement { + /// The node_announcement which should be sent. + msg: crate::lightning::ln::msgs::NodeAnnouncement, + }, /// Used to indicate that a channel_update should be sent to a single peer. /// In contrast to [`Self::BroadcastChannelUpdate`], this is used when the channel is a /// private channel and we shouldn't be informing all of our peers of channel parameters. @@ -2356,9 +2472,10 @@ impl MessageSendEvent { MessageSendEvent::BroadcastChannelAnnouncement {ref msg, ref update_msg, } => { let mut msg_nonref = Clone::clone(msg); let mut update_msg_nonref = Clone::clone(update_msg); + let mut local_update_msg_nonref = if update_msg_nonref.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(update_msg_nonref.take_inner()) } }) }; nativeMessageSendEvent::BroadcastChannelAnnouncement { msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) }, - update_msg: *unsafe { Box::from_raw(update_msg_nonref.take_inner()) }, + update_msg: local_update_msg_nonref, } }, MessageSendEvent::BroadcastChannelUpdate {ref msg, } => { @@ -2367,6 +2484,12 @@ impl MessageSendEvent { msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) }, } }, + MessageSendEvent::BroadcastNodeAnnouncement {ref msg, } => { + let mut msg_nonref = Clone::clone(msg); + nativeMessageSendEvent::BroadcastNodeAnnouncement { + msg: *unsafe { Box::from_raw(msg_nonref.take_inner()) }, + } + }, MessageSendEvent::SendChannelUpdate {ref node_id, ref msg, } => { let mut node_id_nonref = Clone::clone(node_id); let mut msg_nonref = Clone::clone(msg); @@ -2494,9 +2617,10 @@ impl MessageSendEvent { } }, MessageSendEvent::BroadcastChannelAnnouncement {mut msg, mut update_msg, } => { + let mut local_update_msg = if update_msg.inner.is_null() { None } else { Some( { *unsafe { Box::from_raw(update_msg.take_inner()) } }) }; nativeMessageSendEvent::BroadcastChannelAnnouncement { msg: *unsafe { Box::from_raw(msg.take_inner()) }, - update_msg: *unsafe { Box::from_raw(update_msg.take_inner()) }, + update_msg: local_update_msg, } }, MessageSendEvent::BroadcastChannelUpdate {mut msg, } => { @@ -2504,6 +2628,11 @@ impl MessageSendEvent { msg: *unsafe { Box::from_raw(msg.take_inner()) }, } }, + MessageSendEvent::BroadcastNodeAnnouncement {mut msg, } => { + nativeMessageSendEvent::BroadcastNodeAnnouncement { + msg: *unsafe { Box::from_raw(msg.take_inner()) }, + } + }, MessageSendEvent::SendChannelUpdate {mut node_id, mut msg, } => { nativeMessageSendEvent::SendChannelUpdate { node_id: node_id.into_rust(), @@ -2646,9 +2775,10 @@ impl MessageSendEvent { nativeMessageSendEvent::BroadcastChannelAnnouncement {ref msg, ref update_msg, } => { let mut msg_nonref = Clone::clone(msg); let mut update_msg_nonref = Clone::clone(update_msg); + let mut local_update_msg_nonref = crate::lightning::ln::msgs::ChannelUpdate { inner: if update_msg_nonref.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((update_msg_nonref.unwrap())) } }, is_owned: true }; MessageSendEvent::BroadcastChannelAnnouncement { msg: crate::lightning::ln::msgs::ChannelAnnouncement { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, - update_msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(update_msg_nonref), is_owned: true }, + update_msg: local_update_msg_nonref, } }, nativeMessageSendEvent::BroadcastChannelUpdate {ref msg, } => { @@ -2657,6 +2787,12 @@ impl MessageSendEvent { msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, } }, + nativeMessageSendEvent::BroadcastNodeAnnouncement {ref msg, } => { + let mut msg_nonref = Clone::clone(msg); + MessageSendEvent::BroadcastNodeAnnouncement { + msg: crate::lightning::ln::msgs::NodeAnnouncement { inner: ObjOps::heap_alloc(msg_nonref), is_owned: true }, + } + }, nativeMessageSendEvent::SendChannelUpdate {ref node_id, ref msg, } => { let mut node_id_nonref = Clone::clone(node_id); let mut msg_nonref = Clone::clone(msg); @@ -2784,9 +2920,10 @@ impl MessageSendEvent { } }, nativeMessageSendEvent::BroadcastChannelAnnouncement {mut msg, mut update_msg, } => { + let mut local_update_msg = crate::lightning::ln::msgs::ChannelUpdate { inner: if update_msg.is_none() { core::ptr::null_mut() } else { { ObjOps::heap_alloc((update_msg.unwrap())) } }, is_owned: true }; MessageSendEvent::BroadcastChannelAnnouncement { msg: crate::lightning::ln::msgs::ChannelAnnouncement { inner: ObjOps::heap_alloc(msg), is_owned: true }, - update_msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(update_msg), is_owned: true }, + update_msg: local_update_msg, } }, nativeMessageSendEvent::BroadcastChannelUpdate {mut msg, } => { @@ -2794,6 +2931,11 @@ impl MessageSendEvent { msg: crate::lightning::ln::msgs::ChannelUpdate { inner: ObjOps::heap_alloc(msg), is_owned: true }, } }, + nativeMessageSendEvent::BroadcastNodeAnnouncement {mut msg, } => { + MessageSendEvent::BroadcastNodeAnnouncement { + msg: crate::lightning::ln::msgs::NodeAnnouncement { inner: ObjOps::heap_alloc(msg), is_owned: true }, + } + }, nativeMessageSendEvent::SendChannelUpdate {mut node_id, mut msg, } => { MessageSendEvent::SendChannelUpdate { node_id: crate::c_types::PublicKey::from_rust(&node_id), @@ -2954,6 +3096,13 @@ pub extern "C" fn MessageSendEvent_broadcast_channel_update(msg: crate::lightnin } } #[no_mangle] +/// Utility method to constructs a new BroadcastNodeAnnouncement-variant MessageSendEvent +pub extern "C" fn MessageSendEvent_broadcast_node_announcement(msg: crate::lightning::ln::msgs::NodeAnnouncement) -> MessageSendEvent { + MessageSendEvent::BroadcastNodeAnnouncement { + msg, + } +} +#[no_mangle] /// Utility method to constructs a new SendChannelUpdate-variant MessageSendEvent pub extern "C" fn MessageSendEvent_send_channel_update(node_id: crate::c_types::PublicKey, msg: crate::lightning::ln::msgs::ChannelUpdate) -> MessageSendEvent { MessageSendEvent::SendChannelUpdate { diff --git a/lightning-c-bindings/src/lightning/util/indexed_map.rs b/lightning-c-bindings/src/lightning/util/indexed_map.rs new file mode 100644 index 0000000..06fc03a --- /dev/null +++ b/lightning-c-bindings/src/lightning/util/indexed_map.rs @@ -0,0 +1,18 @@ +// This file is Copyright its original authors, visible in version control +// history and in the source files from which this was generated. +// +// This file is licensed under the license available in the LICENSE or LICENSE.md +// file in the root of this repository or, if no such file exists, the same +// license as that which applies to the original source files from which this +// source was automatically generated. + +//! This module has a map which can be iterated in a deterministic order. See the [`IndexedMap`]. + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + diff --git a/lightning-c-bindings/src/lightning/util/mod.rs b/lightning-c-bindings/src/lightning/util/mod.rs index 9e081cb..7318fb1 100644 --- a/lightning-c-bindings/src/lightning/util/mod.rs +++ b/lightning-c-bindings/src/lightning/util/mod.rs @@ -16,6 +16,7 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; +pub mod ser_macros; pub mod events; pub mod errors; pub mod ser; @@ -24,6 +25,7 @@ pub mod invoice; pub mod persist; pub mod string; pub mod wakers; +pub mod indexed_map; pub mod logger; pub mod config; mod fuzz_wrappers { @@ -36,17 +38,6 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; -} -mod ser_macros { - -use alloc::str::FromStr; -use core::ffi::c_void; -use core::convert::Infallible; -use bitcoin::hashes::Hash; -use crate::c_types::*; -#[cfg(feature="no-std")] -use alloc::{vec::Vec, boxed::Box}; - } mod atomic_counter { @@ -91,17 +82,6 @@ use crate::c_types::*; use alloc::{vec::Vec, boxed::Box}; } -} -mod fairrwlock { - -use alloc::str::FromStr; -use core::ffi::c_void; -use core::convert::Infallible; -use bitcoin::hashes::Hash; -use crate::c_types::*; -#[cfg(feature="no-std")] -use alloc::{vec::Vec, boxed::Box}; - } mod zbase32 { diff --git a/lightning-c-bindings/src/lightning/util/persist.rs b/lightning-c-bindings/src/lightning/util/persist.rs index b1e371b..5aae5c6 100644 --- a/lightning-c-bindings/src/lightning/util/persist.rs +++ b/lightning-c-bindings/src/lightning/util/persist.rs @@ -51,9 +51,9 @@ pub(crate) extern "C" fn Persister_clone_fields(orig: &Persister) -> Persister { } use lightning::util::persist::Persister as rustPersister; -impl<'a> rustPersister<'a, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::keysinterface::KeysInterface, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::util::logger::Logger, crate::lightning::routing::scoring::WriteableScore> for Persister { - fn persist_manager(&self, mut channel_manager: &lightning::ln::channelmanager::ChannelManager) -> Result<(), lightning::io::Error> { - let mut ret = (self.persist_manager)(self.this_arg, &crate::lightning::ln::channelmanager::ChannelManager { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_manager as *const lightning::ln::channelmanager::ChannelManager<_, _, _, _, _, >) as *mut _) }, is_owned: false }); +impl<'a> rustPersister<'a, crate::lightning::chain::Watch, crate::lightning::chain::chaininterface::BroadcasterInterface, crate::lightning::chain::keysinterface::EntropySource, crate::lightning::chain::keysinterface::NodeSigner, crate::lightning::chain::keysinterface::SignerProvider, crate::lightning::chain::chaininterface::FeeEstimator, crate::lightning::routing::router::Router, crate::lightning::util::logger::Logger, crate::lightning::routing::scoring::WriteableScore> for Persister { + fn persist_manager(&self, mut channel_manager: &lightning::ln::channelmanager::ChannelManager) -> Result<(), lightning::io::Error> { + let mut ret = (self.persist_manager)(self.this_arg, &crate::lightning::ln::channelmanager::ChannelManager { inner: unsafe { ObjOps::nonnull_ptr_to_inner((channel_manager as *const lightning::ln::channelmanager::ChannelManager<_, _, _, _, _, _, _, _, >) as *mut _) }, is_owned: false }); let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).to_rust() })}; local_ret } diff --git a/lightning-c-bindings/src/lightning/util/ser.rs b/lightning-c-bindings/src/lightning/util/ser.rs index 241033d..824dc7a 100644 --- a/lightning-c-bindings/src/lightning/util/ser.rs +++ b/lightning-c-bindings/src/lightning/util/ser.rs @@ -7,7 +7,10 @@ // source was automatically generated. //! A very simple serialization framework which is used to serialize/deserialize messages as well -//! as ChannelsManagers and ChannelMonitors. +//! as [`ChannelManager`]s and [`ChannelMonitor`]s. +//! +//! [`ChannelManager`]: crate::ln::channelmanager::ChannelManager +//! [`ChannelMonitor`]: crate::chain::channelmonitor::ChannelMonitor use alloc::str::FromStr; use core::ffi::c_void; @@ -25,7 +28,7 @@ pub static MAX_BUF_SIZE: usize = lightning::util::ser::MAX_BUF_SIZE; use lightning::util::ser::BigSize as nativeBigSizeImport; pub(crate) type nativeBigSize = nativeBigSizeImport; -/// Lightning TLV uses a custom variable-length integer called BigSize. It is similar to Bitcoin's +/// Lightning TLV uses a custom variable-length integer called `BigSize`. It is similar to Bitcoin's /// variable-length integers except that it is serialized in big-endian instead of little-endian. /// /// Like Bitcoin's variable-length integer, it exhibits ambiguity in that certain values can be @@ -103,7 +106,9 @@ pub(crate) type nativeHostname = nativeHostnameImport; /// Only the character set and length will be validated. /// The character set consists of ASCII alphanumeric characters, hyphens, and periods. /// Its length is guaranteed to be representable by a single byte. -/// This serialization is used by BOLT 7 hostnames. +/// This serialization is used by [`BOLT 7`] hostnames. +/// +/// [`BOLT 7`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md #[must_use] #[repr(C)] pub struct Hostname { diff --git a/lightning-c-bindings/src/lightning/util/ser_macros.rs b/lightning-c-bindings/src/lightning/util/ser_macros.rs new file mode 100644 index 0000000..1931804 --- /dev/null +++ b/lightning-c-bindings/src/lightning/util/ser_macros.rs @@ -0,0 +1,22 @@ +// This file is Copyright its original authors, visible in version control +// history and in the source files from which this was generated. +// +// This file is licensed under the license available in the LICENSE or LICENSE.md +// file in the root of this repository or, if no such file exists, the same +// license as that which applies to the original source files from which this +// source was automatically generated. + +//! Some macros that implement [`Readable`]/[`Writeable`] traits for lightning messages. +//! They also handle serialization and deserialization of TLVs. +//! +//! [`Readable`]: crate::util::ser::Readable +//! [`Writeable`]: crate::util::ser::Writeable + +use alloc::str::FromStr; +use core::ffi::c_void; +use core::convert::Infallible; +use bitcoin::hashes::Hash; +use crate::c_types::*; +#[cfg(feature="no-std")] +use alloc::{vec::Vec, boxed::Box}; + diff --git a/lightning-c-bindings/src/lightning_background_processor.rs b/lightning-c-bindings/src/lightning_background_processor.rs index 66ffc56..bee829f 100644 --- a/lightning-c-bindings/src/lightning_background_processor.rs +++ b/lightning-c-bindings/src/lightning_background_processor.rs @@ -109,7 +109,7 @@ pub enum GossipSync { None, } use lightning_background_processor::GossipSync as GossipSyncImport; -pub(crate) type nativeGossipSync = GossipSyncImport<&'static lightning::routing::gossip::P2PGossipSync<&'static lightning::routing::gossip::NetworkGraph, crate::lightning::chain::Access, crate::lightning::util::logger::Logger>, &'static lightning_rapid_gossip_sync::RapidGossipSync<&'static lightning::routing::gossip::NetworkGraph, crate::lightning::util::logger::Logger>, &'static lightning::routing::gossip::NetworkGraph, crate::lightning::chain::Access, crate::lightning::util::logger::Logger>; +pub(crate) type nativeGossipSync = GossipSyncImport<&'static lightning::routing::gossip::P2PGossipSync<&'static lightning::routing::gossip::NetworkGraph, crate::lightning::routing::utxo::UtxoLookup, crate::lightning::util::logger::Logger>, &'static lightning_rapid_gossip_sync::RapidGossipSync<&'static lightning::routing::gossip::NetworkGraph, crate::lightning::util::logger::Logger>, &'static lightning::routing::gossip::NetworkGraph, crate::lightning::routing::utxo::UtxoLookup, crate::lightning::util::logger::Logger>; impl GossipSync { #[allow(unused)] diff --git a/lightning-c-bindings/src/lightning_invoice/constants.rs b/lightning-c-bindings/src/lightning_invoice/constants.rs index 4486e0e..a51113f 100644 --- a/lightning-c-bindings/src/lightning_invoice/constants.rs +++ b/lightning-c-bindings/src/lightning_invoice/constants.rs @@ -33,7 +33,7 @@ pub static TAG_DESCRIPTION_HASH: u8 = lightning_invoice::constants::TAG_DESCRIPT pub static TAG_EXPIRY_TIME: u8 = lightning_invoice::constants::TAG_EXPIRY_TIME; #[no_mangle] -pub static TAG_MIN_FINAL_CLTV_EXPIRY: u8 = lightning_invoice::constants::TAG_MIN_FINAL_CLTV_EXPIRY; +pub static TAG_MIN_FINAL_CLTV_EXPIRY_DELTA: u8 = lightning_invoice::constants::TAG_MIN_FINAL_CLTV_EXPIRY_DELTA; #[no_mangle] pub static TAG_FALLBACK: u8 = lightning_invoice::constants::TAG_FALLBACK; diff --git a/lightning-c-bindings/src/lightning_invoice/mod.rs b/lightning-c-bindings/src/lightning_invoice/mod.rs index 78bc50b..4b12f32 100644 --- a/lightning-c-bindings/src/lightning_invoice/mod.rs +++ b/lightning-c-bindings/src/lightning_invoice/mod.rs @@ -613,13 +613,13 @@ pub static DEFAULT_EXPIRY_TIME: u64 = lightning_invoice::DEFAULT_EXPIRY_TIME; /// Default minimum final CLTV expiry as defined by [BOLT 11]. /// /// Note that this is *not* the same value as rust-lightning's minimum CLTV expiry, which is -/// provided in [`MIN_FINAL_CLTV_EXPIRY`]. +/// provided in [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. /// /// [BOLT 11]: https://github.com/lightning/bolts/blob/master/11-payment-encoding.md -/// [`MIN_FINAL_CLTV_EXPIRY`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY +/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA #[no_mangle] -pub static DEFAULT_MIN_FINAL_CLTV_EXPIRY: u64 = lightning_invoice::DEFAULT_MIN_FINAL_CLTV_EXPIRY; +pub static DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA: u64 = lightning_invoice::DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA; use lightning_invoice::Invoice as nativeInvoiceImport; pub(crate) type nativeInvoice = nativeInvoiceImport; @@ -1684,18 +1684,18 @@ pub extern "C" fn ExpiryTime_eq(a: &ExpiryTime, b: &ExpiryTime) -> bool { if a.get_native_ref() == b.get_native_ref() { true } else { false } } -use lightning_invoice::MinFinalCltvExpiry as nativeMinFinalCltvExpiryImport; -pub(crate) type nativeMinFinalCltvExpiry = nativeMinFinalCltvExpiryImport; +use lightning_invoice::MinFinalCltvExpiryDelta as nativeMinFinalCltvExpiryDeltaImport; +pub(crate) type nativeMinFinalCltvExpiryDelta = nativeMinFinalCltvExpiryDeltaImport; -/// `min_final_cltv_expiry` to use for the last HTLC in the route +/// `min_final_cltv_expiry_delta` to use for the last HTLC in the route #[must_use] #[repr(C)] -pub struct MinFinalCltvExpiry { +pub struct MinFinalCltvExpiryDelta { /// A pointer to the opaque Rust object. /// Nearly everywhere, inner must be non-null, however in places where /// the Rust equivalent takes an Option, it may be set to null to indicate None. - pub inner: *mut nativeMinFinalCltvExpiry, + pub inner: *mut nativeMinFinalCltvExpiryDelta, /// Indicates that this is the only struct which contains the same pointer. /// Rust functions which take ownership of an object provided via an argument require @@ -1703,31 +1703,31 @@ pub struct MinFinalCltvExpiry { pub is_owned: bool, } -impl Drop for MinFinalCltvExpiry { +impl Drop for MinFinalCltvExpiryDelta { fn drop(&mut self) { - if self.is_owned && !<*mut nativeMinFinalCltvExpiry>::is_null(self.inner) { + if self.is_owned && !<*mut nativeMinFinalCltvExpiryDelta>::is_null(self.inner) { let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; } } } -/// Frees any resources used by the MinFinalCltvExpiry, if is_owned is set and inner is non-NULL. +/// Frees any resources used by the MinFinalCltvExpiryDelta, if is_owned is set and inner is non-NULL. #[no_mangle] -pub extern "C" fn MinFinalCltvExpiry_free(this_obj: MinFinalCltvExpiry) { } +pub extern "C" fn MinFinalCltvExpiryDelta_free(this_obj: MinFinalCltvExpiryDelta) { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -pub(crate) extern "C" fn MinFinalCltvExpiry_free_void(this_ptr: *mut c_void) { - let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMinFinalCltvExpiry) }; +pub(crate) extern "C" fn MinFinalCltvExpiryDelta_free_void(this_ptr: *mut c_void) { + let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMinFinalCltvExpiryDelta) }; } #[allow(unused)] -impl MinFinalCltvExpiry { - pub(crate) fn get_native_ref(&self) -> &'static nativeMinFinalCltvExpiry { +impl MinFinalCltvExpiryDelta { + pub(crate) fn get_native_ref(&self) -> &'static nativeMinFinalCltvExpiryDelta { unsafe { &*ObjOps::untweak_ptr(self.inner) } } - pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMinFinalCltvExpiry { + pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMinFinalCltvExpiryDelta { unsafe { &mut *ObjOps::untweak_ptr(self.inner) } } /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy - pub(crate) fn take_inner(mut self) -> *mut nativeMinFinalCltvExpiry { + pub(crate) fn take_inner(mut self) -> *mut nativeMinFinalCltvExpiryDelta { assert!(self.is_owned); let ret = ObjOps::untweak_ptr(self.inner); self.inner = core::ptr::null_mut(); @@ -1735,26 +1735,26 @@ impl MinFinalCltvExpiry { } } #[no_mangle] -pub extern "C" fn MinFinalCltvExpiry_get_a(this_ptr: &MinFinalCltvExpiry) -> u64 { +pub extern "C" fn MinFinalCltvExpiryDelta_get_a(this_ptr: &MinFinalCltvExpiryDelta) -> u64 { let mut inner_val = &mut this_ptr.get_native_mut_ref().0; *inner_val } #[no_mangle] -pub extern "C" fn MinFinalCltvExpiry_set_a(this_ptr: &mut MinFinalCltvExpiry, mut val: u64) { +pub extern "C" fn MinFinalCltvExpiryDelta_set_a(this_ptr: &mut MinFinalCltvExpiryDelta, mut val: u64) { unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.0 = val; } -/// Constructs a new MinFinalCltvExpiry given each field +/// Constructs a new MinFinalCltvExpiryDelta given each field #[must_use] #[no_mangle] -pub extern "C" fn MinFinalCltvExpiry_new(mut a_arg: u64) -> MinFinalCltvExpiry { - MinFinalCltvExpiry { inner: ObjOps::heap_alloc(lightning_invoice::MinFinalCltvExpiry ( +pub extern "C" fn MinFinalCltvExpiryDelta_new(mut a_arg: u64) -> MinFinalCltvExpiryDelta { + MinFinalCltvExpiryDelta { inner: ObjOps::heap_alloc(lightning_invoice::MinFinalCltvExpiryDelta ( a_arg, )), is_owned: true } } -impl Clone for MinFinalCltvExpiry { +impl Clone for MinFinalCltvExpiryDelta { fn clone(&self) -> Self { Self { - inner: if <*mut nativeMinFinalCltvExpiry>::is_null(self.inner) { core::ptr::null_mut() } else { + inner: if <*mut nativeMinFinalCltvExpiryDelta>::is_null(self.inner) { core::ptr::null_mut() } else { ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) }, is_owned: true, } @@ -1762,17 +1762,17 @@ impl Clone for MinFinalCltvExpiry { } #[allow(unused)] /// Used only if an object of this type is returned as a trait impl by a method -pub(crate) extern "C" fn MinFinalCltvExpiry_clone_void(this_ptr: *const c_void) -> *mut c_void { - Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeMinFinalCltvExpiry)).clone() })) as *mut c_void +pub(crate) extern "C" fn MinFinalCltvExpiryDelta_clone_void(this_ptr: *const c_void) -> *mut c_void { + Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeMinFinalCltvExpiryDelta)).clone() })) as *mut c_void } #[no_mangle] -/// Creates a copy of the MinFinalCltvExpiry -pub extern "C" fn MinFinalCltvExpiry_clone(orig: &MinFinalCltvExpiry) -> MinFinalCltvExpiry { +/// Creates a copy of the MinFinalCltvExpiryDelta +pub extern "C" fn MinFinalCltvExpiryDelta_clone(orig: &MinFinalCltvExpiryDelta) -> MinFinalCltvExpiryDelta { orig.clone() } -/// Checks if two MinFinalCltvExpirys contain equal inner contents. +/// Checks if two MinFinalCltvExpiryDeltas contain equal inner contents. #[no_mangle] -pub extern "C" fn MinFinalCltvExpiry_hash(o: &MinFinalCltvExpiry) -> u64 { +pub extern "C" fn MinFinalCltvExpiryDelta_hash(o: &MinFinalCltvExpiryDelta) -> u64 { if o.inner.is_null() { return 0; } // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core #[allow(deprecated)] @@ -1780,11 +1780,11 @@ pub extern "C" fn MinFinalCltvExpiry_hash(o: &MinFinalCltvExpiry) -> u64 { core::hash::Hash::hash(o.get_native_ref(), &mut hasher); core::hash::Hasher::finish(&hasher) } -/// Checks if two MinFinalCltvExpirys contain equal inner contents. +/// Checks if two MinFinalCltvExpiryDeltas contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. /// Two objects with NULL inner values will be considered "equal" here. #[no_mangle] -pub extern "C" fn MinFinalCltvExpiry_eq(a: &MinFinalCltvExpiry, b: &MinFinalCltvExpiry) -> bool { +pub extern "C" fn MinFinalCltvExpiryDelta_eq(a: &MinFinalCltvExpiryDelta, b: &MinFinalCltvExpiryDelta) -> bool { if a.inner == b.inner { return true; } if a.inner.is_null() || b.inner.is_null() { return false; } if a.get_native_ref() == b.get_native_ref() { true } else { false } @@ -2243,9 +2243,9 @@ pub extern "C" fn RawInvoice_expiry_time(this_arg: &crate::lightning_invoice::Ra /// Note that the return value (or a relevant inner pointer) may be NULL or all-0s to represent None #[must_use] #[no_mangle] -pub extern "C" fn RawInvoice_min_final_cltv_expiry(this_arg: &crate::lightning_invoice::RawInvoice) -> crate::lightning_invoice::MinFinalCltvExpiry { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.min_final_cltv_expiry(); - let mut local_ret = crate::lightning_invoice::MinFinalCltvExpiry { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning_invoice::MinFinalCltvExpiry<>) as *mut _ }, is_owned: false }; +pub extern "C" fn RawInvoice_min_final_cltv_expiry_delta(this_arg: &crate::lightning_invoice::RawInvoice) -> crate::lightning_invoice::MinFinalCltvExpiryDelta { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.min_final_cltv_expiry_delta(); + let mut local_ret = crate::lightning_invoice::MinFinalCltvExpiryDelta { inner: unsafe { (if ret.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (ret.unwrap()) }) } as *const lightning_invoice::MinFinalCltvExpiryDelta<>) as *mut _ }, is_owned: false }; local_ret } @@ -2487,12 +2487,12 @@ pub extern "C" fn Invoice_would_expire(this_arg: &crate::lightning_invoice::Invo ret } -/// Returns the invoice's `min_final_cltv_expiry` time, if present, otherwise -/// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY`]. +/// Returns the invoice's `min_final_cltv_expiry_delta` time, if present, otherwise +/// [`DEFAULT_MIN_FINAL_CLTV_EXPIRY_DELTA`]. #[must_use] #[no_mangle] -pub extern "C" fn Invoice_min_final_cltv_expiry(this_arg: &crate::lightning_invoice::Invoice) -> u64 { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.min_final_cltv_expiry(); +pub extern "C" fn Invoice_min_final_cltv_expiry_delta(this_arg: &crate::lightning_invoice::Invoice) -> u64 { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.min_final_cltv_expiry_delta(); ret } @@ -2618,6 +2618,10 @@ pub enum CreationError { /// /// [phantom invoices]: crate::utils::create_phantom_invoice MissingRouteHints, + /// The provided `min_final_cltv_expiry_delta` was less than [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. + /// + /// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA + MinFinalCltvExpiryDeltaTooShort, } use lightning_invoice::CreationError as CreationErrorImport; pub(crate) type nativeCreationError = CreationErrorImport; @@ -2631,6 +2635,7 @@ impl CreationError { CreationError::TimestampOutOfBounds => nativeCreationError::TimestampOutOfBounds, CreationError::InvalidAmount => nativeCreationError::InvalidAmount, CreationError::MissingRouteHints => nativeCreationError::MissingRouteHints, + CreationError::MinFinalCltvExpiryDeltaTooShort => nativeCreationError::MinFinalCltvExpiryDeltaTooShort, } } #[allow(unused)] @@ -2641,6 +2646,7 @@ impl CreationError { CreationError::TimestampOutOfBounds => nativeCreationError::TimestampOutOfBounds, CreationError::InvalidAmount => nativeCreationError::InvalidAmount, CreationError::MissingRouteHints => nativeCreationError::MissingRouteHints, + CreationError::MinFinalCltvExpiryDeltaTooShort => nativeCreationError::MinFinalCltvExpiryDeltaTooShort, } } #[allow(unused)] @@ -2651,6 +2657,7 @@ impl CreationError { nativeCreationError::TimestampOutOfBounds => CreationError::TimestampOutOfBounds, nativeCreationError::InvalidAmount => CreationError::InvalidAmount, nativeCreationError::MissingRouteHints => CreationError::MissingRouteHints, + nativeCreationError::MinFinalCltvExpiryDeltaTooShort => CreationError::MinFinalCltvExpiryDeltaTooShort, } } #[allow(unused)] @@ -2661,6 +2668,7 @@ impl CreationError { nativeCreationError::TimestampOutOfBounds => CreationError::TimestampOutOfBounds, nativeCreationError::InvalidAmount => CreationError::InvalidAmount, nativeCreationError::MissingRouteHints => CreationError::MissingRouteHints, + nativeCreationError::MinFinalCltvExpiryDeltaTooShort => CreationError::MinFinalCltvExpiryDeltaTooShort, } } } @@ -2689,6 +2697,10 @@ pub extern "C" fn CreationError_invalid_amount() -> CreationError { /// Utility method to constructs a new MissingRouteHints-variant CreationError pub extern "C" fn CreationError_missing_route_hints() -> CreationError { CreationError::MissingRouteHints} +#[no_mangle] +/// Utility method to constructs a new MinFinalCltvExpiryDeltaTooShort-variant CreationError +pub extern "C" fn CreationError_min_final_cltv_expiry_delta_too_short() -> CreationError { + CreationError::MinFinalCltvExpiryDeltaTooShort} /// Checks if two CreationErrors contain equal inner contents. /// This ignores pointers and is_owned flags and looks at the values in fields. #[no_mangle] diff --git a/lightning-c-bindings/src/lightning_invoice/payment.rs b/lightning-c-bindings/src/lightning_invoice/payment.rs index 8550c27..4c19e67 100644 --- a/lightning-c-bindings/src/lightning_invoice/payment.rs +++ b/lightning-c-bindings/src/lightning_invoice/payment.rs @@ -6,133 +6,7 @@ // license as that which applies to the original source files from which this // source was automatically generated. -//! A module for paying Lightning invoices and sending spontaneous payments. -//! -//! Defines an [`InvoicePayer`] utility for sending payments, parameterized by [`Payer`] and -//! [`Router`] traits. Implementations of [`Payer`] provide the payer's node id, channels, and means -//! to send a payment over a [`Route`]. Implementations of [`Router`] find a [`Route`] between payer -//! and payee using information provided by the payer and from the payee's [`Invoice`], when -//! applicable. -//! -//! [`InvoicePayer`] uses its [`Router`] parameterization for optionally notifying scorers upon -//! receiving the [`Event::PaymentPathFailed`] and [`Event::PaymentPathSuccessful`] events. -//! It also does the same for payment probe failure and success events using [`Event::ProbeFailed`] -//! and [`Event::ProbeSuccessful`]. -//! -//! [`InvoicePayer`] is capable of retrying failed payments. It accomplishes this by implementing -//! [`EventHandler`] which decorates a user-provided handler. It will intercept any -//! [`Event::PaymentPathFailed`] events and retry the failed paths for a fixed number of total -//! attempts or until retry is no longer possible. In such a situation, [`InvoicePayer`] will pass -//! along the events to the user-provided handler. -//! -//! # Example -//! -//! ``` -//! # extern crate lightning; -//! # extern crate lightning_invoice; -//! # extern crate secp256k1; -//! # -//! # use lightning::io; -//! # use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret}; -//! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure}; -//! # use lightning::ln::msgs::LightningError; -//! # use lightning::routing::gossip::NodeId; -//! # use lightning::routing::router::{InFlightHtlcs, Route, RouteHop, RouteParameters, Router}; -//! # use lightning::routing::scoring::{ChannelUsage, Score}; -//! # use lightning::util::events::{Event, EventHandler, EventsProvider}; -//! # use lightning::util::logger::{Logger, Record}; -//! # use lightning::util::ser::{Writeable, Writer}; -//! # use lightning_invoice::Invoice; -//! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry}; -//! # use secp256k1::PublicKey; -//! # use std::cell::RefCell; -//! # use std::ops::Deref; -//! # -//! # struct FakeEventProvider {} -//! # impl EventsProvider for FakeEventProvider { -//! # fn process_pending_events(&self, handler: H) where H::Target: EventHandler {} -//! # } -//! # -//! # struct FakePayer {} -//! # impl Payer for FakePayer { -//! # fn node_id(&self) -> PublicKey { unimplemented!() } -//! # fn first_hops(&self) -> Vec { unimplemented!() } -//! # fn send_payment( -//! # &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option, -//! # payment_id: PaymentId -//! # ) -> Result<(), PaymentSendFailure> { unimplemented!() } -//! # fn send_spontaneous_payment( -//! # &self, route: &Route, payment_preimage: PaymentPreimage, payment_id: PaymentId, -//! # ) -> Result<(), PaymentSendFailure> { unimplemented!() } -//! # fn retry_payment( -//! # &self, route: &Route, payment_id: PaymentId -//! # ) -> Result<(), PaymentSendFailure> { unimplemented!() } -//! # fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() } -//! # fn inflight_htlcs(&self) -> InFlightHtlcs { unimplemented!() } -//! # } -//! # -//! # struct FakeRouter {} -//! # impl Router for FakeRouter { -//! # fn find_route( -//! # &self, payer: &PublicKey, params: &RouteParameters, -//! # first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs -//! # ) -> Result { unimplemented!() } -//! # fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() } -//! # fn notify_payment_path_successful(&self, path: &[&RouteHop]) { unimplemented!() } -//! # fn notify_payment_probe_successful(&self, path: &[&RouteHop]) { unimplemented!() } -//! # fn notify_payment_probe_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() } -//! # } -//! # -//! # struct FakeScorer {} -//! # impl Writeable for FakeScorer { -//! # fn write(&self, w: &mut W) -> Result<(), io::Error> { unimplemented!(); } -//! # } -//! # impl Score for FakeScorer { -//! # fn channel_penalty_msat( -//! # &self, _short_channel_id: u64, _source: &NodeId, _target: &NodeId, _usage: ChannelUsage -//! # ) -> u64 { 0 } -//! # fn payment_path_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {} -//! # fn payment_path_successful(&mut self, _path: &[&RouteHop]) {} -//! # fn probe_failed(&mut self, _path: &[&RouteHop], _short_channel_id: u64) {} -//! # fn probe_successful(&mut self, _path: &[&RouteHop]) {} -//! # } -//! # -//! # struct FakeLogger {} -//! # impl Logger for FakeLogger { -//! # fn log(&self, record: &Record) { unimplemented!() } -//! # } -//! # -//! # fn main() { -//! let event_handler = |event: Event| { -//! match event { -//! Event::PaymentPathFailed { .. } => println!(\"payment failed after retries\"), -//! Event::PaymentSent { .. } => println!(\"payment successful\"), -//! _ => {}, -//! } -//! }; -//! # let payer = FakePayer {}; -//! # let router = FakeRouter {}; -//! # let scorer = RefCell::new(FakeScorer {}); -//! # let logger = FakeLogger {}; -//! let invoice_payer = InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(2)); -//! -//! let invoice = \"...\"; -//! if let Ok(invoice) = invoice.parse::() { -//! invoice_payer.pay_invoice(&invoice).unwrap(); -//! -//! # let event_provider = FakeEventProvider {}; -//! loop { -//! event_provider.process_pending_events(&invoice_payer); -//! } -//! } -//! # } -//! ``` -//! -//! # Note -//! -//! The [`Route`] is computed before each payment attempt. Any updates affecting path finding such -//! as updates to the network graph or changes to channel scores should be applied prior to -//! retries, typically by way of composing [`EventHandler`]s accordingly. +//! Convenient utilities for paying Lightning invoices and sending spontaneous payments. use alloc::str::FromStr; use core::ffi::c_void; @@ -142,296 +16,70 @@ use crate::c_types::*; #[cfg(feature="no-std")] use alloc::{vec::Vec, boxed::Box}; - -use lightning_invoice::payment::InvoicePayer as nativeInvoicePayerImport; -pub(crate) type nativeInvoicePayer = nativeInvoicePayerImport; - -/// A utility for paying [`Invoice`]s and sending spontaneous payments. +/// Pays the given [`Invoice`], retrying if needed based on [`Retry`]. /// -/// See [module-level documentation] for details. +/// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long +/// as the payment is still pending. Once the payment completes or fails, you must ensure that +/// a second payment with the same [`PaymentHash`] is never sent. /// -/// [module-level documentation]: crate::payment -#[must_use] -#[repr(C)] -pub struct InvoicePayer { - /// A pointer to the opaque Rust object. - - /// Nearly everywhere, inner must be non-null, however in places where - /// the Rust equivalent takes an Option, it may be set to null to indicate None. - pub inner: *mut nativeInvoicePayer, - /// Indicates that this is the only struct which contains the same pointer. - - /// Rust functions which take ownership of an object provided via an argument require - /// this to be true and invalidate the object pointed to by inner. - pub is_owned: bool, -} - -impl Drop for InvoicePayer { - fn drop(&mut self) { - if self.is_owned && !<*mut nativeInvoicePayer>::is_null(self.inner) { - let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) }; - } - } -} -/// Frees any resources used by the InvoicePayer, if is_owned is set and inner is non-NULL. +/// If you wish to use a different payment idempotency token, see [`pay_invoice_with_id`]. #[no_mangle] -pub extern "C" fn InvoicePayer_free(this_obj: InvoicePayer) { } -#[allow(unused)] -/// Used only if an object of this type is returned as a trait impl by a method -pub(crate) extern "C" fn InvoicePayer_free_void(this_ptr: *mut c_void) { - let _ = unsafe { Box::from_raw(this_ptr as *mut nativeInvoicePayer) }; -} -#[allow(unused)] -impl InvoicePayer { - pub(crate) fn get_native_ref(&self) -> &'static nativeInvoicePayer { - unsafe { &*ObjOps::untweak_ptr(self.inner) } - } - pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeInvoicePayer { - unsafe { &mut *ObjOps::untweak_ptr(self.inner) } - } - /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy - pub(crate) fn take_inner(mut self) -> *mut nativeInvoicePayer { - assert!(self.is_owned); - let ret = ObjOps::untweak_ptr(self.inner); - self.inner = core::ptr::null_mut(); - ret - } +pub extern "C" fn pay_invoice(invoice: &crate::lightning_invoice::Invoice, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry, channelmanager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { + let mut ret = lightning_invoice::payment::pay_invoice::(invoice.get_native_ref(), retry_strategy.into_native(), channelmanager.get_native_ref()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; + local_ret } -/// A trait defining behavior of an [`Invoice`] payer. -/// -/// While the behavior of [`InvoicePayer`] provides idempotency of duplicate `send_*payment` calls -/// with the same [`PaymentHash`], it is up to the `Payer` to provide idempotency across restarts. + +/// Pays the given [`Invoice`] with a custom idempotency key, retrying if needed based on [`Retry`]. /// -/// [`ChannelManager`] provides idempotency for duplicate payments with the same [`PaymentId`]. +/// Note that idempotency is only guaranteed as long as the payment is still pending. Once the +/// payment completes or fails, no idempotency guarantees are made. /// -/// In order to trivially ensure idempotency for payments, the default `Payer` implementation -/// reuses the [`PaymentHash`] bytes as the [`PaymentId`]. Custom implementations wishing to -/// provide payment idempotency with a different idempotency key (i.e. [`PaymentId`]) should map -/// the [`Invoice`] or spontaneous payment target pubkey to their own idempotency key. +/// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`] +/// has never been paid before. /// -/// [`ChannelManager`]: lightning::ln::channelmanager::ChannelManager -#[repr(C)] -pub struct Payer { - /// An opaque pointer which is passed to your function implementations as an argument. - /// This has no meaning in the LDK, and can be NULL or any other value. - pub this_arg: *mut c_void, - /// Returns the payer's node id. - #[must_use] - pub node_id: extern "C" fn (this_arg: *const c_void) -> crate::c_types::PublicKey, - /// Returns the payer's channels. - #[must_use] - pub first_hops: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_ChannelDetailsZ, - /// Sends a payment over the Lightning Network using the given [`Route`]. - /// - /// Note that payment_secret (or a relevant inner pointer) may be NULL or all-0s to represent None - #[must_use] - pub send_payment: extern "C" fn (this_arg: *const c_void, route: &crate::lightning::routing::router::Route, payment_hash: crate::c_types::ThirtyTwoBytes, payment_secret: crate::c_types::ThirtyTwoBytes, payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ, - /// Sends a spontaneous payment over the Lightning Network using the given [`Route`]. - #[must_use] - pub send_spontaneous_payment: extern "C" fn (this_arg: *const c_void, route: &crate::lightning::routing::router::Route, payment_preimage: crate::c_types::ThirtyTwoBytes, payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ, - /// Retries a failed payment path for the [`PaymentId`] using the given [`Route`]. - #[must_use] - pub retry_payment: extern "C" fn (this_arg: *const c_void, route: &crate::lightning::routing::router::Route, payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ, - /// Signals that no further retries for the given payment will occur. - pub abandon_payment: extern "C" fn (this_arg: *const c_void, payment_id: crate::c_types::ThirtyTwoBytes), - /// Construct an [`InFlightHtlcs`] containing information about currently used up liquidity - /// across payments. - #[must_use] - pub inflight_htlcs: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::router::InFlightHtlcs, - /// Frees any resources associated with this object given its this_arg pointer. - /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed. - pub free: Option, -} -unsafe impl Send for Payer {} -unsafe impl Sync for Payer {} +/// See [`pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency token. #[no_mangle] -pub(crate) extern "C" fn Payer_clone_fields(orig: &Payer) -> Payer { - Payer { - this_arg: orig.this_arg, - node_id: Clone::clone(&orig.node_id), - first_hops: Clone::clone(&orig.first_hops), - send_payment: Clone::clone(&orig.send_payment), - send_spontaneous_payment: Clone::clone(&orig.send_spontaneous_payment), - retry_payment: Clone::clone(&orig.retry_payment), - abandon_payment: Clone::clone(&orig.abandon_payment), - inflight_htlcs: Clone::clone(&orig.inflight_htlcs), - free: Clone::clone(&orig.free), - } -} - -use lightning_invoice::payment::Payer as rustPayer; -impl rustPayer for Payer { - fn node_id(&self) -> secp256k1::PublicKey { - let mut ret = (self.node_id)(self.this_arg); - ret.into_rust() - } - fn first_hops(&self) -> Vec { - let mut ret = (self.first_hops)(self.this_arg); - let mut local_ret = Vec::new(); for mut item in ret.into_rust().drain(..) { local_ret.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; - local_ret - } - fn send_payment(&self, mut route: &lightning::routing::router::Route, mut payment_hash: lightning::ln::PaymentHash, mut payment_secret: &Option, mut payment_id: lightning::ln::channelmanager::PaymentId) -> Result<(), lightning::ln::channelmanager::PaymentSendFailure> { - let mut local_payment_secret = if payment_secret.is_none() { crate::c_types::ThirtyTwoBytes::null() } else { { crate::c_types::ThirtyTwoBytes { data: (payment_secret.unwrap()).0 } } }; - let mut ret = (self.send_payment)(self.this_arg, &crate::lightning::routing::router::Route { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route as *const lightning::routing::router::Route<>) as *mut _) }, is_owned: false }, crate::c_types::ThirtyTwoBytes { data: payment_hash.0 }, local_payment_secret, crate::c_types::ThirtyTwoBytes { data: payment_id.0 }); - let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; - local_ret - } - fn send_spontaneous_payment(&self, mut route: &lightning::routing::router::Route, mut payment_preimage: lightning::ln::PaymentPreimage, mut payment_id: lightning::ln::channelmanager::PaymentId) -> Result<(), lightning::ln::channelmanager::PaymentSendFailure> { - let mut ret = (self.send_spontaneous_payment)(self.this_arg, &crate::lightning::routing::router::Route { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route as *const lightning::routing::router::Route<>) as *mut _) }, is_owned: false }, crate::c_types::ThirtyTwoBytes { data: payment_preimage.0 }, crate::c_types::ThirtyTwoBytes { data: payment_id.0 }); - let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; - local_ret - } - fn retry_payment(&self, mut route: &lightning::routing::router::Route, mut payment_id: lightning::ln::channelmanager::PaymentId) -> Result<(), lightning::ln::channelmanager::PaymentSendFailure> { - let mut ret = (self.retry_payment)(self.this_arg, &crate::lightning::routing::router::Route { inner: unsafe { ObjOps::nonnull_ptr_to_inner((route as *const lightning::routing::router::Route<>) as *mut _) }, is_owned: false }, crate::c_types::ThirtyTwoBytes { data: payment_id.0 }); - let mut local_ret = match ret.result_ok { true => Ok( { () /*(*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.result)) })*/ }), false => Err( { (*unsafe { Box::from_raw(<*mut _>::take_ptr(&mut ret.contents.err)) }).into_native() })}; - local_ret - } - fn abandon_payment(&self, mut payment_id: lightning::ln::channelmanager::PaymentId) { - (self.abandon_payment)(self.this_arg, crate::c_types::ThirtyTwoBytes { data: payment_id.0 }) - } - fn inflight_htlcs(&self) -> lightning::routing::router::InFlightHtlcs { - let mut ret = (self.inflight_htlcs)(self.this_arg); - *unsafe { Box::from_raw(ret.take_inner()) } - } +pub extern "C" fn pay_invoice_with_id(invoice: &crate::lightning_invoice::Invoice, mut payment_id: crate::c_types::ThirtyTwoBytes, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry, channelmanager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NonePaymentErrorZ { + let mut ret = lightning_invoice::payment::pay_invoice_with_id::(invoice.get_native_ref(), ::lightning::ln::channelmanager::PaymentId(payment_id.data), retry_strategy.into_native(), channelmanager.get_native_ref()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; + local_ret } -// We're essentially a pointer already, or at least a set of pointers, so allow us to be used -// directly as a Deref trait in higher-level structs: -impl core::ops::Deref for Payer { - type Target = Self; - fn deref(&self) -> &Self { - self - } -} -/// Calls the free function if one is set -#[no_mangle] -pub extern "C" fn Payer_free(this_ptr: Payer) { } -impl Drop for Payer { - fn drop(&mut self) { - if let Some(f) = self.free { - f(self.this_arg); - } - } -} -/// Strategies available to retry payment path failures for an [`Invoice`]. +/// Pays the given zero-value [`Invoice`] using the given amount, retrying if needed based on +/// [`Retry`]. /// -#[derive(Clone)] -#[must_use] -#[repr(C)] -pub enum Retry { - /// Max number of attempts to retry payment. - /// - /// Note that this is the number of *path* failures, not full payment retries. For multi-path - /// payments, if this is less than the total number of paths, we will never even retry all of the - /// payment's paths. - Attempts( - usize), - /// Time elapsed before abandoning retries for a payment. - Timeout( - u64), -} -use lightning_invoice::payment::Retry as RetryImport; -pub(crate) type nativeRetry = RetryImport; - -impl Retry { - #[allow(unused)] - pub(crate) fn to_native(&self) -> nativeRetry { - match self { - Retry::Attempts (ref a, ) => { - let mut a_nonref = Clone::clone(a); - nativeRetry::Attempts ( - a_nonref, - ) - }, - Retry::Timeout (ref a, ) => { - let mut a_nonref = Clone::clone(a); - nativeRetry::Timeout ( - core::time::Duration::from_secs(a_nonref), - ) - }, - } - } - #[allow(unused)] - pub(crate) fn into_native(self) -> nativeRetry { - match self { - Retry::Attempts (mut a, ) => { - nativeRetry::Attempts ( - a, - ) - }, - Retry::Timeout (mut a, ) => { - nativeRetry::Timeout ( - core::time::Duration::from_secs(a), - ) - }, - } - } - #[allow(unused)] - pub(crate) fn from_native(native: &nativeRetry) -> Self { - match native { - nativeRetry::Attempts (ref a, ) => { - let mut a_nonref = Clone::clone(a); - Retry::Attempts ( - a_nonref, - ) - }, - nativeRetry::Timeout (ref a, ) => { - let mut a_nonref = Clone::clone(a); - Retry::Timeout ( - a_nonref.as_secs(), - ) - }, - } - } - #[allow(unused)] - pub(crate) fn native_into(native: nativeRetry) -> Self { - match native { - nativeRetry::Attempts (mut a, ) => { - Retry::Attempts ( - a, - ) - }, - nativeRetry::Timeout (mut a, ) => { - Retry::Timeout ( - a.as_secs(), - ) - }, - } - } -} -/// Frees any resources used by the Retry -#[no_mangle] -pub extern "C" fn Retry_free(this_ptr: Retry) { } -/// Creates a copy of the Retry -#[no_mangle] -pub extern "C" fn Retry_clone(orig: &Retry) -> Retry { - orig.clone() -} -#[no_mangle] -/// Utility method to constructs a new Attempts-variant Retry -pub extern "C" fn Retry_attempts(a: usize) -> Retry { - Retry::Attempts(a, ) -} -#[no_mangle] -/// Utility method to constructs a new Timeout-variant Retry -pub extern "C" fn Retry_timeout(a: u64) -> Retry { - Retry::Timeout(a, ) -} -/// Checks if two Retrys contain equal inner contents. -/// This ignores pointers and is_owned flags and looks at the values in fields. +/// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long +/// as the payment is still pending. Once the payment completes or fails, you must ensure that +/// a second payment with the same [`PaymentHash`] is never sent. +/// +/// If you wish to use a different payment idempotency token, see +/// [`pay_zero_value_invoice_with_id`]. #[no_mangle] -pub extern "C" fn Retry_eq(a: &Retry, b: &Retry) -> bool { - if &a.to_native() == &b.to_native() { true } else { false } +pub extern "C" fn pay_zero_value_invoice(invoice: &crate::lightning_invoice::Invoice, mut amount_msats: u64, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry, channelmanager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { + let mut ret = lightning_invoice::payment::pay_zero_value_invoice::(invoice.get_native_ref(), amount_msats, retry_strategy.into_native(), channelmanager.get_native_ref()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; + local_ret } -/// Checks if two Retrys contain equal inner contents. + +/// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key, +/// , retrying if needed based on [`Retry`]. +/// +/// Note that idempotency is only guaranteed as long as the payment is still pending. Once the +/// payment completes or fails, no idempotency guarantees are made. +/// +/// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`] +/// has never been paid before. +/// +/// See [`pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the +/// idempotency token. #[no_mangle] -pub extern "C" fn Retry_hash(o: &Retry) -> u64 { - // Note that we'd love to use alloc::collections::hash_map::DefaultHasher but it's not in core - #[allow(deprecated)] - let mut hasher = core::hash::SipHasher::new(); - core::hash::Hash::hash(&o.to_native(), &mut hasher); - core::hash::Hasher::finish(&hasher) +pub extern "C" fn pay_zero_value_invoice_with_id(invoice: &crate::lightning_invoice::Invoice, mut amount_msats: u64, mut payment_id: crate::c_types::ThirtyTwoBytes, mut retry_strategy: crate::lightning::ln::outbound_payment::Retry, channelmanager: &crate::lightning::ln::channelmanager::ChannelManager) -> crate::c_types::derived::CResult_NonePaymentErrorZ { + let mut ret = lightning_invoice::payment::pay_zero_value_invoice_with_id::(invoice.get_native_ref(), amount_msats, ::lightning::ln::channelmanager::PaymentId(payment_id.data), retry_strategy.into_native(), channelmanager.get_native_ref()); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; + local_ret } + /// An error that may occur when making a payment. #[derive(Clone)] #[must_use] @@ -440,12 +88,9 @@ pub enum PaymentError { /// An error resulting from the provided [`Invoice`] or payment hash. Invoice( crate::c_types::Str), - /// An error occurring when finding a route. - Routing( - crate::lightning::ln::msgs::LightningError), /// An error occurring when sending a payment. Sending( - crate::lightning::ln::channelmanager::PaymentSendFailure), + crate::lightning::ln::outbound_payment::RetryableSendFailure), } use lightning_invoice::payment::PaymentError as PaymentErrorImport; pub(crate) type nativePaymentError = PaymentErrorImport; @@ -460,12 +105,6 @@ impl PaymentError { a_nonref.into_str(), ) }, - PaymentError::Routing (ref a, ) => { - let mut a_nonref = Clone::clone(a); - nativePaymentError::Routing ( - *unsafe { Box::from_raw(a_nonref.take_inner()) }, - ) - }, PaymentError::Sending (ref a, ) => { let mut a_nonref = Clone::clone(a); nativePaymentError::Sending ( @@ -482,11 +121,6 @@ impl PaymentError { a.into_str(), ) }, - PaymentError::Routing (mut a, ) => { - nativePaymentError::Routing ( - *unsafe { Box::from_raw(a.take_inner()) }, - ) - }, PaymentError::Sending (mut a, ) => { nativePaymentError::Sending ( a.into_native(), @@ -503,16 +137,10 @@ impl PaymentError { a_nonref.into(), ) }, - nativePaymentError::Routing (ref a, ) => { - let mut a_nonref = Clone::clone(a); - PaymentError::Routing ( - crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(a_nonref), is_owned: true }, - ) - }, nativePaymentError::Sending (ref a, ) => { let mut a_nonref = Clone::clone(a); PaymentError::Sending ( - crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(a_nonref), + crate::lightning::ln::outbound_payment::RetryableSendFailure::native_into(a_nonref), ) }, } @@ -525,14 +153,9 @@ impl PaymentError { a.into(), ) }, - nativePaymentError::Routing (mut a, ) => { - PaymentError::Routing ( - crate::lightning::ln::msgs::LightningError { inner: ObjOps::heap_alloc(a), is_owned: true }, - ) - }, nativePaymentError::Sending (mut a, ) => { PaymentError::Sending ( - crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(a), + crate::lightning::ln::outbound_payment::RetryableSendFailure::native_into(a), ) }, } @@ -552,158 +175,7 @@ pub extern "C" fn PaymentError_invoice(a: crate::c_types::Str) -> PaymentError { PaymentError::Invoice(a, ) } #[no_mangle] -/// Utility method to constructs a new Routing-variant PaymentError -pub extern "C" fn PaymentError_routing(a: crate::lightning::ln::msgs::LightningError) -> PaymentError { - PaymentError::Routing(a, ) -} -#[no_mangle] /// Utility method to constructs a new Sending-variant PaymentError -pub extern "C" fn PaymentError_sending(a: crate::lightning::ln::channelmanager::PaymentSendFailure) -> PaymentError { +pub extern "C" fn PaymentError_sending(a: crate::lightning::ln::outbound_payment::RetryableSendFailure) -> PaymentError { PaymentError::Sending(a, ) } -/// Creates an invoice payer that retries failed payment paths. -/// -/// Will forward any [`Event::PaymentPathFailed`] events to the decorated `event_handler` once -/// `retry` has been exceeded for a given [`Invoice`]. -#[must_use] -#[no_mangle] -pub extern "C" fn InvoicePayer_new(mut payer: crate::lightning_invoice::payment::Payer, mut router: crate::lightning::routing::router::Router, mut logger: crate::lightning::util::logger::Logger, mut event_handler: crate::lightning::util::events::EventHandler, mut retry: crate::lightning_invoice::payment::Retry) -> crate::lightning_invoice::payment::InvoicePayer { - let mut ret = lightning_invoice::payment::InvoicePayer::new(payer, router, logger, event_handler, retry.into_native()); - crate::lightning_invoice::payment::InvoicePayer { inner: ObjOps::heap_alloc(ret), is_owned: true } -} - -/// Pays the given [`Invoice`], caching it for later use in case a retry is needed. -/// -/// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long -/// as the payment is still pending. Once the payment completes or fails, you must ensure that -/// a second payment with the same [`PaymentHash`] is never sent. -/// -/// If you wish to use a different payment idempotency token, see -/// [`Self::pay_invoice_with_id`]. -#[must_use] -#[no_mangle] -pub extern "C" fn InvoicePayer_pay_invoice(this_arg: &crate::lightning_invoice::payment::InvoicePayer, invoice: &crate::lightning_invoice::Invoice) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_invoice(invoice.get_native_ref()); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; - local_ret -} - -/// Pays the given [`Invoice`] with a custom idempotency key, caching the invoice for later use -/// in case a retry is needed. -/// -/// Note that idempotency is only guaranteed as long as the payment is still pending. Once the -/// payment completes or fails, no idempotency guarantees are made. -/// -/// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`] -/// has never been paid before. -/// -/// See [`Self::pay_invoice`] for a variant which uses the [`PaymentHash`] for the idempotency -/// token. -#[must_use] -#[no_mangle] -pub extern "C" fn InvoicePayer_pay_invoice_with_id(this_arg: &crate::lightning_invoice::payment::InvoicePayer, invoice: &crate::lightning_invoice::Invoice, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentErrorZ { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_invoice_with_id(invoice.get_native_ref(), ::lightning::ln::channelmanager::PaymentId(payment_id.data)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; - local_ret -} - -/// Pays the given zero-value [`Invoice`] using the given amount, caching it for later use in -/// case a retry is needed. -/// -/// [`Invoice::payment_hash`] is used as the [`PaymentId`], which ensures idempotency as long -/// as the payment is still pending. Once the payment completes or fails, you must ensure that -/// a second payment with the same [`PaymentHash`] is never sent. -/// -/// If you wish to use a different payment idempotency token, see -/// [`Self::pay_zero_value_invoice_with_id`]. -#[must_use] -#[no_mangle] -pub extern "C" fn InvoicePayer_pay_zero_value_invoice(this_arg: &crate::lightning_invoice::payment::InvoicePayer, invoice: &crate::lightning_invoice::Invoice, mut amount_msats: u64) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_zero_value_invoice(invoice.get_native_ref(), amount_msats); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; - local_ret -} - -/// Pays the given zero-value [`Invoice`] using the given amount and custom idempotency key, -/// caching the invoice for later use in case a retry is needed. -/// -/// Note that idempotency is only guaranteed as long as the payment is still pending. Once the -/// payment completes or fails, no idempotency guarantees are made. -/// -/// You should ensure that the [`Invoice::payment_hash`] is unique and the same [`PaymentHash`] -/// has never been paid before. -/// -/// See [`Self::pay_zero_value_invoice`] for a variant which uses the [`PaymentHash`] for the -/// idempotency token. -#[must_use] -#[no_mangle] -pub extern "C" fn InvoicePayer_pay_zero_value_invoice_with_id(this_arg: &crate::lightning_invoice::payment::InvoicePayer, invoice: &crate::lightning_invoice::Invoice, mut amount_msats: u64, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentErrorZ { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_zero_value_invoice_with_id(invoice.get_native_ref(), amount_msats, ::lightning::ln::channelmanager::PaymentId(payment_id.data)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; - local_ret -} - -/// Pays `pubkey` an amount using the hash of the given preimage, caching it for later use in -/// case a retry is needed. -/// -/// The hash of the [`PaymentPreimage`] is used as the [`PaymentId`], which ensures idempotency -/// as long as the payment is still pending. Once the payment completes or fails, you must -/// ensure that a second payment with the same [`PaymentPreimage`] is never sent. -#[must_use] -#[no_mangle] -pub extern "C" fn InvoicePayer_pay_pubkey(this_arg: &crate::lightning_invoice::payment::InvoicePayer, mut pubkey: crate::c_types::PublicKey, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut amount_msats: u64, mut final_cltv_expiry_delta: u32) -> crate::c_types::derived::CResult_PaymentIdPaymentErrorZ { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_pubkey(pubkey.into_rust(), ::lightning::ln::PaymentPreimage(payment_preimage.data), amount_msats, final_cltv_expiry_delta); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::c_types::ThirtyTwoBytes { data: o.0 } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; - local_ret -} - -/// Pays `pubkey` an amount using the hash of the given preimage and a custom idempotency key, -/// caching the invoice for later use in case a retry is needed. -/// -/// Note that idempotency is only guaranteed as long as the payment is still pending. Once the -/// payment completes or fails, no idempotency guarantees are made. -/// -/// You should ensure that the [`PaymentPreimage`] is unique and the corresponding -/// [`PaymentHash`] has never been paid before. -#[must_use] -#[no_mangle] -pub extern "C" fn InvoicePayer_pay_pubkey_with_id(this_arg: &crate::lightning_invoice::payment::InvoicePayer, mut pubkey: crate::c_types::PublicKey, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut payment_id: crate::c_types::ThirtyTwoBytes, mut amount_msats: u64, mut final_cltv_expiry_delta: u32) -> crate::c_types::derived::CResult_NonePaymentErrorZ { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.pay_pubkey_with_id(pubkey.into_rust(), ::lightning::ln::PaymentPreimage(payment_preimage.data), ::lightning::ln::channelmanager::PaymentId(payment_id.data), amount_msats, final_cltv_expiry_delta); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::payment::PaymentError::native_into(e) }).into() }; - local_ret -} - -/// Removes the payment cached by the given payment hash. -/// -/// Should be called once a payment has failed or succeeded if not using [`InvoicePayer`] as an -/// [`EventHandler`]. Otherwise, calling this method is unnecessary. -#[no_mangle] -pub extern "C" fn InvoicePayer_remove_cached_payment(this_arg: &crate::lightning_invoice::payment::InvoicePayer, payment_hash: *const [u8; 32]) { - unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.remove_cached_payment(&::lightning::ln::PaymentHash(unsafe { *payment_hash })) -} - -impl From for crate::lightning::util::events::EventHandler { - fn from(obj: nativeInvoicePayer) -> Self { - let mut rust_obj = InvoicePayer { inner: ObjOps::heap_alloc(obj), is_owned: true }; - let mut ret = InvoicePayer_as_EventHandler(&rust_obj); - // 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 - rust_obj.inner = core::ptr::null_mut(); - ret.free = Some(InvoicePayer_free_void); - ret - } -} -/// Constructs a new EventHandler which calls the relevant methods on this_arg. -/// This copies the `inner` pointer in this_arg and thus the returned EventHandler must be freed before this_arg is -#[no_mangle] -pub extern "C" fn InvoicePayer_as_EventHandler(this_arg: &InvoicePayer) -> crate::lightning::util::events::EventHandler { - crate::lightning::util::events::EventHandler { - this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, - free: None, - handle_event: InvoicePayer_EventHandler_handle_event, - } -} - -extern "C" fn InvoicePayer_EventHandler_handle_event(this_arg: *const c_void, mut event: crate::lightning::util::events::Event) { - >::handle_event(unsafe { &mut *(this_arg as *mut nativeInvoicePayer) }, event.into_native()) -} - diff --git a/lightning-c-bindings/src/lightning_invoice/utils.rs b/lightning-c-bindings/src/lightning_invoice/utils.rs index b0d33ab..6bc7bea 100644 --- a/lightning-c-bindings/src/lightning_invoice/utils.rs +++ b/lightning-c-bindings/src/lightning_invoice/utils.rs @@ -35,8 +35,15 @@ use alloc::{vec::Vec, boxed::Box}; /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. +/// +/// `duration_since_epoch` is the current time since epoch in seconds. /// -/// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom +/// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to +/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`] - 3. +/// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block +/// confirmations during routing. +/// +/// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this /// requirement). /// @@ -45,14 +52,19 @@ use alloc::{vec::Vec, boxed::Box}; /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels +/// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA +/// +/// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not +/// available and the current time is supplied by the caller. /// /// Note that payment_hash (or a relevant inner pointer) may be NULL or all-0s to represent None #[no_mangle] -pub extern "C" fn create_phantom_invoice(mut amt_msat: crate::c_types::derived::COption_u64Z, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut description: crate::c_types::Str, mut invoice_expiry_delta_secs: u32, mut phantom_route_hints: crate::c_types::derived::CVec_PhantomRouteHintsZ, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { +pub extern "C" fn create_phantom_invoice(mut amt_msat: crate::c_types::derived::COption_u64Z, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut description: crate::c_types::Str, mut invoice_expiry_delta_secs: u32, mut phantom_route_hints: crate::c_types::derived::CVec_PhantomRouteHintsZ, mut entropy_source: crate::lightning::chain::keysinterface::EntropySource, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z, mut duration_since_epoch: u64) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { let mut local_amt_msat = if amt_msat.is_some() { Some( { amt_msat.take() }) } else { None }; let mut local_payment_hash = if payment_hash.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentHash(payment_hash.data) }) }; let mut local_phantom_route_hints = Vec::new(); for mut item in phantom_route_hints.into_rust().drain(..) { local_phantom_route_hints.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; - let mut ret = lightning_invoice::utils::create_phantom_invoice::(local_amt_msat, local_payment_hash, description.into_string(), invoice_expiry_delta_secs, local_phantom_route_hints, keys_manager, logger, network.into_native()); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = lightning_invoice::utils::create_phantom_invoice::(local_amt_msat, local_payment_hash, description.into_string(), invoice_expiry_delta_secs, local_phantom_route_hints, entropy_source, node_signer, logger, network.into_native(), local_min_final_cltv_expiry_delta, core::time::Duration::from_secs(duration_since_epoch)); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; local_ret } @@ -78,8 +90,10 @@ pub extern "C" fn create_phantom_invoice(mut amt_msat: crate::c_types::derived:: /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. +/// +/// `duration_since_epoch` is the current time since epoch in seconds. /// -/// Note that the provided `keys_manager`'s `KeysInterface` implementation must support phantom +/// Note that the provided `keys_manager`'s `NodeSigner` implementation must support phantom /// invoices in its `sign_invoice` implementation ([`PhantomKeysManager`] satisfies this /// requirement). /// @@ -88,14 +102,18 @@ pub extern "C" fn create_phantom_invoice(mut amt_msat: crate::c_types::derived:: /// [`ChannelManager::create_inbound_payment`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment /// [`ChannelManager::create_inbound_payment_for_hash`]: lightning::ln::channelmanager::ChannelManager::create_inbound_payment_for_hash /// [`PhantomRouteHints::channels`]: lightning::ln::channelmanager::PhantomRouteHints::channels +/// +/// This can be used in a `no_std` environment, where [`std::time::SystemTime`] is not +/// available and the current time is supplied by the caller. /// /// Note that payment_hash (or a relevant inner pointer) may be NULL or all-0s to represent None #[no_mangle] -pub extern "C" fn create_phantom_invoice_with_description_hash(mut amt_msat: crate::c_types::derived::COption_u64Z, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut invoice_expiry_delta_secs: u32, mut description_hash: crate::lightning_invoice::Sha256, mut phantom_route_hints: crate::c_types::derived::CVec_PhantomRouteHintsZ, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { +pub extern "C" fn create_phantom_invoice_with_description_hash(mut amt_msat: crate::c_types::derived::COption_u64Z, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut invoice_expiry_delta_secs: u32, mut description_hash: crate::lightning_invoice::Sha256, mut phantom_route_hints: crate::c_types::derived::CVec_PhantomRouteHintsZ, mut entropy_source: crate::lightning::chain::keysinterface::EntropySource, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z, mut duration_since_epoch: u64) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { let mut local_amt_msat = if amt_msat.is_some() { Some( { amt_msat.take() }) } else { None }; let mut local_payment_hash = if payment_hash.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentHash(payment_hash.data) }) }; let mut local_phantom_route_hints = Vec::new(); for mut item in phantom_route_hints.into_rust().drain(..) { local_phantom_route_hints.push( { *unsafe { Box::from_raw(item.take_inner()) } }); }; - let mut ret = lightning_invoice::utils::create_phantom_invoice_with_description_hash::(local_amt_msat, local_payment_hash, invoice_expiry_delta_secs, *unsafe { Box::from_raw(description_hash.take_inner()) }, local_phantom_route_hints, keys_manager, logger, network.into_native()); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = lightning_invoice::utils::create_phantom_invoice_with_description_hash::(local_amt_msat, local_payment_hash, invoice_expiry_delta_secs, *unsafe { Box::from_raw(description_hash.take_inner()) }, local_phantom_route_hints, entropy_source, node_signer, logger, network.into_native(), local_min_final_cltv_expiry_delta, core::time::Duration::from_secs(duration_since_epoch)); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; local_ret } @@ -108,10 +126,18 @@ pub extern "C" fn create_phantom_invoice_with_description_hash(mut amt_msat: cra /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. +/// +/// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to +/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. +/// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block +/// confirmations during routing. +/// +/// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA #[no_mangle] -pub extern "C" fn create_invoice_from_channelmanager(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description: crate::c_types::Str, mut invoice_expiry_delta_secs: u32) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { +pub extern "C" fn create_invoice_from_channelmanager(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description: crate::c_types::Str, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { let mut local_amt_msat = if amt_msat.is_some() { Some( { amt_msat.take() }) } else { None }; - let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager::(channelmanager.get_native_ref(), keys_manager, logger, network.into_native(), local_amt_msat, description.into_string(), invoice_expiry_delta_secs); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager::(channelmanager.get_native_ref(), node_signer, logger, network.into_native(), local_amt_msat, description.into_string(), invoice_expiry_delta_secs, local_min_final_cltv_expiry_delta); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; local_ret } @@ -125,10 +151,18 @@ pub extern "C" fn create_invoice_from_channelmanager(channelmanager: &crate::lig /// /// `invoice_expiry_delta_secs` describes the number of seconds that the invoice is valid for /// in excess of the current time. +/// +/// You can specify a custom `min_final_cltv_expiry_delta`, or let LDK default it to +/// [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. The provided expiry must be at least [`MIN_FINAL_CLTV_EXPIRY_DELTA`]. +/// Note that LDK will add a buffer of 3 blocks to the delta to allow for up to a few new block +/// confirmations during routing. +/// +/// [`MIN_FINAL_CLTV_EXPIRY_DETLA`]: lightning::ln::channelmanager::MIN_FINAL_CLTV_EXPIRY_DELTA #[no_mangle] -pub extern "C" fn create_invoice_from_channelmanager_with_description_hash(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description_hash: crate::lightning_invoice::Sha256, mut invoice_expiry_delta_secs: u32) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { +pub extern "C" fn create_invoice_from_channelmanager_with_description_hash(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description_hash: crate::lightning_invoice::Sha256, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { let mut local_amt_msat = if amt_msat.is_some() { Some( { amt_msat.take() }) } else { None }; - let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager_with_description_hash::(channelmanager.get_native_ref(), keys_manager, logger, network.into_native(), local_amt_msat, *unsafe { Box::from_raw(description_hash.take_inner()) }, invoice_expiry_delta_secs); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager_with_description_hash::(channelmanager.get_native_ref(), node_signer, logger, network.into_native(), local_amt_msat, *unsafe { Box::from_raw(description_hash.take_inner()) }, invoice_expiry_delta_secs, local_min_final_cltv_expiry_delta); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; local_ret } @@ -137,9 +171,10 @@ pub extern "C" fn create_invoice_from_channelmanager_with_description_hash(chann /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not /// available and the current time is supplied by the caller. #[no_mangle] -pub extern "C" fn create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description_hash: crate::lightning_invoice::Sha256, mut duration_since_epoch: u64, mut invoice_expiry_delta_secs: u32) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { +pub extern "C" fn create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description_hash: crate::lightning_invoice::Sha256, mut duration_since_epoch: u64, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { let mut local_amt_msat = if amt_msat.is_some() { Some( { amt_msat.take() }) } else { None }; - let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch::(channelmanager.get_native_ref(), keys_manager, logger, network.into_native(), local_amt_msat, *unsafe { Box::from_raw(description_hash.take_inner()) }, core::time::Duration::from_secs(duration_since_epoch), invoice_expiry_delta_secs); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager_with_description_hash_and_duration_since_epoch::(channelmanager.get_native_ref(), node_signer, logger, network.into_native(), local_amt_msat, *unsafe { Box::from_raw(description_hash.take_inner()) }, core::time::Duration::from_secs(duration_since_epoch), invoice_expiry_delta_secs, local_min_final_cltv_expiry_delta); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; local_ret } @@ -148,9 +183,10 @@ pub extern "C" fn create_invoice_from_channelmanager_with_description_hash_and_d /// This version can be used in a `no_std` environment, where [`std::time::SystemTime`] is not /// available and the current time is supplied by the caller. #[no_mangle] -pub extern "C" fn create_invoice_from_channelmanager_and_duration_since_epoch(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description: crate::c_types::Str, mut duration_since_epoch: u64, mut invoice_expiry_delta_secs: u32) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { +pub extern "C" fn create_invoice_from_channelmanager_and_duration_since_epoch(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description: crate::c_types::Str, mut duration_since_epoch: u64, mut invoice_expiry_delta_secs: u32, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { let mut local_amt_msat = if amt_msat.is_some() { Some( { amt_msat.take() }) } else { None }; - let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager_and_duration_since_epoch::(channelmanager.get_native_ref(), keys_manager, logger, network.into_native(), local_amt_msat, description.into_string(), core::time::Duration::from_secs(duration_since_epoch), invoice_expiry_delta_secs); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager_and_duration_since_epoch::(channelmanager.get_native_ref(), node_signer, logger, network.into_native(), local_amt_msat, description.into_string(), core::time::Duration::from_secs(duration_since_epoch), invoice_expiry_delta_secs, local_min_final_cltv_expiry_delta); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; local_ret } @@ -160,79 +196,11 @@ pub extern "C" fn create_invoice_from_channelmanager_and_duration_since_epoch(ch /// This may be useful if you're building an on-chain swap or involving another protocol where /// the payment hash is also involved outside the scope of lightning. #[no_mangle] -pub extern "C" fn create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description: crate::c_types::Str, mut duration_since_epoch: u64, mut invoice_expiry_delta_secs: u32, mut payment_hash: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { +pub extern "C" fn create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash(channelmanager: &crate::lightning::ln::channelmanager::ChannelManager, mut node_signer: crate::lightning::chain::keysinterface::NodeSigner, mut logger: crate::lightning::util::logger::Logger, mut network: crate::lightning_invoice::Currency, mut amt_msat: crate::c_types::derived::COption_u64Z, mut description: crate::c_types::Str, mut duration_since_epoch: u64, mut invoice_expiry_delta_secs: u32, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut min_final_cltv_expiry_delta: crate::c_types::derived::COption_u16Z) -> crate::c_types::derived::CResult_InvoiceSignOrCreationErrorZ { let mut local_amt_msat = if amt_msat.is_some() { Some( { amt_msat.take() }) } else { None }; - let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash::(channelmanager.get_native_ref(), keys_manager, logger, network.into_native(), local_amt_msat, description.into_string(), core::time::Duration::from_secs(duration_since_epoch), invoice_expiry_delta_secs, ::lightning::ln::PaymentHash(payment_hash.data)); + let mut local_min_final_cltv_expiry_delta = if min_final_cltv_expiry_delta.is_some() { Some( { min_final_cltv_expiry_delta.take() }) } else { None }; + let mut ret = lightning_invoice::utils::create_invoice_from_channelmanager_and_duration_since_epoch_with_payment_hash::(channelmanager.get_native_ref(), node_signer, logger, network.into_native(), local_amt_msat, description.into_string(), core::time::Duration::from_secs(duration_since_epoch), invoice_expiry_delta_secs, ::lightning::ln::PaymentHash(payment_hash.data), local_min_final_cltv_expiry_delta); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning_invoice::Invoice { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_invoice::SignOrCreationError::native_into(e) }).into() }; local_ret } -impl From for crate::lightning_invoice::payment::Payer { - fn from(obj: nativeChannelManager) -> Self { - let mut rust_obj = ChannelManager { inner: ObjOps::heap_alloc(obj), is_owned: true }; - let mut ret = ChannelManager_as_Payer(&rust_obj); - // 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 - rust_obj.inner = core::ptr::null_mut(); - ret.free = Some(ChannelManager_free_void); - ret - } -} -/// Constructs a new Payer which calls the relevant methods on this_arg. -/// This copies the `inner` pointer in this_arg and thus the returned Payer must be freed before this_arg is -#[no_mangle] -pub extern "C" fn ChannelManager_as_Payer(this_arg: &ChannelManager) -> crate::lightning_invoice::payment::Payer { - crate::lightning_invoice::payment::Payer { - this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void }, - free: None, - node_id: ChannelManager_Payer_node_id, - first_hops: ChannelManager_Payer_first_hops, - send_payment: ChannelManager_Payer_send_payment, - send_spontaneous_payment: ChannelManager_Payer_send_spontaneous_payment, - retry_payment: ChannelManager_Payer_retry_payment, - abandon_payment: ChannelManager_Payer_abandon_payment, - inflight_htlcs: ChannelManager_Payer_inflight_htlcs, - } -} - -#[must_use] -extern "C" fn ChannelManager_Payer_node_id(this_arg: *const c_void) -> crate::c_types::PublicKey { - let mut ret = >::node_id(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ); - crate::c_types::PublicKey::from_rust(&ret) -} -#[must_use] -extern "C" fn ChannelManager_Payer_first_hops(this_arg: *const c_void) -> crate::c_types::derived::CVec_ChannelDetailsZ { - let mut ret = >::first_hops(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ); - let mut local_ret = Vec::new(); for mut item in ret.drain(..) { local_ret.push( { crate::lightning::ln::channelmanager::ChannelDetails { inner: ObjOps::heap_alloc(item), is_owned: true } }); }; - local_ret.into() -} -#[must_use] -extern "C" fn ChannelManager_Payer_send_payment(this_arg: *const c_void, route: &crate::lightning::routing::router::Route, mut payment_hash: crate::c_types::ThirtyTwoBytes, mut payment_secret: crate::c_types::ThirtyTwoBytes, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ { - let mut local_payment_secret = if payment_secret.data == [0; 32] { None } else { Some( { ::lightning::ln::PaymentSecret(payment_secret.data) }) }; - let mut ret = >::send_payment(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, route.get_native_ref(), ::lightning::ln::PaymentHash(payment_hash.data), &local_payment_secret, ::lightning::ln::channelmanager::PaymentId(payment_id.data)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; - local_ret -} -#[must_use] -extern "C" fn ChannelManager_Payer_send_spontaneous_payment(this_arg: *const c_void, route: &crate::lightning::routing::router::Route, mut payment_preimage: crate::c_types::ThirtyTwoBytes, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ { - let mut ret = >::send_spontaneous_payment(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, route.get_native_ref(), ::lightning::ln::PaymentPreimage(payment_preimage.data), ::lightning::ln::channelmanager::PaymentId(payment_id.data)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; - local_ret -} -#[must_use] -extern "C" fn ChannelManager_Payer_retry_payment(this_arg: *const c_void, route: &crate::lightning::routing::router::Route, mut payment_id: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NonePaymentSendFailureZ { - let mut ret = >::retry_payment(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, route.get_native_ref(), ::lightning::ln::channelmanager::PaymentId(payment_id.data)); - let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { () /*o*/ }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::channelmanager::PaymentSendFailure::native_into(e) }).into() }; - local_ret -} -extern "C" fn ChannelManager_Payer_abandon_payment(this_arg: *const c_void, mut payment_id: crate::c_types::ThirtyTwoBytes) { - >::abandon_payment(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ::lightning::ln::channelmanager::PaymentId(payment_id.data)) -} -#[must_use] -extern "C" fn ChannelManager_Payer_inflight_htlcs(this_arg: *const c_void) -> crate::lightning::routing::router::InFlightHtlcs { - let mut ret = >::inflight_htlcs(unsafe { &mut *(this_arg as *mut nativeChannelManager) }, ); - crate::lightning::routing::router::InFlightHtlcs { inner: ObjOps::heap_alloc(ret), is_owned: true } -} - -use crate::lightning::ln::channelmanager::nativeChannelManager as nativeChannelManager; -use crate::lightning::ln::channelmanager::ChannelManager; -use crate::lightning::ln::channelmanager::ChannelManager_free_void; diff --git a/lightning-c-bindings/src/lightning_persister.rs b/lightning-c-bindings/src/lightning_persister.rs index 3f6892e..5af129e 100644 --- a/lightning-c-bindings/src/lightning_persister.rs +++ b/lightning-c-bindings/src/lightning_persister.rs @@ -109,8 +109,8 @@ pub extern "C" fn FilesystemPersister_get_data_dir(this_arg: &crate::lightning_p /// Read `ChannelMonitor`s from disk. #[must_use] #[no_mangle] -pub extern "C" fn FilesystemPersister_read_channelmonitors(this_arg: &crate::lightning_persister::FilesystemPersister, mut keys_manager: crate::lightning::chain::keysinterface::KeysInterface) -> crate::c_types::derived::CResult_CVec_C2Tuple_BlockHashChannelMonitorZZErrorZ { - let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.read_channelmonitors(keys_manager); +pub extern "C" fn FilesystemPersister_read_channelmonitors(this_arg: &crate::lightning_persister::FilesystemPersister, mut entropy_source: crate::lightning::chain::keysinterface::EntropySource, signer_provider: &crate::lightning::chain::keysinterface::SignerProvider) -> crate::c_types::derived::CResult_CVec_C2Tuple_BlockHashChannelMonitorZZErrorZ { + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.read_channelmonitors(entropy_source, signer_provider); let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { let mut local_ret_0 = Vec::new(); for mut item in o.drain(..) { local_ret_0.push( { let (mut orig_ret_0_0_0, mut orig_ret_0_0_1) = item; let mut local_ret_0_0 = (crate::c_types::ThirtyTwoBytes { data: orig_ret_0_0_0.into_inner() }, crate::lightning::chain::channelmonitor::ChannelMonitor { inner: ObjOps::heap_alloc(orig_ret_0_0_1), is_owned: true }).into(); local_ret_0_0 }); }; local_ret_0.into() }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::c_types::IOError::from_rust(e) }).into() }; local_ret } diff --git a/lightning-c-bindings/src/lightning_rapid_gossip_sync/mod.rs b/lightning-c-bindings/src/lightning_rapid_gossip_sync/mod.rs index 66c8f7e..fb40cca 100644 --- a/lightning-c-bindings/src/lightning_rapid_gossip_sync/mod.rs +++ b/lightning-c-bindings/src/lightning_rapid_gossip_sync/mod.rs @@ -49,9 +49,8 @@ //! # } //! # let logger = FakeLogger {}; //! -//! let block_hash = genesis_block(Network::Bitcoin).header.block_hash(); -//! let network_graph = NetworkGraph::new(block_hash, &logger); -//! let rapid_sync = RapidGossipSync::new(&network_graph); +//! let network_graph = NetworkGraph::new(Network::Bitcoin, &logger); +//! let rapid_sync = RapidGossipSync::new(&network_graph, &logger); //! let snapshot_contents: &[u8] = &[0; 0]; //! let new_last_sync_timestamp_result = rapid_sync.update_network_graph(snapshot_contents); //! ``` @@ -134,16 +133,14 @@ impl RapidGossipSync { /// Instantiate a new [`RapidGossipSync`] instance. #[must_use] #[no_mangle] -pub extern "C" fn RapidGossipSync_new(network_graph: &crate::lightning::routing::gossip::NetworkGraph) -> crate::lightning_rapid_gossip_sync::RapidGossipSync { - let mut ret = lightning_rapid_gossip_sync::RapidGossipSync::new(network_graph.get_native_ref()); +pub extern "C" fn RapidGossipSync_new(network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning_rapid_gossip_sync::RapidGossipSync { + let mut ret = lightning_rapid_gossip_sync::RapidGossipSync::new(network_graph.get_native_ref(), logger); crate::lightning_rapid_gossip_sync::RapidGossipSync { inner: ObjOps::heap_alloc(ret), is_owned: true } } /// Update network graph from binary data. /// Returns the last sync timestamp to be used the next time rapid sync data is queried. /// -/// `network_graph`: network graph to be updated -/// /// `update_data`: `&[u8]` binary stream that comprises the update data #[must_use] #[no_mangle] @@ -153,6 +150,20 @@ pub extern "C" fn RapidGossipSync_update_network_graph(this_arg: &crate::lightni local_ret } +/// Update network graph from binary data. +/// Returns the last sync timestamp to be used the next time rapid sync data is queried. +/// +/// `update_data`: `&[u8]` binary stream that comprises the update data +/// `current_time_unix`: `Option` optional current timestamp to verify data age +#[must_use] +#[no_mangle] +pub extern "C" fn RapidGossipSync_update_network_graph_no_std(this_arg: &crate::lightning_rapid_gossip_sync::RapidGossipSync, mut update_data: crate::c_types::u8slice, mut current_time_unix: crate::c_types::derived::COption_u64Z) -> crate::c_types::derived::CResult_u32GraphSyncErrorZ { + let mut local_current_time_unix = if current_time_unix.is_some() { Some( { current_time_unix.take() }) } else { None }; + let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.update_network_graph_no_std(update_data.to_slice(), local_current_time_unix); + let mut local_ret = match ret { Ok(mut o) => crate::c_types::CResultTempl::ok( { o }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning_rapid_gossip_sync::error::GraphSyncError::native_into(e) }).into() }; + local_ret +} + /// Returns whether a rapid gossip sync has completed at least once. #[must_use] #[no_mangle] -- 2.30.2