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