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