Don't underpay htlc_min due to path contribution
[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         /// This is non-const for your convenience, an object passed to Rust is never written to.
104         pub data: *mut u8,
105         pub datalen: usize,
106         pub data_is_owned: bool,
107 }
108 impl Transaction {
109         pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
110                 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
111                 ::bitcoin::consensus::encode::deserialize(unsafe { std::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
112         }
113         pub(crate) fn from_vec(v: Vec<u8>) -> Self {
114                 let datalen = v.len();
115                 let data = Box::into_raw(v.into_boxed_slice());
116                 Self {
117                         data: unsafe { (*data).as_mut_ptr() },
118                         datalen,
119                         data_is_owned: true,
120                 }
121         }
122 }
123 impl Drop for Transaction {
124         fn drop(&mut self) {
125                 if self.data_is_owned && self.datalen != 0 {
126                         let _ = CVecTempl { data: self.data as *mut u8, datalen: self.datalen };
127                 }
128         }
129 }
130 #[no_mangle]
131 pub extern "C" fn Transaction_free(_res: Transaction) { }
132
133 #[repr(C)]
134 #[derive(Clone)]
135 /// A transaction output including a scriptPubKey and value.
136 /// This type *does* own its own memory, so must be free'd appropriately.
137 pub struct TxOut {
138         pub script_pubkey: derived::CVec_u8Z,
139         pub value: u64,
140 }
141
142 impl TxOut {
143         pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
144                 ::bitcoin::blockdata::transaction::TxOut {
145                         script_pubkey: self.script_pubkey.into_rust().into(),
146                         value: self.value,
147                 }
148         }
149         pub(crate) fn from_rust(txout: ::bitcoin::blockdata::transaction::TxOut) -> Self {
150                 Self {
151                         script_pubkey: CVecTempl::from(txout.script_pubkey.into_bytes()),
152                         value: txout.value
153                 }
154         }
155 }
156 #[no_mangle]
157 pub extern "C" fn TxOut_free(_res: TxOut) { }
158
159 #[repr(C)]
160 pub struct u8slice {
161         pub data: *const u8,
162         pub datalen: usize
163 }
164 impl u8slice {
165         pub(crate) fn from_slice(s: &[u8]) -> Self {
166                 Self {
167                         data: s.as_ptr(),
168                         datalen: s.len(),
169                 }
170         }
171         pub(crate) fn to_slice(&self) -> &[u8] {
172                 if self.datalen == 0 { return &[]; }
173                 unsafe { std::slice::from_raw_parts(self.data, self.datalen) }
174         }
175 }
176
177 #[repr(C)]
178 #[derive(Copy, Clone)]
179 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
180 /// look up the corresponding function in rust-lightning's docs.
181 pub struct ThirtyTwoBytes {
182         pub data: [u8; 32],
183 }
184 impl ThirtyTwoBytes {
185         pub(crate) fn null() -> Self {
186                 Self { data: [0; 32] }
187         }
188 }
189
190 #[repr(C)]
191 pub struct ThreeBytes { pub data: [u8; 3], }
192 #[derive(Clone)]
193 #[repr(C)]
194 pub struct FourBytes { pub data: [u8; 4], }
195 #[derive(Clone)]
196 #[repr(C)]
197 pub struct TenBytes { pub data: [u8; 10], }
198 #[derive(Clone)]
199 #[repr(C)]
200 pub struct SixteenBytes { pub data: [u8; 16], }
201
202 pub(crate) struct VecWriter(pub Vec<u8>);
203 impl lightning::util::ser::Writer for VecWriter {
204         fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
205                 self.0.extend_from_slice(buf);
206                 Ok(())
207         }
208         fn size_hint(&mut self, size: usize) {
209                 self.0.reserve_exact(size);
210         }
211 }
212 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
213         let mut out = VecWriter(Vec::new());
214         i.write(&mut out).unwrap();
215         CVecTempl::from(out.0)
216 }
217 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
218         I::read(&mut s.to_slice())
219 }
220
221 #[repr(C)]
222 #[derive(Copy, Clone)]
223 /// A Rust str object, ie a reference to a UTF8-valid string.
224 /// This is *not* null-terminated so cannot be used directly as a C string!
225 pub struct Str {
226         pub chars: *const u8,
227         pub len: usize
228 }
229 impl Into<Str> for &'static str {
230         fn into(self) -> Str {
231                 Str { chars: self.as_ptr(), len: self.len() }
232         }
233 }
234 impl Into<&'static str> for Str {
235         fn into(self) -> &'static str {
236                 if self.len == 0 { return ""; }
237                 std::str::from_utf8(unsafe { std::slice::from_raw_parts(self.chars, self.len) }).unwrap()
238         }
239 }
240
241 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
242 // Thus, they must gracefully handle being completely null in _free.
243
244 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
245 // everywhere in the containers.
246
247 #[repr(C)]
248 pub union CResultPtr<O, E> {
249         pub result: *mut O,
250         pub err: *mut E,
251 }
252 #[repr(C)]
253 pub struct CResultTempl<O, E> {
254         pub contents: CResultPtr<O, E>,
255         pub result_ok: bool,
256 }
257 impl<O, E> CResultTempl<O, E> {
258         pub(crate) extern "C" fn ok(o: O) -> Self {
259                 CResultTempl {
260                         contents: CResultPtr {
261                                 result: Box::into_raw(Box::new(o)),
262                         },
263                         result_ok: true,
264                 }
265         }
266         pub(crate) extern "C" fn err(e: E) -> Self {
267                 CResultTempl {
268                         contents: CResultPtr {
269                                 err: Box::into_raw(Box::new(e)),
270                         },
271                         result_ok: false,
272                 }
273         }
274 }
275 pub extern "C" fn CResultTempl_free<O, E>(_res: CResultTempl<O, E>) { }
276 impl<O, E> Drop for CResultTempl<O, E> {
277         fn drop(&mut self) {
278                 if self.result_ok {
279                         if unsafe { !self.contents.result.is_null() } {
280                                 unsafe { Box::from_raw(self.contents.result) };
281                         }
282                 } else if unsafe { !self.contents.err.is_null() } {
283                         unsafe { Box::from_raw(self.contents.err) };
284                 }
285         }
286 }
287
288 #[repr(C)]
289 pub struct CVecTempl<T> {
290         pub data: *mut T,
291         pub datalen: usize
292 }
293 impl<T> CVecTempl<T> {
294         pub(crate) fn into_rust(&mut self) -> Vec<T> {
295                 if self.datalen == 0 { return Vec::new(); }
296                 let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
297                 self.data = std::ptr::null_mut();
298                 self.datalen = 0;
299                 ret
300         }
301         pub(crate) fn as_slice(&self) -> &[T] {
302                 unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
303         }
304 }
305 impl<T> From<Vec<T>> for CVecTempl<T> {
306         fn from(v: Vec<T>) -> Self {
307                 let datalen = v.len();
308                 let data = Box::into_raw(v.into_boxed_slice());
309                 CVecTempl { datalen, data: unsafe { (*data).as_mut_ptr() } }
310         }
311 }
312 pub extern "C" fn CVecTempl_free<T>(_res: CVecTempl<T>) { }
313 impl<T> Drop for CVecTempl<T> {
314         fn drop(&mut self) {
315                 if self.datalen == 0 { return; }
316                 unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
317         }
318 }
319 impl<T: Clone> Clone for CVecTempl<T> {
320         fn clone(&self) -> Self {
321                 let mut res = Vec::new();
322                 if self.datalen == 0 { return Self::from(res); }
323                 res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
324                 Self::from(res)
325         }
326 }
327
328 #[repr(C)]
329 pub struct C2TupleTempl<A, B> {
330         pub a: A,
331         pub b: B,
332 }
333 impl<A, B> From<(A, B)> for C2TupleTempl<A, B> {
334         fn from(tup: (A, B)) -> Self {
335                 Self {
336                         a: tup.0,
337                         b: tup.1,
338                 }
339         }
340 }
341 impl<A, B> C2TupleTempl<A, B> {
342         pub(crate) fn to_rust(mut self) -> (A, B) {
343                 (self.a, self.b)
344         }
345 }
346 pub extern "C" fn C2TupleTempl_free<A, B>(_res: C2TupleTempl<A, B>) { }
347 impl <A: Clone, B: Clone> Clone for C2TupleTempl<A, B> {
348         fn clone(&self) -> Self {
349                 Self {
350                         a: self.a.clone(),
351                         b: self.b.clone()
352                 }
353         }
354 }
355
356 #[repr(C)]
357 pub struct C3TupleTempl<A, B, C> {
358         pub a: A,
359         pub b: B,
360         pub c: C,
361 }
362 impl<A, B, C> From<(A, B, C)> for C3TupleTempl<A, B, C> {
363         fn from(tup: (A, B, C)) -> Self {
364                 Self {
365                         a: tup.0,
366                         b: tup.1,
367                         c: tup.2,
368                 }
369         }
370 }
371 impl<A, B, C> C3TupleTempl<A, B, C> {
372         pub(crate) fn to_rust(mut self) -> (A, B, C) {
373                 (self.a, self.b, self.c)
374         }
375 }
376 pub extern "C" fn C3TupleTempl_free<A, B, C>(_res: C3TupleTempl<A, B, C>) { }
377
378 /// Utility to make it easy to set a pointer to null and get its original value in line.
379 pub(crate) trait TakePointer<T> {
380         fn take_ptr(&mut self) -> T;
381 }
382 impl<T> TakePointer<*const T> for *const T {
383         fn take_ptr(&mut self) -> *const T {
384                 let ret = *self;
385                 *self = std::ptr::null();
386                 ret
387         }
388 }
389 impl<T> TakePointer<*mut T> for *mut T {
390         fn take_ptr(&mut self) -> *mut T {
391                 let ret = *self;
392                 *self = std::ptr::null_mut();
393                 ret
394         }
395 }