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