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