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