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