71aa6793cc25c9c3f2de853dedb9de0ff90e5f2b
[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::PublicKey as SecpPublicKey;
9 use bitcoin::secp256k1::SecretKey as SecpSecretKey;
10 use bitcoin::secp256k1::ecdsa::Signature as SecpSignature;
11 use bitcoin::secp256k1::Error as SecpError;
12 use bitcoin::secp256k1::ecdsa::RecoveryId;
13 use bitcoin::secp256k1::ecdsa::RecoverableSignature as SecpRecoverableSignature;
14 use bitcoin::bech32;
15
16 use core::convert::TryInto; // Bindings need at least rustc 1.34
17 use core::ffi::c_void;
18
19 #[cfg(feature = "std")]
20 pub(crate) use std::io::{self, Cursor, Read};
21 #[cfg(feature = "no-std")]
22 pub(crate) use core2::io::{self, Cursor, Read};
23 #[cfg(feature = "no-std")]
24 use alloc::{boxed::Box, vec::Vec, string::String};
25
26 #[repr(C)]
27 /// A dummy struct of which an instance must never exist.
28 /// This corresponds to the Rust type `Infallible`, or, in unstable rust, `!`
29 pub struct NotConstructable {
30         _priv_thing: core::convert::Infallible,
31 }
32 impl From<core::convert::Infallible> for NotConstructable {
33         fn from(_: core::convert::Infallible) -> Self { unreachable!(); }
34 }
35
36 /// Integer in the range `0..32`
37 #[derive(PartialEq, Eq, Copy, Clone)]
38 #[allow(non_camel_case_types)]
39 #[repr(C)]
40 pub struct u5(u8);
41
42 impl From<bech32::u5> for u5 {
43         fn from(o: bech32::u5) -> Self { Self(o.to_u8()) }
44 }
45 impl Into<bech32::u5> for u5 {
46         fn into(self) -> bech32::u5 { bech32::u5::try_from_u8(self.0).expect("u5 objects must be in the range 0..32") }
47 }
48
49 #[derive(Clone)]
50 #[repr(C)]
51 /// Represents a valid secp256k1 public key serialized in "compressed form" as a 33 byte array.
52 pub struct PublicKey {
53         /// The bytes of the public key
54         pub compressed_form: [u8; 33],
55 }
56 impl PublicKey {
57         pub(crate) fn from_rust(pk: &SecpPublicKey) -> Self {
58                 Self {
59                         compressed_form: pk.serialize(),
60                 }
61         }
62         pub(crate) fn into_rust(&self) -> SecpPublicKey {
63                 SecpPublicKey::from_slice(&self.compressed_form).unwrap()
64         }
65         pub(crate) fn is_null(&self) -> bool { self.compressed_form[..] == [0; 33][..] }
66         pub(crate) fn null() -> Self { Self { compressed_form: [0; 33] } }
67 }
68
69 #[repr(C)]
70 #[derive(Clone)]
71 /// Represents a valid secp256k1 secret key serialized as a 32 byte array.
72 pub struct SecretKey {
73         /// The bytes of the secret key
74         pub bytes: [u8; 32],
75 }
76 impl SecretKey {
77         // from_rust isn't implemented for a ref since we just return byte array refs directly
78         pub(crate) fn from_rust(sk: SecpSecretKey) -> Self {
79                 let mut bytes = [0; 32];
80                 bytes.copy_from_slice(&sk[..]);
81                 Self { bytes }
82         }
83         pub(crate) fn into_rust(&self) -> SecpSecretKey {
84                 SecpSecretKey::from_slice(&self.bytes).unwrap()
85         }
86 }
87
88 #[repr(C)]
89 #[derive(Clone)]
90 /// Represents a secp256k1 signature serialized as two 32-byte numbers
91 pub struct Signature {
92         /// The bytes of the signature in "compact" form
93         pub compact_form: [u8; 64],
94 }
95 impl Signature {
96         pub(crate) fn from_rust(pk: &SecpSignature) -> Self {
97                 Self {
98                         compact_form: pk.serialize_compact(),
99                 }
100         }
101         pub(crate) fn into_rust(&self) -> SecpSignature {
102                 SecpSignature::from_compact(&self.compact_form).unwrap()
103         }
104         // The following are used for Option<Signature> which we support, but don't use anymore
105         #[allow(unused)] pub(crate) fn is_null(&self) -> bool { self.compact_form[..] == [0; 64][..] }
106         #[allow(unused)] pub(crate) fn null() -> Self { Self { compact_form: [0; 64] } }
107 }
108
109 #[repr(C)]
110 #[derive(Clone)]
111 /// Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which
112 /// allows recovering the exact public key which created the signature given the message.
113 pub struct RecoverableSignature {
114         /// The bytes of the signature in "compact" form plus a "Recovery ID" which allows for
115         /// recovery.
116         pub serialized_form: [u8; 68],
117 }
118 impl RecoverableSignature {
119         pub(crate) fn from_rust(pk: &SecpRecoverableSignature) -> Self {
120                 let (id, compact_form) = pk.serialize_compact();
121                 let mut serialized_form = [0; 68];
122                 serialized_form[0..64].copy_from_slice(&compact_form[..]);
123                 serialized_form[64..].copy_from_slice(&id.to_i32().to_le_bytes());
124                 Self { serialized_form }
125         }
126         pub(crate) fn into_rust(&self) -> SecpRecoverableSignature {
127                 let mut id = [0; 4];
128                 id.copy_from_slice(&self.serialized_form[64..]);
129                 SecpRecoverableSignature::from_compact(&self.serialized_form[0..64],
130                                 RecoveryId::from_i32(i32::from_le_bytes(id)).expect("Invalid Recovery ID"))
131                         .unwrap()
132         }
133 }
134
135 #[repr(C)]
136 #[derive(Copy, Clone)]
137 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
138 pub enum Secp256k1Error {
139         /// Signature failed verification
140         IncorrectSignature,
141         /// Badly sized message ("messages" are actually fixed-sized digests; see the MESSAGE_SIZE constant)
142         InvalidMessage,
143         /// Bad public key
144         InvalidPublicKey,
145         /// Bad signature
146         InvalidSignature,
147         /// Bad secret key
148         InvalidSecretKey,
149         /// Bad shared secret.
150         InvalidSharedSecret,
151         /// Bad recovery id
152         InvalidRecoveryId,
153         /// Invalid tweak for add_assign or mul_assign
154         InvalidTweak,
155         /// Didn't pass enough memory to context creation with preallocated memory
156         NotEnoughMemory,
157         /// Bad set of public keys.
158         InvalidPublicKeySum,
159         /// The only valid parity values are 0 or 1.
160         InvalidParityValue,
161 }
162 impl Secp256k1Error {
163         pub(crate) fn from_rust(err: SecpError) -> Self {
164                 match err {
165                         SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
166                         SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
167                         SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
168                         SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
169                         SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
170                         SecpError::InvalidSharedSecret => Secp256k1Error::InvalidSharedSecret,
171                         SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
172                         SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
173                         SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
174                         SecpError::InvalidPublicKeySum => Secp256k1Error::InvalidPublicKeySum,
175                         SecpError::InvalidParityValue(_) => Secp256k1Error::InvalidParityValue,
176                 }
177         }
178         pub(crate) fn into_rust(self) -> SecpError {
179                 let invalid_parity = secp256k1::Parity::from_i32(42).unwrap_err();
180                 match self {
181                         Secp256k1Error::IncorrectSignature => SecpError::IncorrectSignature,
182                         Secp256k1Error::InvalidMessage => SecpError::InvalidMessage,
183                         Secp256k1Error::InvalidPublicKey => SecpError::InvalidPublicKey,
184                         Secp256k1Error::InvalidSignature => SecpError::InvalidSignature,
185                         Secp256k1Error::InvalidSecretKey => SecpError::InvalidSecretKey,
186                         Secp256k1Error::InvalidSharedSecret => SecpError::InvalidSharedSecret,
187                         Secp256k1Error::InvalidRecoveryId => SecpError::InvalidRecoveryId,
188                         Secp256k1Error::InvalidTweak => SecpError::InvalidTweak,
189                         Secp256k1Error::NotEnoughMemory => SecpError::NotEnoughMemory,
190                         Secp256k1Error::InvalidPublicKeySum => SecpError::InvalidPublicKeySum,
191                         Secp256k1Error::InvalidParityValue => SecpError::InvalidParityValue(invalid_parity),
192                 }
193         }
194 }
195
196 #[repr(C)]
197 #[derive(Copy, Clone)]
198 /// Represents an error returned from the bech32 library during validation of some bech32 data
199 pub enum Bech32Error {
200         /// String does not contain the separator character
201         MissingSeparator,
202         /// The checksum does not match the rest of the data
203         InvalidChecksum,
204         /// The data or human-readable part is too long or too short
205         InvalidLength,
206         /// Some part of the string contains an invalid character
207         InvalidChar(u32),
208         /// Some part of the data has an invalid value
209         InvalidData(u8),
210         /// The bit conversion failed due to a padding issue
211         InvalidPadding,
212         /// The whole string must be of one case
213         MixedCase,
214 }
215 impl Bech32Error {
216         pub(crate) fn from_rust(err: bech32::Error) -> Self {
217                 match err {
218                         bech32::Error::MissingSeparator => Self::MissingSeparator,
219                         bech32::Error::InvalidChecksum => Self::InvalidChecksum,
220                         bech32::Error::InvalidLength => Self::InvalidLength,
221                         bech32::Error::InvalidChar(c) => Self::InvalidChar(c as u32),
222                         bech32::Error::InvalidData(d) => Self::InvalidData(d),
223                         bech32::Error::InvalidPadding => Self::InvalidPadding,
224                         bech32::Error::MixedCase => Self::MixedCase,
225                 }
226         }
227         pub(crate) fn into_rust(self) -> bech32::Error {
228                 match self {
229                         Self::MissingSeparator => bech32::Error::MissingSeparator,
230                         Self::InvalidChecksum => bech32::Error::InvalidChecksum,
231                         Self::InvalidLength => bech32::Error::InvalidLength,
232                         Self::InvalidChar(c) => bech32::Error::InvalidChar(core::char::from_u32(c).expect("Invalid UTF-8 character in Bech32Error::InvalidChar")),
233                         Self::InvalidData(d) => bech32::Error::InvalidData(d),
234                         Self::InvalidPadding => bech32::Error::InvalidPadding,
235                         Self::MixedCase => bech32::Error::MixedCase,
236                 }
237         }
238 }
239 #[no_mangle]
240 /// Creates a new Bech32Error which has the same data as `orig`
241 pub extern "C" fn Bech32Error_clone(orig: &Bech32Error) -> Bech32Error { orig.clone() }
242 #[no_mangle]
243 /// Releases any memory held by the given `Bech32Error` (which is currently none)
244 pub extern "C" fn Bech32Error_free(o: Bech32Error) { }
245
246 #[repr(C)]
247 #[derive(Clone, Copy, PartialEq)]
248 /// Sub-errors which don't have specific information in them use this type.
249 pub struct Error {
250         /// Zero-Sized_types aren't consistent across Rust/C/C++, so we add some size here
251         pub _dummy: u8,
252 }
253
254 #[repr(C)]
255 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
256 #[derive(Clone, Copy, PartialEq)]
257 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
258 pub enum IOError {
259         NotFound,
260         PermissionDenied,
261         ConnectionRefused,
262         ConnectionReset,
263         ConnectionAborted,
264         NotConnected,
265         AddrInUse,
266         AddrNotAvailable,
267         BrokenPipe,
268         AlreadyExists,
269         WouldBlock,
270         InvalidInput,
271         InvalidData,
272         TimedOut,
273         WriteZero,
274         Interrupted,
275         Other,
276         UnexpectedEof,
277 }
278 #[cfg(feature = "std")]
279 impl IOError {
280         pub(crate) fn from_rust(err: std::io::Error) -> Self {
281                 match err.kind() {
282                         std::io::ErrorKind::NotFound => IOError::NotFound,
283                         std::io::ErrorKind::PermissionDenied => IOError::PermissionDenied,
284                         std::io::ErrorKind::ConnectionRefused => IOError::ConnectionRefused,
285                         std::io::ErrorKind::ConnectionReset => IOError::ConnectionReset,
286                         std::io::ErrorKind::ConnectionAborted => IOError::ConnectionAborted,
287                         std::io::ErrorKind::NotConnected => IOError::NotConnected,
288                         std::io::ErrorKind::AddrInUse => IOError::AddrInUse,
289                         std::io::ErrorKind::AddrNotAvailable => IOError::AddrNotAvailable,
290                         std::io::ErrorKind::BrokenPipe => IOError::BrokenPipe,
291                         std::io::ErrorKind::AlreadyExists => IOError::AlreadyExists,
292                         std::io::ErrorKind::WouldBlock => IOError::WouldBlock,
293                         std::io::ErrorKind::InvalidInput => IOError::InvalidInput,
294                         std::io::ErrorKind::InvalidData => IOError::InvalidData,
295                         std::io::ErrorKind::TimedOut => IOError::TimedOut,
296                         std::io::ErrorKind::WriteZero => IOError::WriteZero,
297                         std::io::ErrorKind::Interrupted => IOError::Interrupted,
298                         std::io::ErrorKind::Other => IOError::Other,
299                         std::io::ErrorKind::UnexpectedEof => IOError::UnexpectedEof,
300                         _ => IOError::Other,
301                 }
302         }
303         pub(crate) fn to_rust(&self) -> std::io::Error {
304                 std::io::Error::new(match self {
305                         IOError::NotFound => std::io::ErrorKind::NotFound,
306                         IOError::PermissionDenied => std::io::ErrorKind::PermissionDenied,
307                         IOError::ConnectionRefused => std::io::ErrorKind::ConnectionRefused,
308                         IOError::ConnectionReset => std::io::ErrorKind::ConnectionReset,
309                         IOError::ConnectionAborted => std::io::ErrorKind::ConnectionAborted,
310                         IOError::NotConnected => std::io::ErrorKind::NotConnected,
311                         IOError::AddrInUse => std::io::ErrorKind::AddrInUse,
312                         IOError::AddrNotAvailable => std::io::ErrorKind::AddrNotAvailable,
313                         IOError::BrokenPipe => std::io::ErrorKind::BrokenPipe,
314                         IOError::AlreadyExists => std::io::ErrorKind::AlreadyExists,
315                         IOError::WouldBlock => std::io::ErrorKind::WouldBlock,
316                         IOError::InvalidInput => std::io::ErrorKind::InvalidInput,
317                         IOError::InvalidData => std::io::ErrorKind::InvalidData,
318                         IOError::TimedOut => std::io::ErrorKind::TimedOut,
319                         IOError::WriteZero => std::io::ErrorKind::WriteZero,
320                         IOError::Interrupted => std::io::ErrorKind::Interrupted,
321                         IOError::Other => std::io::ErrorKind::Other,
322                         IOError::UnexpectedEof => std::io::ErrorKind::UnexpectedEof,
323                 }, "")
324         }
325 }
326
327 #[repr(C)]
328 /// A serialized transaction, in (pointer, length) form.
329 ///
330 /// This type optionally owns its own memory, and thus the semantics around access change based on
331 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
332 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
333 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
334 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
335 /// you would be invalid.
336 ///
337 /// Note that, while it may change in the future, because transactions on the Rust side are stored
338 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
339 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
340 /// `data_is_owned` either set or unset at your discretion.
341 pub struct Transaction {
342         /// The serialized transaction data.
343         ///
344         /// This is non-const for your convenience, an object passed to Rust is never written to.
345         pub data: *mut u8,
346         /// The length of the serialized transaction
347         pub datalen: usize,
348         /// Whether the data pointed to by `data` should be freed or not.
349         pub data_is_owned: bool,
350 }
351 impl Transaction {
352         fn from_vec(vec: Vec<u8>) -> Self {
353                 let datalen = vec.len();
354                 let data = Box::into_raw(vec.into_boxed_slice());
355                 Self {
356                         data: unsafe { (*data).as_mut_ptr() },
357                         datalen,
358                         data_is_owned: true,
359                 }
360         }
361         pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
362                 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
363                 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
364         }
365         pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
366                 let vec = ::bitcoin::consensus::encode::serialize(btc);
367                 Self::from_vec(vec)
368         }
369 }
370 impl Drop for Transaction {
371         fn drop(&mut self) {
372                 if self.data_is_owned && self.datalen != 0 {
373                         let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
374                 }
375         }
376 }
377 impl Clone for Transaction {
378         fn clone(&self) -> Self {
379                 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
380                 let mut v = Vec::new();
381                 v.extend_from_slice(&sl);
382                 Self::from_vec(v)
383         }
384 }
385 #[no_mangle]
386 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
387 pub extern "C" fn Transaction_free(_res: Transaction) { }
388
389 pub(crate) fn bitcoin_to_C_outpoint(outpoint: ::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
390         crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: outpoint.txid.into_inner() }, outpoint.vout.try_into().unwrap())
391 }
392 pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
393         unsafe {
394                 ::bitcoin::blockdata::transaction::OutPoint {
395                         txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
396                 }
397         }
398 }
399
400 #[repr(C)]
401 #[derive(Clone)]
402 /// A transaction output including a scriptPubKey and value.
403 /// This type *does* own its own memory, so must be free'd appropriately.
404 pub struct TxOut {
405         /// The script_pubkey in this output
406         pub script_pubkey: derived::CVec_u8Z,
407         /// The value, in satoshis, of this output
408         pub value: u64,
409 }
410
411 impl TxOut {
412         pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
413                 ::bitcoin::blockdata::transaction::TxOut {
414                         script_pubkey: self.script_pubkey.into_rust().into(),
415                         value: self.value,
416                 }
417         }
418         pub(crate) fn from_rust(txout: ::bitcoin::blockdata::transaction::TxOut) -> Self {
419                 Self {
420                         script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.into_bytes()),
421                         value: txout.value
422                 }
423         }
424 }
425
426 #[no_mangle]
427 /// Convenience function for constructing a new TxOut
428 pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
429         TxOut { script_pubkey, value }
430 }
431 #[no_mangle]
432 /// Frees the data pointed to by script_pubkey.
433 pub extern "C" fn TxOut_free(_res: TxOut) { }
434 #[no_mangle]
435 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
436 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
437
438 #[repr(C)]
439 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
440 /// own the memory pointed to by data.
441 pub struct u8slice {
442         /// A pointer to the byte buffer
443         pub data: *const u8,
444         /// The number of bytes pointed to by `data`.
445         pub datalen: usize
446 }
447 impl u8slice {
448         pub(crate) fn from_slice(s: &[u8]) -> Self {
449                 Self {
450                         data: s.as_ptr(),
451                         datalen: s.len(),
452                 }
453         }
454         pub(crate) fn to_slice(&self) -> &[u8] {
455                 if self.datalen == 0 { return &[]; }
456                 unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
457         }
458         pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
459                 let sl = self.to_slice();
460                 Cursor::new(sl)
461         }
462         pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
463                 Self::from_slice(v.as_slice())
464         }
465 }
466 pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
467         let mut res = Vec::new();
468         r.read_to_end(&mut res).unwrap();
469         derived::CVec_u8Z::from(res)
470 }
471
472 #[repr(C)]
473 #[derive(Copy, Clone)]
474 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
475 /// look up the corresponding function in rust-lightning's docs.
476 pub struct ThirtyTwoBytes {
477         /// The thirty-two bytes
478         pub data: [u8; 32],
479 }
480 impl ThirtyTwoBytes {
481         pub(crate) fn null() -> Self {
482                 Self { data: [0; 32] }
483         }
484 }
485
486 #[repr(C)]
487 /// A 3-byte byte array.
488 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
489 #[derive(Clone)]
490 #[repr(C)]
491 /// A 4-byte byte array.
492 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
493 #[derive(Clone)]
494 #[repr(C)]
495 /// A 12-byte byte array.
496 pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
497 #[derive(Clone)]
498 #[repr(C)]
499 /// A 16-byte byte array.
500 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
501 #[derive(Clone)]
502 #[repr(C)]
503 /// A 20-byte byte array.
504 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
505
506 pub(crate) struct VecWriter(pub Vec<u8>);
507 impl lightning::util::ser::Writer for VecWriter {
508         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
509                 self.0.extend_from_slice(buf);
510                 Ok(())
511         }
512 }
513 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
514         let mut out = VecWriter(Vec::new());
515         i.write(&mut out).unwrap();
516         derived::CVec_u8Z::from(out.0)
517 }
518 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
519         I::read(&mut s.to_slice())
520 }
521 pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
522         I::read(&mut s.to_slice())
523 }
524 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
525         I::read(&mut s.to_slice(), args)
526 }
527
528 #[repr(C)]
529 /// A Rust str object, ie a reference to a UTF8-valid string.
530 /// This is *not* null-terminated so cannot be used directly as a C string!
531 pub struct Str {
532         /// A pointer to the string's bytes, in UTF8 encoding
533         pub chars: *const u8,
534         /// The number of bytes (not characters!) pointed to by `chars`
535         pub len: usize,
536         /// Whether the data pointed to by `chars` should be freed or not.
537         pub chars_is_owned: bool,
538 }
539 impl Into<Str> for &'static str {
540         fn into(self) -> Str {
541                 Str { chars: self.as_ptr(), len: self.len(), chars_is_owned: false }
542         }
543 }
544 impl Into<Str> for &mut &'static str {
545         fn into(self) -> Str {
546                 let us: &'static str = *self;
547                 us.into()
548         }
549 }
550
551 impl Str {
552         pub(crate) fn into_str(&self) -> &'static str {
553                 if self.len == 0 { return ""; }
554                 core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
555         }
556         pub(crate) fn into_string(mut self) -> String {
557                 let bytes = if self.len == 0 {
558                         Vec::new()
559                 } else if self.chars_is_owned {
560                         let ret = unsafe {
561                                 Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
562                         }.into();
563                         self.chars_is_owned = false;
564                         ret
565                 } else {
566                         let mut ret = Vec::with_capacity(self.len);
567                         ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
568                         ret
569                 };
570                 String::from_utf8(bytes).unwrap()
571         }
572 }
573 impl Into<Str> for String {
574         fn into(self) -> Str {
575                 let s = Box::leak(self.into_boxed_str());
576                 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
577         }
578 }
579 impl Clone for Str {
580         fn clone(&self) -> Self {
581                 String::from(self.into_str()).into()
582         }
583 }
584
585 impl Drop for Str {
586         fn drop(&mut self) {
587                 if self.chars_is_owned && self.len != 0 {
588                         let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
589                 }
590         }
591 }
592 #[no_mangle]
593 /// Frees the data buffer, if chars_is_owned is set and len > 0.
594 pub extern "C" fn Str_free(_res: Str) { }
595
596 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
597 // Thus, they must gracefully handle being completely null in _free.
598
599 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
600 // everywhere in the containers.
601
602 #[repr(C)]
603 pub(crate) union CResultPtr<O, E> {
604         pub(crate) result: *mut O,
605         pub(crate) err: *mut E,
606 }
607 #[repr(C)]
608 pub(crate) struct CResultTempl<O, E> {
609         pub(crate) contents: CResultPtr<O, E>,
610         pub(crate) result_ok: bool,
611 }
612 impl<O, E> CResultTempl<O, E> {
613         pub(crate) extern "C" fn ok(o: O) -> Self {
614                 CResultTempl {
615                         contents: CResultPtr {
616                                 result: Box::into_raw(Box::new(o)),
617                         },
618                         result_ok: true,
619                 }
620         }
621         pub(crate) extern "C" fn err(e: E) -> Self {
622                 CResultTempl {
623                         contents: CResultPtr {
624                                 err: Box::into_raw(Box::new(e)),
625                         },
626                         result_ok: false,
627                 }
628         }
629 }
630 impl<O, E> Drop for CResultTempl<O, E> {
631         fn drop(&mut self) {
632                 if self.result_ok {
633                         if unsafe { !self.contents.result.is_null() } {
634                                 unsafe { Box::from_raw(self.contents.result) };
635                         }
636                 } else if unsafe { !self.contents.err.is_null() } {
637                         unsafe { Box::from_raw(self.contents.err) };
638                 }
639         }
640 }
641
642 /// Utility to make it easy to set a pointer to null and get its original value in line.
643 pub(crate) trait TakePointer<T> {
644         fn take_ptr(&mut self) -> T;
645 }
646 impl<T> TakePointer<*const T> for *const T {
647         fn take_ptr(&mut self) -> *const T {
648                 let ret = *self;
649                 *self = core::ptr::null();
650                 ret
651         }
652 }
653 impl<T> TakePointer<*mut T> for *mut T {
654         fn take_ptr(&mut self) -> *mut T {
655                 let ret = *self;
656                 *self = core::ptr::null_mut();
657                 ret
658         }
659 }
660
661
662 pub(crate) mod ObjOps {
663         #[cfg(feature = "no-std")]
664         use alloc::boxed::Box;
665
666         #[inline]
667         #[must_use = "returns new dangling pointer"]
668         pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
669                 let ptr = Box::into_raw(Box::new(obj));
670                 nonnull_ptr_to_inner(ptr)
671         }
672         #[inline]
673         pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
674                 if core::mem::size_of::<T>() == 0 {
675                         // We map `None::<T>` as `T { inner: null, .. }` which works great for all
676                         // non-Zero-Sized-Types `T`.
677                         // For ZSTs, we need to differentiate between null implying `None` and null implying
678                         // `Some` with no allocation.
679                         // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
680                         // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
681                         // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
682                         // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
683                         // fine.
684                         // Note that we add 4095 here as at least the Java client assumes that the low bit on
685                         // any heap pointer is 0, which is generally provided by malloc, but which is not true
686                         // for ZSTs "allocated" by `Box::new`.
687                         debug_assert_eq!(ptr as usize, 1);
688                         unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
689                 } else {
690                         // In order to get better test coverage, also increment non-ZST pointers with
691                         // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
692                         #[cfg(test_mod_pointers)]
693                         unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
694                         #[cfg(not(test_mod_pointers))]
695                         unsafe { ptr as *mut T }
696                 }
697         }
698         #[inline]
699         /// Invert nonnull_ptr_to_inner
700         pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
701                 if core::mem::size_of::<T>() == 0 {
702                         unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
703                 } else {
704                         #[cfg(test_mod_pointers)]
705                         unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
706                         #[cfg(not(test_mod_pointers))]
707                         ptr
708                 }
709         }
710 }
711
712 #[cfg(test_mod_pointers)]
713 #[no_mangle]
714 /// This function exists for memory safety testing purposes. It should never be used in production
715 /// code
716 pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
717         if ptr as usize == 1 {
718                 core::ptr::null()
719         } else {
720                 unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
721         }
722 }
723
724 pub(crate) struct SmartPtr<T> {
725         ptr: *mut T,
726 }
727 impl<T> SmartPtr<T> {
728         pub(crate) fn from_obj(o: T) -> Self {
729                 Self { ptr: Box::into_raw(Box::new(o)) }
730         }
731         pub(crate) fn null() -> Self {
732                 Self { ptr: core::ptr::null_mut() }
733         }
734 }
735 impl<T> Drop for SmartPtr<T> {
736         fn drop(&mut self) {
737                 if self.ptr != core::ptr::null_mut() {
738                         unsafe { Box::from_raw(self.ptr); }
739                 }
740         }
741 }
742 impl<T> core::ops::Deref for SmartPtr<T> {
743         type Target = *mut T;
744         fn deref(&self) -> &*mut T {
745                 &self.ptr
746         }
747 }