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