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