Drop the now-unused usizeslice bindings struct
[rust-lightning] / lightning-c-bindings / src / c_types / mod.rs
1 pub mod derived;
2
3 use bitcoin::Script as BitcoinScript;
4 use bitcoin::Transaction as BitcoinTransaction;
5 use bitcoin::secp256k1::key::PublicKey as SecpPublicKey;
6 use bitcoin::secp256k1::key::SecretKey as SecpSecretKey;
7 use bitcoin::secp256k1::Signature as SecpSignature;
8 use bitcoin::secp256k1::Error as SecpError;
9
10 #[derive(Clone)]
11 #[repr(C)]
12 pub struct PublicKey {
13         pub compressed_form: [u8; 33],
14 }
15 impl PublicKey {
16         pub(crate) fn from_rust(pk: &SecpPublicKey) -> Self {
17                 Self {
18                         compressed_form: pk.serialize(),
19                 }
20         }
21         pub(crate) fn into_rust(&self) -> SecpPublicKey {
22                 SecpPublicKey::from_slice(&self.compressed_form).unwrap()
23         }
24         pub(crate) fn is_null(&self) -> bool { self.compressed_form[..] == [0; 33][..] }
25         pub(crate) fn null() -> Self { Self { compressed_form: [0; 33] } }
26 }
27
28 #[repr(C)]
29 pub struct SecretKey {
30         pub bytes: [u8; 32],
31 }
32 impl SecretKey {
33         // from_rust isn't implemented for a ref since we just return byte array refs directly
34         pub(crate) fn from_rust(sk: SecpSecretKey) -> Self {
35                 let mut bytes = [0; 32];
36                 bytes.copy_from_slice(&sk[..]);
37                 Self { bytes }
38         }
39         pub(crate) fn into_rust(&self) -> SecpSecretKey {
40                 SecpSecretKey::from_slice(&self.bytes).unwrap()
41         }
42 }
43
44 #[repr(C)]
45 pub struct Signature {
46         pub compact_form: [u8; 64],
47 }
48 impl Signature {
49         pub(crate) fn from_rust(pk: &SecpSignature) -> Self {
50                 Self {
51                         compact_form: pk.serialize_compact(),
52                 }
53         }
54         pub(crate) fn into_rust(&self) -> SecpSignature {
55                 SecpSignature::from_compact(&self.compact_form).unwrap()
56         }
57         pub(crate) fn is_null(&self) -> bool { self.compact_form[..] == [0; 64][..] }
58         pub(crate) fn null() -> Self { Self { compact_form: [0; 64] } }
59 }
60
61 #[repr(C)]
62 pub enum Secp256k1Error {
63         IncorrectSignature,
64         InvalidMessage,
65         InvalidPublicKey,
66         InvalidSignature,
67         InvalidSecretKey,
68         InvalidRecoveryId,
69         InvalidTweak,
70         NotEnoughMemory,
71         CallbackPanicked,
72 }
73 impl Secp256k1Error {
74         pub(crate) fn from_rust(err: SecpError) -> Self {
75                 match err {
76                         SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
77                         SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
78                         SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
79                         SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
80                         SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
81                         SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
82                         SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
83                         SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
84                 }
85         }
86 }
87
88 #[repr(C)]
89 /// A serialized transaction, in (pointer, length) form.
90 ///
91 /// This type optionally owns its own memory, and thus the semantics around access change based on
92 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
93 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
94 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
95 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
96 /// you would be invalid.
97 ///
98 /// Note that, while it may change in the future, because transactions on the Rust side are stored
99 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
100 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
101 /// `data_is_owned` either set or unset at your discretion.
102 pub struct Transaction {
103         pub data: *const u8,
104         pub datalen: usize,
105         pub data_is_owned: bool,
106 }
107 impl Transaction {
108         pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
109                 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
110                 ::bitcoin::consensus::encode::deserialize(unsafe { std::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
111         }
112         pub(crate) fn from_vec(v: Vec<u8>) -> Self {
113                 let datalen = v.len();
114                 let data = Box::into_raw(v.into_boxed_slice());
115                 Self {
116                         data: unsafe { (*data).as_mut_ptr() },
117                         datalen,
118                         data_is_owned: true,
119                 }
120         }
121 }
122 impl Drop for Transaction {
123         fn drop(&mut self) {
124                 if self.data_is_owned && self.datalen != 0 {
125                         let _ = CVecTempl { data: self.data as *mut u8, datalen: self.datalen };
126                 }
127         }
128 }
129 #[no_mangle]
130 pub extern "C" fn Transaction_free(_res: Transaction) { }
131
132 #[repr(C)]
133 #[derive(Clone)]
134 /// A transaction output including a scriptPubKey and value.
135 /// This type *does* own its own memory, so must be free'd appropriately.
136 pub struct TxOut {
137         pub script_pubkey: derived::CVec_u8Z,
138         pub value: u64,
139 }
140
141 impl TxOut {
142         pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
143                 ::bitcoin::blockdata::transaction::TxOut {
144                         script_pubkey: self.script_pubkey.into_rust().into(),
145                         value: self.value,
146                 }
147         }
148         pub(crate) fn from_rust(txout: ::bitcoin::blockdata::transaction::TxOut) -> Self {
149                 Self {
150                         script_pubkey: CVecTempl::from(txout.script_pubkey.into_bytes()),
151                         value: txout.value
152                 }
153         }
154 }
155 #[no_mangle]
156 pub extern "C" fn TxOut_free(_res: TxOut) { }
157
158 #[repr(C)]
159 pub struct u8slice {
160         pub data: *const u8,
161         pub datalen: usize
162 }
163 impl u8slice {
164         pub(crate) fn from_slice(s: &[u8]) -> Self {
165                 Self {
166                         data: s.as_ptr(),
167                         datalen: s.len(),
168                 }
169         }
170         pub(crate) fn to_slice(&self) -> &[u8] {
171                 if self.datalen == 0 { return &[]; }
172                 unsafe { std::slice::from_raw_parts(self.data, self.datalen) }
173         }
174 }
175
176 #[repr(C)]
177 #[derive(Copy, Clone)]
178 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
179 /// look up the corresponding function in rust-lightning's docs.
180 pub struct ThirtyTwoBytes {
181         pub data: [u8; 32],
182 }
183 impl ThirtyTwoBytes {
184         pub(crate) fn null() -> Self {
185                 Self { data: [0; 32] }
186         }
187 }
188
189 #[repr(C)]
190 pub struct ThreeBytes { pub data: [u8; 3], }
191 #[derive(Clone)]
192 #[repr(C)]
193 pub struct FourBytes { pub data: [u8; 4], }
194 #[derive(Clone)]
195 #[repr(C)]
196 pub struct TenBytes { pub data: [u8; 10], }
197 #[derive(Clone)]
198 #[repr(C)]
199 pub struct SixteenBytes { pub data: [u8; 16], }
200
201 pub(crate) struct VecWriter(pub Vec<u8>);
202 impl lightning::util::ser::Writer for VecWriter {
203         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
204                 self.0.extend_from_slice(buf);
205                 Ok(())
206         }
207         fn size_hint(&mut self, size: usize) {
208                 self.0.reserve_exact(size);
209         }
210 }
211 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
212         let mut out = VecWriter(Vec::new());
213         i.write(&mut out).unwrap();
214         CVecTempl::from(out.0)
215 }
216 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
217         I::read(&mut s.to_slice())
218 }
219
220 #[repr(C)]
221 #[derive(Copy, Clone)]
222 /// A Rust str object, ie a reference to a UTF8-valid string.
223 /// This is *not* null-terminated so cannot be used directly as a C string!
224 pub struct Str {
225         pub chars: *const u8,
226         pub len: usize
227 }
228 impl Into<Str> for &'static str {
229         fn into(self) -> Str {
230                 Str { chars: self.as_ptr(), len: self.len() }
231         }
232 }
233 impl Into<&'static str> for Str {
234         fn into(self) -> &'static str {
235                 if self.len == 0 { return ""; }
236                 std::str::from_utf8(unsafe { std::slice::from_raw_parts(self.chars, self.len) }).unwrap()
237         }
238 }
239
240 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
241 // Thus, they must gracefully handle being completely null in _free.
242
243 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
244 // everywhere in the containers.
245
246 #[repr(C)]
247 pub union CResultPtr<O, E> {
248         pub result: *mut O,
249         pub err: *mut E,
250 }
251 #[repr(C)]
252 pub struct CResultTempl<O, E> {
253         pub contents: CResultPtr<O, E>,
254         pub result_ok: bool,
255 }
256 impl<O, E> CResultTempl<O, E> {
257         pub(crate) extern "C" fn ok(o: O) -> Self {
258                 CResultTempl {
259                         contents: CResultPtr {
260                                 result: Box::into_raw(Box::new(o)),
261                         },
262                         result_ok: true,
263                 }
264         }
265         pub(crate) extern "C" fn err(e: E) -> Self {
266                 CResultTempl {
267                         contents: CResultPtr {
268                                 err: Box::into_raw(Box::new(e)),
269                         },
270                         result_ok: false,
271                 }
272         }
273 }
274 pub extern "C" fn CResultTempl_free<O, E>(_res: CResultTempl<O, E>) { }
275 impl<O, E> Drop for CResultTempl<O, E> {
276         fn drop(&mut self) {
277                 if self.result_ok {
278                         if unsafe { !self.contents.result.is_null() } {
279                                 unsafe { Box::from_raw(self.contents.result) };
280                         }
281                 } else if unsafe { !self.contents.err.is_null() } {
282                         unsafe { Box::from_raw(self.contents.err) };
283                 }
284         }
285 }
286
287 #[repr(C)]
288 pub struct CVecTempl<T> {
289         pub data: *mut T,
290         pub datalen: usize
291 }
292 impl<T> CVecTempl<T> {
293         pub(crate) fn into_rust(&mut self) -> Vec<T> {
294                 if self.datalen == 0 { return Vec::new(); }
295                 let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
296                 self.data = std::ptr::null_mut();
297                 self.datalen = 0;
298                 ret
299         }
300         pub(crate) fn as_slice(&self) -> &[T] {
301                 unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
302         }
303 }
304 impl<T> From<Vec<T>> for CVecTempl<T> {
305         fn from(v: Vec<T>) -> Self {
306                 let datalen = v.len();
307                 let data = Box::into_raw(v.into_boxed_slice());
308                 CVecTempl { datalen, data: unsafe { (*data).as_mut_ptr() } }
309         }
310 }
311 pub extern "C" fn CVecTempl_free<T>(_res: CVecTempl<T>) { }
312 impl<T> Drop for CVecTempl<T> {
313         fn drop(&mut self) {
314                 if self.datalen == 0 { return; }
315                 unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
316         }
317 }
318 impl<T: Clone> Clone for CVecTempl<T> {
319         fn clone(&self) -> Self {
320                 let mut res = Vec::new();
321                 if self.datalen == 0 { return Self::from(res); }
322                 res.clone_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
323                 Self::from(res)
324         }
325 }
326
327 #[repr(C)]
328 pub struct C2TupleTempl<A, B> {
329         pub a: *mut A,
330         pub b: *mut B,
331 }
332 impl<A, B> From<(A, B)> for C2TupleTempl<A, B> {
333         fn from(tup: (A, B)) -> Self {
334                 Self {
335                         a: Box::into_raw(Box::new(tup.0)),
336                         b: Box::into_raw(Box::new(tup.1)),
337                 }
338         }
339 }
340 impl<A, B> C2TupleTempl<A, B> {
341         pub(crate) fn to_rust(mut self) -> (A, B) {
342                 let res = (unsafe { *Box::from_raw(self.a) }, unsafe { *Box::from_raw(self.b) });
343                 self.a = std::ptr::null_mut();
344                 self.b = std::ptr::null_mut();
345                 res
346         }
347 }
348 pub extern "C" fn C2TupleTempl_free<A, B>(_res: C2TupleTempl<A, B>) { }
349 impl<A, B> Drop for C2TupleTempl<A, B> {
350         fn drop(&mut self) {
351                 if !self.a.is_null() {
352                         unsafe { Box::from_raw(self.a) };
353                 }
354                 if !self.b.is_null() {
355                         unsafe { Box::from_raw(self.b) };
356                 }
357         }
358 }
359 impl <A: Clone, B: Clone> Clone for C2TupleTempl<A, B> {
360         fn clone(&self) -> Self {
361                 Self {
362                         a: Box::into_raw(Box::new(unsafe { &*self.a }.clone())),
363                         b: Box::into_raw(Box::new(unsafe { &*self.b }.clone()))
364                 }
365         }
366 }
367
368 #[repr(C)]
369 pub struct C3TupleTempl<A, B, C> {
370         pub a: *mut A,
371         pub b: *mut B,
372         pub c: *mut C,
373 }
374 impl<A, B, C> From<(A, B, C)> for C3TupleTempl<A, B, C> {
375         fn from(tup: (A, B, C)) -> Self {
376                 Self {
377                         a: Box::into_raw(Box::new(tup.0)),
378                         b: Box::into_raw(Box::new(tup.1)),
379                         c: Box::into_raw(Box::new(tup.2)),
380                 }
381         }
382 }
383 impl<A, B, C> C3TupleTempl<A, B, C> {
384         pub(crate) fn to_rust(mut self) -> (A, B, C) {
385                 let res = (unsafe { *Box::from_raw(self.a) }, unsafe { *Box::from_raw(self.b) }, unsafe { *Box::from_raw(self.c) });
386                 self.a = std::ptr::null_mut();
387                 self.b = std::ptr::null_mut();
388                 self.c = std::ptr::null_mut();
389                 res
390         }
391 }
392 pub extern "C" fn C3TupleTempl_free<A, B, C>(_res: C3TupleTempl<A, B, C>) { }
393 impl<A, B, C> Drop for C3TupleTempl<A, B, C> {
394         fn drop(&mut self) {
395                 if !self.a.is_null() {
396                         unsafe { Box::from_raw(self.a) };
397                 }
398                 if !self.b.is_null() {
399                         unsafe { Box::from_raw(self.b) };
400                 }
401                 if !self.c.is_null() {
402                         unsafe { Box::from_raw(self.c) };
403                 }
404         }
405 }
406
407 /// Utility to make it easy to set a pointer to null and get its original value in line.
408 pub(crate) trait TakePointer<T> {
409         fn take_ptr(&mut self) -> T;
410 }
411 impl<T> TakePointer<*const T> for *const T {
412         fn take_ptr(&mut self) -> *const T {
413                 let ret = *self;
414                 *self = std::ptr::null();
415                 ret
416         }
417 }
418 impl<T> TakePointer<*mut T> for *mut T {
419         fn take_ptr(&mut self) -> *mut T {
420                 let ret = *self;
421                 *self = std::ptr::null_mut();
422                 ret
423         }
424 }