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