Merge pull request #60 from TheBlueMatt/main
[ldk-c-bindings] / lightning-c-bindings / src / lightning / ln / chan_utils.rs
index 02f7f7b6a2cec40d1b45742b8d159fca6ffd3310..225dfbb3d8c02d1f1c1f7e2303d69f99dc48e40a 100644 (file)
@@ -9,11 +9,13 @@
 //! Various utilities for building scripts and deriving keys related to channels. These are
 //! largely of interest for those implementing chain::keysinterface::Sign message signing by hand.
 
-use std::str::FromStr;
-use std::ffi::c_void;
+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};
 
 /// Gets the weight for an HTLC-Success transaction.
 #[no_mangle]
@@ -43,6 +45,135 @@ pub extern "C" fn build_closing_transaction(mut to_holder_value_sat: u64, mut to
        crate::c_types::Transaction::from_bitcoin(&ret)
 }
 
+
+use lightning::ln::chan_utils::CounterpartyCommitmentSecrets as nativeCounterpartyCommitmentSecretsImport;
+pub(crate) type nativeCounterpartyCommitmentSecrets = nativeCounterpartyCommitmentSecretsImport;
+
+/// Implements the per-commitment secret storage scheme from
+/// [BOLT 3](https://github.com/lightningnetwork/lightning-rfc/blob/dcbf8583976df087c79c3ce0b535311212e6812d/03-transactions.md#efficient-per-commitment-secret-storage).
+///
+/// Allows us to keep track of all of the revocation secrets of our counterparty in just 50*32 bytes
+/// or so.
+#[must_use]
+#[repr(C)]
+pub struct CounterpartyCommitmentSecrets {
+       /// 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 nativeCounterpartyCommitmentSecrets,
+       /// 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 CounterpartyCommitmentSecrets {
+       fn drop(&mut self) {
+               if self.is_owned && !<*mut nativeCounterpartyCommitmentSecrets>::is_null(self.inner) {
+                       let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
+               }
+       }
+}
+/// Frees any resources used by the CounterpartyCommitmentSecrets, if is_owned is set and inner is non-NULL.
+#[no_mangle]
+pub extern "C" fn CounterpartyCommitmentSecrets_free(this_obj: CounterpartyCommitmentSecrets) { }
+#[allow(unused)]
+/// Used only if an object of this type is returned as a trait impl by a method
+pub(crate) extern "C" fn CounterpartyCommitmentSecrets_free_void(this_ptr: *mut c_void) {
+       unsafe { let _ = Box::from_raw(this_ptr as *mut nativeCounterpartyCommitmentSecrets); }
+}
+#[allow(unused)]
+impl CounterpartyCommitmentSecrets {
+       pub(crate) fn get_native_ref(&self) -> &'static nativeCounterpartyCommitmentSecrets {
+               unsafe { &*ObjOps::untweak_ptr(self.inner) }
+       }
+       pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeCounterpartyCommitmentSecrets {
+               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 nativeCounterpartyCommitmentSecrets {
+               assert!(self.is_owned);
+               let ret = ObjOps::untweak_ptr(self.inner);
+               self.inner = core::ptr::null_mut();
+               ret
+       }
+}
+impl Clone for CounterpartyCommitmentSecrets {
+       fn clone(&self) -> Self {
+               Self {
+                       inner: if <*mut nativeCounterpartyCommitmentSecrets>::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 CounterpartyCommitmentSecrets_clone_void(this_ptr: *const c_void) -> *mut c_void {
+       Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeCounterpartyCommitmentSecrets)).clone() })) as *mut c_void
+}
+#[no_mangle]
+/// Creates a copy of the CounterpartyCommitmentSecrets
+pub extern "C" fn CounterpartyCommitmentSecrets_clone(orig: &CounterpartyCommitmentSecrets) -> CounterpartyCommitmentSecrets {
+       orig.clone()
+}
+/// Creates a new empty `CounterpartyCommitmentSecrets` structure.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn CounterpartyCommitmentSecrets_new() -> CounterpartyCommitmentSecrets {
+       let mut ret = lightning::ln::chan_utils::CounterpartyCommitmentSecrets::new();
+       CounterpartyCommitmentSecrets { inner: ObjOps::heap_alloc(ret), is_owned: true }
+}
+
+/// Returns the minimum index of all stored secrets. Note that indexes start
+/// at 1 << 48 and get decremented by one for each new secret.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn CounterpartyCommitmentSecrets_get_min_seen_secret(this_arg: &CounterpartyCommitmentSecrets) -> u64 {
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_min_seen_secret();
+       ret
+}
+
+/// Inserts the `secret` at `idx`. Returns `Ok(())` if the secret
+/// was generated in accordance with BOLT 3 and is consistent with previous secrets.
+#[must_use]
+#[no_mangle]
+pub extern "C" fn CounterpartyCommitmentSecrets_provide_secret(this_arg: &mut CounterpartyCommitmentSecrets, mut idx: u64, mut secret: crate::c_types::ThirtyTwoBytes) -> crate::c_types::derived::CResult_NoneNoneZ {
+       let mut ret = unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut nativeCounterpartyCommitmentSecrets)) }.provide_secret(idx, secret.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( { () /*e*/ }).into() };
+       local_ret
+}
+
+/// Returns the secret at `idx`.
+/// Returns `None` if `idx` is < [`CounterpartyCommitmentSecrets::get_min_seen_secret`].
+///
+/// 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 CounterpartyCommitmentSecrets_get_secret(this_arg: &CounterpartyCommitmentSecrets, mut idx: u64) -> crate::c_types::ThirtyTwoBytes {
+       let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.get_secret(idx);
+       let mut local_ret = if ret.is_none() { crate::c_types::ThirtyTwoBytes { data: [0; 32] } } else {  { crate::c_types::ThirtyTwoBytes { data: (ret.unwrap()) } } };
+       local_ret
+}
+
+#[no_mangle]
+/// Serialize the CounterpartyCommitmentSecrets object into a byte array which can be read by CounterpartyCommitmentSecrets_read
+pub extern "C" fn CounterpartyCommitmentSecrets_write(obj: &CounterpartyCommitmentSecrets) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
+}
+#[no_mangle]
+pub(crate) extern "C" fn CounterpartyCommitmentSecrets_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
+       crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeCounterpartyCommitmentSecrets) })
+}
+#[no_mangle]
+/// Read a CounterpartyCommitmentSecrets from a byte array, created by CounterpartyCommitmentSecrets_write
+pub extern "C" fn CounterpartyCommitmentSecrets_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_CounterpartyCommitmentSecretsDecodeErrorZ {
+       let res: Result<lightning::ln::chan_utils::CounterpartyCommitmentSecrets, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
+       let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::ln::chan_utils::CounterpartyCommitmentSecrets { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
+       local_res
+}
 /// Derives a per-commitment-transaction private key (eg an htlc key or delayed_payment key)
 /// from the base secret and the per_commitment_point.
 ///
@@ -159,7 +290,7 @@ impl TxCreationKeys {
        pub(crate) fn take_inner(mut self) -> *mut nativeTxCreationKeys {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -237,7 +368,7 @@ pub extern "C" fn TxCreationKeys_new(mut per_commitment_point_arg: crate::c_type
 impl Clone for TxCreationKeys {
        fn clone(&self) -> Self {
                Self {
-                       inner: if <*mut nativeTxCreationKeys>::is_null(self.inner) { std::ptr::null_mut() } else {
+                       inner: if <*mut nativeTxCreationKeys>::is_null(self.inner) { core::ptr::null_mut() } else {
                                ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
@@ -316,7 +447,7 @@ impl ChannelPublicKeys {
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelPublicKeys {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -408,7 +539,7 @@ pub extern "C" fn ChannelPublicKeys_new(mut funding_pubkey_arg: crate::c_types::
 impl Clone for ChannelPublicKeys {
        fn clone(&self) -> Self {
                Self {
-                       inner: if <*mut nativeChannelPublicKeys>::is_null(self.inner) { std::ptr::null_mut() } else {
+                       inner: if <*mut nativeChannelPublicKeys>::is_null(self.inner) { core::ptr::null_mut() } else {
                                ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
@@ -520,7 +651,7 @@ impl HTLCOutputInCommitment {
        pub(crate) fn take_inner(mut self) -> *mut nativeHTLCOutputInCommitment {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -609,7 +740,7 @@ pub extern "C" fn HTLCOutputInCommitment_new(mut offered_arg: bool, mut amount_m
 impl Clone for HTLCOutputInCommitment {
        fn clone(&self) -> Self {
                Self {
-                       inner: if <*mut nativeHTLCOutputInCommitment>::is_null(self.inner) { std::ptr::null_mut() } else {
+                       inner: if <*mut nativeHTLCOutputInCommitment>::is_null(self.inner) { core::ptr::null_mut() } else {
                                ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
@@ -733,7 +864,7 @@ impl ChannelTransactionParameters {
        pub(crate) fn take_inner(mut self) -> *mut nativeChannelTransactionParameters {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -779,7 +910,7 @@ pub extern "C" fn ChannelTransactionParameters_set_is_outbound_from_holder(this_
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_get_counterparty_parameters(this_ptr: &ChannelTransactionParameters) -> crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters {
        let mut inner_val = &mut this_ptr.get_native_mut_ref().counterparty_parameters;
-       let mut local_inner_val = crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::ln::chan_utils::CounterpartyChannelTransactionParameters<>) as *mut _ }, is_owned: false };
+       let mut local_inner_val = crate::lightning::ln::chan_utils::CounterpartyChannelTransactionParameters { 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::chan_utils::CounterpartyChannelTransactionParameters<>) as *mut _ }, is_owned: false };
        local_inner_val
 }
 /// The late-bound counterparty channel transaction parameters.
@@ -797,7 +928,7 @@ pub extern "C" fn ChannelTransactionParameters_set_counterparty_parameters(this_
 #[no_mangle]
 pub extern "C" fn ChannelTransactionParameters_get_funding_outpoint(this_ptr: &ChannelTransactionParameters) -> crate::lightning::chain::transaction::OutPoint {
        let mut inner_val = &mut this_ptr.get_native_mut_ref().funding_outpoint;
-       let mut local_inner_val = crate::lightning::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { std::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::chain::transaction::OutPoint<>) as *mut _ }, is_owned: false };
+       let mut local_inner_val = crate::lightning::chain::transaction::OutPoint { inner: unsafe { (if inner_val.is_none() { core::ptr::null() } else { ObjOps::nonnull_ptr_to_inner( { (inner_val.as_ref().unwrap()) }) } as *const lightning::chain::transaction::OutPoint<>) as *mut _ }, is_owned: false };
        local_inner_val
 }
 /// The late-bound funding outpoint
@@ -840,7 +971,7 @@ pub extern "C" fn ChannelTransactionParameters_new(mut holder_pubkeys_arg: crate
 impl Clone for ChannelTransactionParameters {
        fn clone(&self) -> Self {
                Self {
-                       inner: if <*mut nativeChannelTransactionParameters>::is_null(self.inner) { std::ptr::null_mut() } else {
+                       inner: if <*mut nativeChannelTransactionParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
                                ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
@@ -903,7 +1034,7 @@ impl CounterpartyChannelTransactionParameters {
        pub(crate) fn take_inner(mut self) -> *mut nativeCounterpartyChannelTransactionParameters {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -941,7 +1072,7 @@ pub extern "C" fn CounterpartyChannelTransactionParameters_new(mut pubkeys_arg:
 impl Clone for CounterpartyChannelTransactionParameters {
        fn clone(&self) -> Self {
                Self {
-                       inner: if <*mut nativeCounterpartyChannelTransactionParameters>::is_null(self.inner) { std::ptr::null_mut() } else {
+                       inner: if <*mut nativeCounterpartyChannelTransactionParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
                                ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
@@ -1070,7 +1201,7 @@ impl DirectedChannelTransactionParameters {
        pub(crate) fn take_inner(mut self) -> *mut nativeDirectedChannelTransactionParameters {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -1175,7 +1306,7 @@ impl HolderCommitmentTransaction {
        pub(crate) fn take_inner(mut self) -> *mut nativeHolderCommitmentTransaction {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -1199,7 +1330,7 @@ pub extern "C" fn HolderCommitmentTransaction_set_counterparty_htlc_sigs(this_pt
 impl Clone for HolderCommitmentTransaction {
        fn clone(&self) -> Self {
                Self {
-                       inner: if <*mut nativeHolderCommitmentTransaction>::is_null(self.inner) { std::ptr::null_mut() } else {
+                       inner: if <*mut nativeHolderCommitmentTransaction>::is_null(self.inner) { core::ptr::null_mut() } else {
                                ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
@@ -1288,7 +1419,7 @@ impl BuiltCommitmentTransaction {
        pub(crate) fn take_inner(mut self) -> *mut nativeBuiltCommitmentTransaction {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -1332,7 +1463,7 @@ pub extern "C" fn BuiltCommitmentTransaction_new(mut transaction_arg: crate::c_t
 impl Clone for BuiltCommitmentTransaction {
        fn clone(&self) -> Self {
                Self {
-                       inner: if <*mut nativeBuiltCommitmentTransaction>::is_null(self.inner) { std::ptr::null_mut() } else {
+                       inner: if <*mut nativeBuiltCommitmentTransaction>::is_null(self.inner) { core::ptr::null_mut() } else {
                                ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
@@ -1434,14 +1565,14 @@ impl ClosingTransaction {
        pub(crate) fn take_inner(mut self) -> *mut nativeClosingTransaction {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
 impl Clone for ClosingTransaction {
        fn clone(&self) -> Self {
                Self {
-                       inner: if <*mut nativeClosingTransaction>::is_null(self.inner) { std::ptr::null_mut() } else {
+                       inner: if <*mut nativeClosingTransaction>::is_null(self.inner) { core::ptr::null_mut() } else {
                                ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
@@ -1461,11 +1592,11 @@ pub extern "C" fn ClosingTransaction_clone(orig: &ClosingTransaction) -> Closing
 #[no_mangle]
 pub extern "C" fn ClosingTransaction_hash(o: &ClosingTransaction) -> u64 {
        if o.inner.is_null() { return 0; }
-       // Note that we'd love to use std::collections::hash_map::DefaultHasher but it's not in core
+       // 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();
-       std::hash::Hash::hash(o.get_native_ref(), &mut hasher);
-       std::hash::Hasher::finish(&hasher)
+       core::hash::Hash::hash(o.get_native_ref(), &mut hasher);
+       core::hash::Hasher::finish(&hasher)
 }
 /// Construct an object of the class
 #[must_use]
@@ -1586,7 +1717,7 @@ impl TrustedClosingTransaction {
        pub(crate) fn take_inner(mut self) -> *mut nativeTrustedClosingTransaction {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -1669,14 +1800,14 @@ impl CommitmentTransaction {
        pub(crate) fn take_inner(mut self) -> *mut nativeCommitmentTransaction {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
 impl Clone for CommitmentTransaction {
        fn clone(&self) -> Self {
                Self {
-                       inner: if <*mut nativeCommitmentTransaction>::is_null(self.inner) { std::ptr::null_mut() } else {
+                       inner: if <*mut nativeCommitmentTransaction>::is_null(self.inner) { core::ptr::null_mut() } else {
                                ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
                        is_owned: true,
                }
@@ -1819,7 +1950,7 @@ impl TrustedCommitmentTransaction {
        pub(crate) fn take_inner(mut self) -> *mut nativeTrustedCommitmentTransaction {
                assert!(self.is_owned);
                let ret = ObjOps::untweak_ptr(self.inner);
-               self.inner = std::ptr::null_mut();
+               self.inner = core::ptr::null_mut();
                ret
        }
 }
@@ -1859,6 +1990,8 @@ pub extern "C" fn TrustedCommitmentTransaction_opt_anchors(this_arg: &TrustedCom
 /// which HTLCOutputInCommitment::transaction_output_index.is_some()).
 ///
 /// The returned Vec has one entry for each HTLC, and in the same order.
+///
+/// This function is only valid in the holder commitment context, it always uses SigHashType::All.
 #[must_use]
 #[no_mangle]
 pub extern "C" fn TrustedCommitmentTransaction_get_htlc_sigs(this_arg: &TrustedCommitmentTransaction, htlc_base_key: *const [u8; 32], channel_parameters: &crate::lightning::ln::chan_utils::DirectedChannelTransactionParameters) -> crate::c_types::derived::CResult_CVec_SignatureZNoneZ {