Merge pull request #70 from TheBlueMatt/main
[ldk-c-bindings] / lightning-c-bindings / src / c_types / mod.rs
index c4113a9647cf20f64b09d11881a626992d884d55..1e88f0521e53c8ce56372278b3dcb17d3e4db3e5 100644 (file)
@@ -9,8 +9,42 @@ use bitcoin::secp256k1::key::PublicKey as SecpPublicKey;
 use bitcoin::secp256k1::key::SecretKey as SecpSecretKey;
 use bitcoin::secp256k1::Signature as SecpSignature;
 use bitcoin::secp256k1::Error as SecpError;
+use bitcoin::secp256k1::recovery::RecoveryId;
+use bitcoin::secp256k1::recovery::RecoverableSignature as SecpRecoverableSignature;
+use bitcoin::bech32;
 
-use std::convert::TryInto; // Bindings need at least rustc 1.34
+use core::convert::TryInto; // Bindings need at least rustc 1.34
+use core::ffi::c_void;
+
+#[cfg(feature = "std")]
+pub(crate) use std::io::{self, Cursor, Read};
+#[cfg(feature = "no-std")]
+pub(crate) use core2::io::{self, Cursor, Read};
+#[cfg(feature = "no-std")]
+use alloc::{boxed::Box, vec::Vec, string::String};
+
+#[repr(C)]
+/// A dummy struct of which an instance must never exist.
+/// This corresponds to the Rust type `Infallible`, or, in unstable rust, `!`
+pub struct NotConstructable {
+       _priv_thing: core::convert::Infallible,
+}
+impl From<core::convert::Infallible> for NotConstructable {
+       fn from(_: core::convert::Infallible) -> Self { unreachable!(); }
+}
+
+/// Integer in the range `0..32`
+#[derive(PartialEq, Eq, Copy, Clone)]
+#[allow(non_camel_case_types)]
+#[repr(C)]
+pub struct u5(u8);
+
+impl From<bech32::u5> for u5 {
+       fn from(o: bech32::u5) -> Self { Self(o.to_u8()) }
+}
+impl Into<bech32::u5> for u5 {
+       fn into(self) -> bech32::u5 { bech32::u5::try_from_u8(self.0).expect("u5 objects must be in the range 0..32") }
+}
 
 #[derive(Clone)]
 #[repr(C)]
@@ -33,6 +67,7 @@ impl PublicKey {
 }
 
 #[repr(C)]
+#[derive(Clone)]
 /// Represents a valid secp256k1 secret key serialized as a 32 byte array.
 pub struct SecretKey {
        /// The bytes of the secret key
@@ -72,6 +107,33 @@ impl Signature {
 }
 
 #[repr(C)]
+#[derive(Clone)]
+/// 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.
+pub struct RecoverableSignature {
+       /// The bytes of the signature in "compact" form plus a "Recovery ID" which allows for
+       /// recovery.
+       pub serialized_form: [u8; 68],
+}
+impl RecoverableSignature {
+       pub(crate) fn from_rust(pk: &SecpRecoverableSignature) -> Self {
+               let (id, compact_form) = pk.serialize_compact();
+               let mut serialized_form = [0; 68];
+               serialized_form[0..64].copy_from_slice(&compact_form[..]);
+               serialized_form[64..].copy_from_slice(&id.to_i32().to_le_bytes());
+               Self { serialized_form }
+       }
+       pub(crate) fn into_rust(&self) -> SecpRecoverableSignature {
+               let mut id = [0; 4];
+               id.copy_from_slice(&self.serialized_form[64..]);
+               SecpRecoverableSignature::from_compact(&self.serialized_form[0..64],
+                               RecoveryId::from_i32(i32::from_le_bytes(id)).expect("Invalid Recovery ID"))
+                       .unwrap()
+       }
+}
+
+#[repr(C)]
+#[derive(Copy, Clone)]
 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
 pub enum Secp256k1Error {
        /// Signature failed verification
@@ -107,10 +169,82 @@ impl Secp256k1Error {
                        SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
                }
        }
+       pub(crate) fn into_rust(self) -> SecpError {
+               match self {
+                       Secp256k1Error::IncorrectSignature => SecpError::IncorrectSignature,
+                       Secp256k1Error::InvalidMessage => SecpError::InvalidMessage,
+                       Secp256k1Error::InvalidPublicKey => SecpError::InvalidPublicKey,
+                       Secp256k1Error::InvalidSignature => SecpError::InvalidSignature,
+                       Secp256k1Error::InvalidSecretKey => SecpError::InvalidSecretKey,
+                       Secp256k1Error::InvalidRecoveryId => SecpError::InvalidRecoveryId,
+                       Secp256k1Error::InvalidTweak => SecpError::InvalidTweak,
+                       Secp256k1Error::TweakCheckFailed => SecpError::TweakCheckFailed,
+                       Secp256k1Error::NotEnoughMemory => SecpError::NotEnoughMemory,
+               }
+       }
+}
+
+#[repr(C)]
+#[derive(Copy, Clone)]
+/// Represents an error returned from the bech32 library during validation of some bech32 data
+pub enum Bech32Error {
+       /// String does not contain the separator character
+       MissingSeparator,
+       /// The checksum does not match the rest of the data
+       InvalidChecksum,
+       /// The data or human-readable part is too long or too short
+       InvalidLength,
+       /// Some part of the string contains an invalid character
+       InvalidChar(u32),
+       /// Some part of the data has an invalid value
+       InvalidData(u8),
+       /// The bit conversion failed due to a padding issue
+       InvalidPadding,
+       /// The whole string must be of one case
+       MixedCase,
+}
+impl Bech32Error {
+       pub(crate) fn from_rust(err: bech32::Error) -> Self {
+               match err {
+                       bech32::Error::MissingSeparator => Self::MissingSeparator,
+                       bech32::Error::InvalidChecksum => Self::InvalidChecksum,
+                       bech32::Error::InvalidLength => Self::InvalidLength,
+                       bech32::Error::InvalidChar(c) => Self::InvalidChar(c as u32),
+                       bech32::Error::InvalidData(d) => Self::InvalidData(d),
+                       bech32::Error::InvalidPadding => Self::InvalidPadding,
+                       bech32::Error::MixedCase => Self::MixedCase,
+               }
+       }
+       pub(crate) fn into_rust(self) -> bech32::Error {
+               match self {
+                       Self::MissingSeparator => bech32::Error::MissingSeparator,
+                       Self::InvalidChecksum => bech32::Error::InvalidChecksum,
+                       Self::InvalidLength => bech32::Error::InvalidLength,
+                       Self::InvalidChar(c) => bech32::Error::InvalidChar(core::char::from_u32(c).expect("Invalid UTF-8 character in Bech32Error::InvalidChar")),
+                       Self::InvalidData(d) => bech32::Error::InvalidData(d),
+                       Self::InvalidPadding => bech32::Error::InvalidPadding,
+                       Self::MixedCase => bech32::Error::MixedCase,
+               }
+       }
+}
+#[no_mangle]
+/// Creates a new Bech32Error which has the same data as `orig`
+pub extern "C" fn Bech32Error_clone(orig: &Bech32Error) -> Bech32Error { orig.clone() }
+#[no_mangle]
+/// Releases any memory held by the given `Bech32Error` (which is currently none)
+pub extern "C" fn Bech32Error_free(o: Bech32Error) { }
+
+#[repr(C)]
+#[derive(Clone, Copy, PartialEq)]
+/// Sub-errors which don't have specific information in them use this type.
+pub struct Error {
+       /// Zero-Sized_types aren't consistent across Rust/C/C++, so we add some size here
+       pub _dummy: u8,
 }
 
 #[repr(C)]
 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
+#[derive(Clone, Copy, PartialEq)]
 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
 pub enum IOError {
        NotFound,
@@ -132,6 +266,7 @@ pub enum IOError {
        Other,
        UnexpectedEof,
 }
+#[cfg(feature = "std")]
 impl IOError {
        pub(crate) fn from_rust(err: std::io::Error) -> Self {
                match err.kind() {
@@ -156,6 +291,28 @@ impl IOError {
                        _ => IOError::Other,
                }
        }
+       pub(crate) fn to_rust(&self) -> std::io::Error {
+               std::io::Error::new(match self {
+                       IOError::NotFound => std::io::ErrorKind::NotFound,
+                       IOError::PermissionDenied => std::io::ErrorKind::PermissionDenied,
+                       IOError::ConnectionRefused => std::io::ErrorKind::ConnectionRefused,
+                       IOError::ConnectionReset => std::io::ErrorKind::ConnectionReset,
+                       IOError::ConnectionAborted => std::io::ErrorKind::ConnectionAborted,
+                       IOError::NotConnected => std::io::ErrorKind::NotConnected,
+                       IOError::AddrInUse => std::io::ErrorKind::AddrInUse,
+                       IOError::AddrNotAvailable => std::io::ErrorKind::AddrNotAvailable,
+                       IOError::BrokenPipe => std::io::ErrorKind::BrokenPipe,
+                       IOError::AlreadyExists => std::io::ErrorKind::AlreadyExists,
+                       IOError::WouldBlock => std::io::ErrorKind::WouldBlock,
+                       IOError::InvalidInput => std::io::ErrorKind::InvalidInput,
+                       IOError::InvalidData => std::io::ErrorKind::InvalidData,
+                       IOError::TimedOut => std::io::ErrorKind::TimedOut,
+                       IOError::WriteZero => std::io::ErrorKind::WriteZero,
+                       IOError::Interrupted => std::io::ErrorKind::Interrupted,
+                       IOError::Other => std::io::ErrorKind::Other,
+                       IOError::UnexpectedEof => std::io::ErrorKind::UnexpectedEof,
+               }, "")
+       }
 }
 
 #[repr(C)]
@@ -183,12 +340,7 @@ pub struct Transaction {
        pub data_is_owned: bool,
 }
 impl Transaction {
-       pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
-               if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
-               ::bitcoin::consensus::encode::deserialize(unsafe { std::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
-       }
-       pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
-               let vec = ::bitcoin::consensus::encode::serialize(btc);
+       fn from_vec(vec: Vec<u8>) -> Self {
                let datalen = vec.len();
                let data = Box::into_raw(vec.into_boxed_slice());
                Self {
@@ -197,6 +349,14 @@ impl Transaction {
                        data_is_owned: true,
                }
        }
+       pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
+               if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
+               ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
+       }
+       pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
+               let vec = ::bitcoin::consensus::encode::serialize(btc);
+               Self::from_vec(vec)
+       }
 }
 impl Drop for Transaction {
        fn drop(&mut self) {
@@ -205,6 +365,14 @@ impl Drop for Transaction {
                }
        }
 }
+impl Clone for Transaction {
+       fn clone(&self) -> Self {
+               let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
+               let mut v = Vec::new();
+               v.extend_from_slice(&sl);
+               Self::from_vec(v)
+       }
+}
 #[no_mangle]
 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
 pub extern "C" fn Transaction_free(_res: Transaction) { }
@@ -212,6 +380,13 @@ pub extern "C" fn Transaction_free(_res: Transaction) { }
 pub(crate) fn bitcoin_to_C_outpoint(outpoint: ::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
        crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: outpoint.txid.into_inner() }, outpoint.vout.try_into().unwrap())
 }
+pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
+       unsafe {
+               ::bitcoin::blockdata::transaction::OutPoint {
+                       txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
+               }
+       }
+}
 
 #[repr(C)]
 #[derive(Clone)]
@@ -238,6 +413,12 @@ impl TxOut {
                }
        }
 }
+
+#[no_mangle]
+/// Convenience function for constructing a new TxOut
+pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
+       TxOut { script_pubkey, value }
+}
 #[no_mangle]
 /// Frees the data pointed to by script_pubkey.
 pub extern "C" fn TxOut_free(_res: TxOut) { }
@@ -263,9 +444,21 @@ impl u8slice {
        }
        pub(crate) fn to_slice(&self) -> &[u8] {
                if self.datalen == 0 { return &[]; }
-               unsafe { std::slice::from_raw_parts(self.data, self.datalen) }
+               unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
+       }
+       pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
+               let sl = self.to_slice();
+               Cursor::new(sl)
+       }
+       pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
+               Self::from_slice(v.as_slice())
        }
 }
+pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
+       let mut res = Vec::new();
+       r.read_to_end(&mut res).unwrap();
+       derived::CVec_u8Z::from(res)
+}
 
 #[repr(C)]
 #[derive(Copy, Clone)]
@@ -290,22 +483,23 @@ pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
 #[derive(Clone)]
 #[repr(C)]
-/// A 10-byte byte array.
-pub struct TenBytes { /** The ten bytes */ pub data: [u8; 10], }
+/// A 12-byte byte array.
+pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
 #[derive(Clone)]
 #[repr(C)]
 /// A 16-byte byte array.
 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
+#[derive(Clone)]
+#[repr(C)]
+/// A 20-byte byte array.
+pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
 
 pub(crate) struct VecWriter(pub Vec<u8>);
 impl lightning::util::ser::Writer for VecWriter {
-       fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
+       fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
                self.0.extend_from_slice(buf);
                Ok(())
        }
-       fn size_hint(&mut self, size: usize) {
-               self.0.reserve_exact(size);
-       }
 }
 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
        let mut out = VecWriter(Vec::new());
@@ -315,31 +509,80 @@ pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derive
 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
        I::read(&mut s.to_slice())
 }
+pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
+       I::read(&mut s.to_slice())
+}
 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
        I::read(&mut s.to_slice(), args)
 }
 
 #[repr(C)]
-#[derive(Copy, Clone)]
 /// 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!
 pub struct Str {
        /// A pointer to the string's bytes, in UTF8 encoding
        pub chars: *const u8,
        /// The number of bytes (not characters!) pointed to by `chars`
-       pub len: usize
+       pub len: usize,
+       /// Whether the data pointed to by `chars` should be freed or not.
+       pub chars_is_owned: bool,
 }
 impl Into<Str> for &'static str {
        fn into(self) -> Str {
-               Str { chars: self.as_ptr(), len: self.len() }
+               Str { chars: self.as_ptr(), len: self.len(), chars_is_owned: false }
+       }
+}
+impl Into<Str> for &mut &'static str {
+       fn into(self) -> Str {
+               let us: &'static str = *self;
+               us.into()
        }
 }
-impl Into<&'static str> for Str {
-       fn into(self) -> &'static str {
+
+impl Str {
+       pub(crate) fn into_str(&self) -> &'static str {
                if self.len == 0 { return ""; }
-               std::str::from_utf8(unsafe { std::slice::from_raw_parts(self.chars, self.len) }).unwrap()
+               core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
+       }
+       pub(crate) fn into_string(mut self) -> String {
+               let bytes = if self.len == 0 {
+                       Vec::new()
+               } else if self.chars_is_owned {
+                       let ret = unsafe {
+                               Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
+                       }.into();
+                       self.chars_is_owned = false;
+                       ret
+               } else {
+                       let mut ret = Vec::with_capacity(self.len);
+                       ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
+                       ret
+               };
+               String::from_utf8(bytes).unwrap()
+       }
+}
+impl Into<Str> for String {
+       fn into(self) -> Str {
+               let s = Box::leak(self.into_boxed_str());
+               Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
+       }
+}
+impl Clone for Str {
+       fn clone(&self) -> Self {
+               self.into_str().clone().into()
+       }
+}
+
+impl Drop for Str {
+       fn drop(&mut self) {
+               if self.chars_is_owned && self.len != 0 {
+                       let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
+               }
        }
 }
+#[no_mangle]
+/// Frees the data buffer, if chars_is_owned is set and len > 0.
+pub extern "C" fn Str_free(_res: Str) { }
 
 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
 // Thus, they must gracefully handle being completely null in _free.
@@ -394,14 +637,102 @@ pub(crate) trait TakePointer<T> {
 impl<T> TakePointer<*const T> for *const T {
        fn take_ptr(&mut self) -> *const T {
                let ret = *self;
-               *self = std::ptr::null();
+               *self = core::ptr::null();
                ret
        }
 }
 impl<T> TakePointer<*mut T> for *mut T {
        fn take_ptr(&mut self) -> *mut T {
                let ret = *self;
-               *self = std::ptr::null_mut();
+               *self = core::ptr::null_mut();
                ret
        }
 }
+
+
+pub(crate) mod ObjOps {
+       #[cfg(feature = "no-std")]
+       use alloc::boxed::Box;
+
+       #[inline]
+       #[must_use = "returns new dangling pointer"]
+       pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
+               let ptr = Box::into_raw(Box::new(obj));
+               nonnull_ptr_to_inner(ptr)
+       }
+       #[inline]
+       pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
+               if core::mem::size_of::<T>() == 0 {
+                       // We map `None::<T>` as `T { inner: null, .. }` which works great for all
+                       // non-Zero-Sized-Types `T`.
+                       // For ZSTs, we need to differentiate between null implying `None` and null implying
+                       // `Some` with no allocation.
+                       // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
+                       // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
+                       // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
+                       // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
+                       // fine.
+                       // Note that we add 4095 here as at least the Java client assumes that the low bit on
+                       // any heap pointer is 0, which is generally provided by malloc, but which is not true
+                       // for ZSTs "allocated" by `Box::new`.
+                       debug_assert_eq!(ptr as usize, 1);
+                       unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
+               } else {
+                       // In order to get better test coverage, also increment non-ZST pointers with
+                       // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
+                       #[cfg(test_mod_pointers)]
+                       unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
+                       #[cfg(not(test_mod_pointers))]
+                       unsafe { ptr as *mut T }
+               }
+       }
+       #[inline]
+       /// Invert nonnull_ptr_to_inner
+       pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
+               if core::mem::size_of::<T>() == 0 {
+                       unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
+               } else {
+                       #[cfg(test_mod_pointers)]
+                       unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
+                       #[cfg(not(test_mod_pointers))]
+                       ptr
+               }
+       }
+}
+
+#[cfg(test_mod_pointers)]
+#[no_mangle]
+/// This function exists for memory safety testing purposes. It should never be used in production
+/// code
+pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
+       if ptr as usize == 1 {
+               core::ptr::null()
+       } else {
+               unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
+       }
+}
+
+pub(crate) struct SmartPtr<T> {
+       ptr: *mut T,
+}
+impl<T> SmartPtr<T> {
+       pub(crate) fn from_obj(o: T) -> Self {
+               Self { ptr: Box::into_raw(Box::new(o)) }
+       }
+       pub(crate) fn null() -> Self {
+               Self { ptr: core::ptr::null_mut() }
+       }
+}
+impl<T> Drop for SmartPtr<T> {
+       fn drop(&mut self) {
+               if self.ptr != core::ptr::null_mut() {
+                       unsafe { Box::from_raw(self.ptr); }
+               }
+       }
+}
+impl<T> core::ops::Deref for SmartPtr<T> {
+       type Target = *mut T;
+       fn deref(&self) -> &*mut T {
+               &self.ptr
+       }
+}