Merge pull request #18 from TheBlueMatt/2021-04-invoice-incl
[ldk-c-bindings] / lightning-c-bindings / src / c_types / mod.rs
1 //! This module contains standard C-mapped types for types not in the original crate.
2
3 /// Auto-generated C-mapped types for templated containers
4 pub mod derived;
5
6 use bitcoin::Transaction as BitcoinTransaction;
7 use bitcoin::hashes::Hash;
8 use bitcoin::secp256k1::key::PublicKey as SecpPublicKey;
9 use bitcoin::secp256k1::key::SecretKey as SecpSecretKey;
10 use bitcoin::secp256k1::Signature as SecpSignature;
11 use bitcoin::secp256k1::Error as SecpError;
12 use bitcoin::bech32;
13
14 use std::convert::TryInto; // Bindings need at least rustc 1.34
15
16 /// Integer in the range `0..32`
17 #[derive(PartialEq, Eq, Copy, Clone)]
18 #[allow(non_camel_case_types)]
19 #[repr(C)]
20 pub struct u5(u8);
21
22 impl From<bech32::u5> for u5 {
23         fn from(o: bech32::u5) -> Self { Self(o.to_u8()) }
24 }
25 impl Into<bech32::u5> for u5 {
26         fn into(self) -> bech32::u5 { bech32::u5::try_from_u8(self.0).expect("u5 objects must be in the range 0..32") }
27 }
28
29 #[derive(Clone)]
30 #[repr(C)]
31 /// Represents a valid secp256k1 public key serialized in "compressed form" as a 33 byte array.
32 pub struct PublicKey {
33         /// The bytes of the public key
34         pub compressed_form: [u8; 33],
35 }
36 impl PublicKey {
37         pub(crate) fn from_rust(pk: &SecpPublicKey) -> Self {
38                 Self {
39                         compressed_form: pk.serialize(),
40                 }
41         }
42         pub(crate) fn into_rust(&self) -> SecpPublicKey {
43                 SecpPublicKey::from_slice(&self.compressed_form).unwrap()
44         }
45         pub(crate) fn is_null(&self) -> bool { self.compressed_form[..] == [0; 33][..] }
46         pub(crate) fn null() -> Self { Self { compressed_form: [0; 33] } }
47 }
48
49 #[repr(C)]
50 /// Represents a valid secp256k1 secret key serialized as a 32 byte array.
51 pub struct SecretKey {
52         /// The bytes of the secret key
53         pub bytes: [u8; 32],
54 }
55 impl SecretKey {
56         // from_rust isn't implemented for a ref since we just return byte array refs directly
57         pub(crate) fn from_rust(sk: SecpSecretKey) -> Self {
58                 let mut bytes = [0; 32];
59                 bytes.copy_from_slice(&sk[..]);
60                 Self { bytes }
61         }
62         pub(crate) fn into_rust(&self) -> SecpSecretKey {
63                 SecpSecretKey::from_slice(&self.bytes).unwrap()
64         }
65 }
66
67 #[repr(C)]
68 #[derive(Clone)]
69 /// Represents a secp256k1 signature serialized as two 32-byte numbers
70 pub struct Signature {
71         /// The bytes of the signature in "compact" form
72         pub compact_form: [u8; 64],
73 }
74 impl Signature {
75         pub(crate) fn from_rust(pk: &SecpSignature) -> Self {
76                 Self {
77                         compact_form: pk.serialize_compact(),
78                 }
79         }
80         pub(crate) fn into_rust(&self) -> SecpSignature {
81                 SecpSignature::from_compact(&self.compact_form).unwrap()
82         }
83         // The following are used for Option<Signature> which we support, but don't use anymore
84         #[allow(unused)] pub(crate) fn is_null(&self) -> bool { self.compact_form[..] == [0; 64][..] }
85         #[allow(unused)] pub(crate) fn null() -> Self { Self { compact_form: [0; 64] } }
86 }
87
88 #[repr(C)]
89 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
90 pub enum Secp256k1Error {
91         /// Signature failed verification
92         IncorrectSignature,
93         /// Badly sized message ("messages" are actually fixed-sized digests; see the MESSAGE_SIZE constant)
94         InvalidMessage,
95         /// Bad public key
96         InvalidPublicKey,
97         /// Bad signature
98         InvalidSignature,
99         /// Bad secret key
100         InvalidSecretKey,
101         /// Bad recovery id
102         InvalidRecoveryId,
103         /// Invalid tweak for add_assign or mul_assign
104         InvalidTweak,
105         /// tweak_add_check failed on an xonly public key
106         TweakCheckFailed,
107         /// Didn't pass enough memory to context creation with preallocated memory
108         NotEnoughMemory,
109 }
110 impl Secp256k1Error {
111         pub(crate) fn from_rust(err: SecpError) -> Self {
112                 match err {
113                         SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
114                         SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
115                         SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
116                         SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
117                         SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
118                         SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
119                         SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
120                         SecpError::TweakCheckFailed => Secp256k1Error::TweakCheckFailed,
121                         SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
122                 }
123         }
124 }
125
126 #[repr(C)]
127 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
128 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
129 pub enum IOError {
130         NotFound,
131         PermissionDenied,
132         ConnectionRefused,
133         ConnectionReset,
134         ConnectionAborted,
135         NotConnected,
136         AddrInUse,
137         AddrNotAvailable,
138         BrokenPipe,
139         AlreadyExists,
140         WouldBlock,
141         InvalidInput,
142         InvalidData,
143         TimedOut,
144         WriteZero,
145         Interrupted,
146         Other,
147         UnexpectedEof,
148 }
149 impl IOError {
150         pub(crate) fn from_rust(err: std::io::Error) -> Self {
151                 match err.kind() {
152                         std::io::ErrorKind::NotFound => IOError::NotFound,
153                         std::io::ErrorKind::PermissionDenied => IOError::PermissionDenied,
154                         std::io::ErrorKind::ConnectionRefused => IOError::ConnectionRefused,
155                         std::io::ErrorKind::ConnectionReset => IOError::ConnectionReset,
156                         std::io::ErrorKind::ConnectionAborted => IOError::ConnectionAborted,
157                         std::io::ErrorKind::NotConnected => IOError::NotConnected,
158                         std::io::ErrorKind::AddrInUse => IOError::AddrInUse,
159                         std::io::ErrorKind::AddrNotAvailable => IOError::AddrNotAvailable,
160                         std::io::ErrorKind::BrokenPipe => IOError::BrokenPipe,
161                         std::io::ErrorKind::AlreadyExists => IOError::AlreadyExists,
162                         std::io::ErrorKind::WouldBlock => IOError::WouldBlock,
163                         std::io::ErrorKind::InvalidInput => IOError::InvalidInput,
164                         std::io::ErrorKind::InvalidData => IOError::InvalidData,
165                         std::io::ErrorKind::TimedOut => IOError::TimedOut,
166                         std::io::ErrorKind::WriteZero => IOError::WriteZero,
167                         std::io::ErrorKind::Interrupted => IOError::Interrupted,
168                         std::io::ErrorKind::Other => IOError::Other,
169                         std::io::ErrorKind::UnexpectedEof => IOError::UnexpectedEof,
170                         _ => IOError::Other,
171                 }
172         }
173 }
174
175 #[repr(C)]
176 /// A serialized transaction, in (pointer, length) form.
177 ///
178 /// This type optionally owns its own memory, and thus the semantics around access change based on
179 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
180 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
181 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
182 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
183 /// you would be invalid.
184 ///
185 /// Note that, while it may change in the future, because transactions on the Rust side are stored
186 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
187 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
188 /// `data_is_owned` either set or unset at your discretion.
189 pub struct Transaction {
190         /// The serialized transaction data.
191         ///
192         /// This is non-const for your convenience, an object passed to Rust is never written to.
193         pub data: *mut u8,
194         /// The length of the serialized transaction
195         pub datalen: usize,
196         /// Whether the data pointed to by `data` should be freed or not.
197         pub data_is_owned: bool,
198 }
199 impl Transaction {
200         pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
201                 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
202                 ::bitcoin::consensus::encode::deserialize(unsafe { std::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
203         }
204         pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
205                 let vec = ::bitcoin::consensus::encode::serialize(btc);
206                 let datalen = vec.len();
207                 let data = Box::into_raw(vec.into_boxed_slice());
208                 Self {
209                         data: unsafe { (*data).as_mut_ptr() },
210                         datalen,
211                         data_is_owned: true,
212                 }
213         }
214 }
215 impl Drop for Transaction {
216         fn drop(&mut self) {
217                 if self.data_is_owned && self.datalen != 0 {
218                         let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
219                 }
220         }
221 }
222 #[no_mangle]
223 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
224 pub extern "C" fn Transaction_free(_res: Transaction) { }
225
226 pub(crate) fn bitcoin_to_C_outpoint(outpoint: ::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
227         crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: outpoint.txid.into_inner() }, outpoint.vout.try_into().unwrap())
228 }
229
230 #[repr(C)]
231 #[derive(Clone)]
232 /// A transaction output including a scriptPubKey and value.
233 /// This type *does* own its own memory, so must be free'd appropriately.
234 pub struct TxOut {
235         /// The script_pubkey in this output
236         pub script_pubkey: derived::CVec_u8Z,
237         /// The value, in satoshis, of this output
238         pub value: u64,
239 }
240
241 impl TxOut {
242         pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
243                 ::bitcoin::blockdata::transaction::TxOut {
244                         script_pubkey: self.script_pubkey.into_rust().into(),
245                         value: self.value,
246                 }
247         }
248         pub(crate) fn from_rust(txout: ::bitcoin::blockdata::transaction::TxOut) -> Self {
249                 Self {
250                         script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.into_bytes()),
251                         value: txout.value
252                 }
253         }
254 }
255 #[no_mangle]
256 /// Frees the data pointed to by script_pubkey.
257 pub extern "C" fn TxOut_free(_res: TxOut) { }
258 #[no_mangle]
259 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
260 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
261
262 #[repr(C)]
263 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
264 /// own the memory pointed to by data.
265 pub struct u8slice {
266         /// A pointer to the byte buffer
267         pub data: *const u8,
268         /// The number of bytes pointed to by `data`.
269         pub datalen: usize
270 }
271 impl u8slice {
272         pub(crate) fn from_slice(s: &[u8]) -> Self {
273                 Self {
274                         data: s.as_ptr(),
275                         datalen: s.len(),
276                 }
277         }
278         pub(crate) fn to_slice(&self) -> &[u8] {
279                 if self.datalen == 0 { return &[]; }
280                 unsafe { std::slice::from_raw_parts(self.data, self.datalen) }
281         }
282 }
283
284 #[repr(C)]
285 #[derive(Copy, Clone)]
286 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
287 /// look up the corresponding function in rust-lightning's docs.
288 pub struct ThirtyTwoBytes {
289         /// The thirty-two bytes
290         pub data: [u8; 32],
291 }
292 impl ThirtyTwoBytes {
293         pub(crate) fn null() -> Self {
294                 Self { data: [0; 32] }
295         }
296 }
297
298 #[repr(C)]
299 /// A 3-byte byte array.
300 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
301 #[derive(Clone)]
302 #[repr(C)]
303 /// A 4-byte byte array.
304 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
305 #[derive(Clone)]
306 #[repr(C)]
307 /// A 10-byte byte array.
308 pub struct TenBytes { /** The ten bytes */ pub data: [u8; 10], }
309 #[derive(Clone)]
310 #[repr(C)]
311 /// A 16-byte byte array.
312 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
313 #[derive(Clone)]
314 #[repr(C)]
315 /// A 20-byte byte array.
316 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
317
318 pub(crate) struct VecWriter(pub Vec<u8>);
319 impl lightning::util::ser::Writer for VecWriter {
320         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
321                 self.0.extend_from_slice(buf);
322                 Ok(())
323         }
324         fn size_hint(&mut self, size: usize) {
325                 self.0.reserve_exact(size);
326         }
327 }
328 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
329         let mut out = VecWriter(Vec::new());
330         i.write(&mut out).unwrap();
331         derived::CVec_u8Z::from(out.0)
332 }
333 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
334         I::read(&mut s.to_slice())
335 }
336 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
337         I::read(&mut s.to_slice(), args)
338 }
339
340 #[repr(C)]
341 #[derive(Clone)]
342 /// A Rust str object, ie a reference to a UTF8-valid string.
343 /// This is *not* null-terminated so cannot be used directly as a C string!
344 pub struct Str {
345         /// A pointer to the string's bytes, in UTF8 encoding
346         pub chars: *const u8,
347         /// The number of bytes (not characters!) pointed to by `chars`
348         pub len: usize,
349         /// Whether the data pointed to by `chars` should be freed or not.
350         pub chars_is_owned: bool,
351 }
352 impl Into<Str> for &'static str {
353         fn into(self) -> Str {
354                 Str { chars: self.as_ptr(), len: self.len(), chars_is_owned: false }
355         }
356 }
357 impl Into<&'static str> for Str {
358         fn into(self) -> &'static str {
359                 if self.len == 0 { return ""; }
360                 std::str::from_utf8(unsafe { std::slice::from_raw_parts(self.chars, self.len) }).unwrap()
361         }
362 }
363 impl Into<Str> for String {
364         fn into(self) -> Str {
365                 let s = Box::leak(self.into_boxed_str());
366                 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
367         }
368 }
369
370 impl Drop for Str {
371         fn drop(&mut self) {
372                 if self.chars_is_owned && self.len != 0 {
373                         let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
374                 }
375         }
376 }
377 #[no_mangle]
378 /// Frees the data buffer, if chars_is_owned is set and len > 0.
379 pub extern "C" fn Str_free(_res: Str) { }
380
381 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
382 // Thus, they must gracefully handle being completely null in _free.
383
384 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
385 // everywhere in the containers.
386
387 #[repr(C)]
388 pub(crate) union CResultPtr<O, E> {
389         pub(crate) result: *mut O,
390         pub(crate) err: *mut E,
391 }
392 #[repr(C)]
393 pub(crate) struct CResultTempl<O, E> {
394         pub(crate) contents: CResultPtr<O, E>,
395         pub(crate) result_ok: bool,
396 }
397 impl<O, E> CResultTempl<O, E> {
398         pub(crate) extern "C" fn ok(o: O) -> Self {
399                 CResultTempl {
400                         contents: CResultPtr {
401                                 result: Box::into_raw(Box::new(o)),
402                         },
403                         result_ok: true,
404                 }
405         }
406         pub(crate) extern "C" fn err(e: E) -> Self {
407                 CResultTempl {
408                         contents: CResultPtr {
409                                 err: Box::into_raw(Box::new(e)),
410                         },
411                         result_ok: false,
412                 }
413         }
414 }
415 impl<O, E> Drop for CResultTempl<O, E> {
416         fn drop(&mut self) {
417                 if self.result_ok {
418                         if unsafe { !self.contents.result.is_null() } {
419                                 unsafe { Box::from_raw(self.contents.result) };
420                         }
421                 } else if unsafe { !self.contents.err.is_null() } {
422                         unsafe { Box::from_raw(self.contents.err) };
423                 }
424         }
425 }
426
427 /// Utility to make it easy to set a pointer to null and get its original value in line.
428 pub(crate) trait TakePointer<T> {
429         fn take_ptr(&mut self) -> T;
430 }
431 impl<T> TakePointer<*const T> for *const T {
432         fn take_ptr(&mut self) -> *const T {
433                 let ret = *self;
434                 *self = std::ptr::null();
435                 ret
436         }
437 }
438 impl<T> TakePointer<*mut T> for *mut T {
439         fn take_ptr(&mut self) -> *mut T {
440                 let ret = *self;
441                 *self = std::ptr::null_mut();
442                 ret
443         }
444 }