Add support for witnesses via a manual mapping
[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 /// Frees the data pointed to by data
513 pub extern "C" fn Witness_free(_res: Witness) { }
514
515 pub(crate) fn bitcoin_to_C_outpoint(outpoint: ::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
516         crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: outpoint.txid.into_inner() }, outpoint.vout.try_into().unwrap())
517 }
518 pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
519         unsafe {
520                 ::bitcoin::blockdata::transaction::OutPoint {
521                         txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
522                 }
523         }
524 }
525
526 #[repr(C)]
527 #[derive(Clone)]
528 /// A transaction output including a scriptPubKey and value.
529 /// This type *does* own its own memory, so must be free'd appropriately.
530 pub struct TxOut {
531         /// The script_pubkey in this output
532         pub script_pubkey: derived::CVec_u8Z,
533         /// The value, in satoshis, of this output
534         pub value: u64,
535 }
536
537 impl TxOut {
538         pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
539                 ::bitcoin::blockdata::transaction::TxOut {
540                         script_pubkey: self.script_pubkey.into_rust().into(),
541                         value: self.value,
542                 }
543         }
544         pub(crate) fn from_rust(txout: ::bitcoin::blockdata::transaction::TxOut) -> Self {
545                 Self {
546                         script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.into_bytes()),
547                         value: txout.value
548                 }
549         }
550 }
551
552 #[no_mangle]
553 /// Convenience function for constructing a new TxOut
554 pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
555         TxOut { script_pubkey, value }
556 }
557 #[no_mangle]
558 /// Frees the data pointed to by script_pubkey.
559 pub extern "C" fn TxOut_free(_res: TxOut) { }
560 #[no_mangle]
561 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
562 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
563
564 #[repr(C)]
565 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
566 /// own the memory pointed to by data.
567 pub struct u8slice {
568         /// A pointer to the byte buffer
569         pub data: *const u8,
570         /// The number of bytes pointed to by `data`.
571         pub datalen: usize
572 }
573 impl u8slice {
574         pub(crate) fn from_slice(s: &[u8]) -> Self {
575                 Self {
576                         data: s.as_ptr(),
577                         datalen: s.len(),
578                 }
579         }
580         pub(crate) fn to_slice(&self) -> &[u8] {
581                 if self.datalen == 0 { return &[]; }
582                 unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
583         }
584         pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
585                 let sl = self.to_slice();
586                 Cursor::new(sl)
587         }
588         pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
589                 Self::from_slice(v.as_slice())
590         }
591 }
592 pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
593         let mut res = Vec::new();
594         r.read_to_end(&mut res).unwrap();
595         derived::CVec_u8Z::from(res)
596 }
597
598 #[repr(C)]
599 #[derive(Copy, Clone)]
600 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
601 /// look up the corresponding function in rust-lightning's docs.
602 pub struct ThirtyTwoBytes {
603         /// The thirty-two bytes
604         pub data: [u8; 32],
605 }
606 impl ThirtyTwoBytes {
607         pub(crate) fn null() -> Self {
608                 Self { data: [0; 32] }
609         }
610 }
611
612 #[repr(C)]
613 /// A 3-byte byte array.
614 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
615 #[derive(Clone)]
616 #[repr(C)]
617 /// A 4-byte byte array.
618 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
619 #[derive(Clone)]
620 #[repr(C)]
621 /// A 12-byte byte array.
622 pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
623 #[derive(Clone)]
624 #[repr(C)]
625 /// A 16-byte byte array.
626 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
627 #[derive(Clone)]
628 #[repr(C)]
629 /// A 20-byte byte array.
630 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
631
632 pub(crate) struct VecWriter(pub Vec<u8>);
633 impl lightning::util::ser::Writer for VecWriter {
634         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
635                 self.0.extend_from_slice(buf);
636                 Ok(())
637         }
638 }
639 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
640         let mut out = VecWriter(Vec::new());
641         i.write(&mut out).unwrap();
642         derived::CVec_u8Z::from(out.0)
643 }
644 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
645         I::read(&mut s.to_slice())
646 }
647 pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
648         I::read(&mut s.to_slice())
649 }
650 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
651         I::read(&mut s.to_slice(), args)
652 }
653
654 #[repr(C)]
655 /// A Rust str object, ie a reference to a UTF8-valid string.
656 /// This is *not* null-terminated so cannot be used directly as a C string!
657 pub struct Str {
658         /// A pointer to the string's bytes, in UTF8 encoding
659         pub chars: *const u8,
660         /// The number of bytes (not characters!) pointed to by `chars`
661         pub len: usize,
662         /// Whether the data pointed to by `chars` should be freed or not.
663         pub chars_is_owned: bool,
664 }
665 impl Into<Str> for &'static str {
666         fn into(self) -> Str {
667                 Str { chars: self.as_ptr(), len: self.len(), chars_is_owned: false }
668         }
669 }
670 impl Into<Str> for &mut &'static str {
671         fn into(self) -> Str {
672                 let us: &'static str = *self;
673                 us.into()
674         }
675 }
676
677 impl Str {
678         pub(crate) fn into_str(&self) -> &'static str {
679                 if self.len == 0 { return ""; }
680                 core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
681         }
682         pub(crate) fn into_string(mut self) -> String {
683                 let bytes = if self.len == 0 {
684                         Vec::new()
685                 } else if self.chars_is_owned {
686                         let ret = unsafe {
687                                 Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
688                         }.into();
689                         self.chars_is_owned = false;
690                         ret
691                 } else {
692                         let mut ret = Vec::with_capacity(self.len);
693                         ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
694                         ret
695                 };
696                 String::from_utf8(bytes).unwrap()
697         }
698 }
699 impl Into<Str> for String {
700         fn into(self) -> Str {
701                 let s = Box::leak(self.into_boxed_str());
702                 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
703         }
704 }
705 impl Clone for Str {
706         fn clone(&self) -> Self {
707                 String::from(self.into_str()).into()
708         }
709 }
710
711 impl Drop for Str {
712         fn drop(&mut self) {
713                 if self.chars_is_owned && self.len != 0 {
714                         let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
715                 }
716         }
717 }
718 #[no_mangle]
719 /// Frees the data buffer, if chars_is_owned is set and len > 0.
720 pub extern "C" fn Str_free(_res: Str) { }
721
722 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
723 // Thus, they must gracefully handle being completely null in _free.
724
725 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
726 // everywhere in the containers.
727
728 #[repr(C)]
729 pub(crate) union CResultPtr<O, E> {
730         pub(crate) result: *mut O,
731         pub(crate) err: *mut E,
732 }
733 #[repr(C)]
734 pub(crate) struct CResultTempl<O, E> {
735         pub(crate) contents: CResultPtr<O, E>,
736         pub(crate) result_ok: bool,
737 }
738 impl<O, E> CResultTempl<O, E> {
739         pub(crate) extern "C" fn ok(o: O) -> Self {
740                 CResultTempl {
741                         contents: CResultPtr {
742                                 result: Box::into_raw(Box::new(o)),
743                         },
744                         result_ok: true,
745                 }
746         }
747         pub(crate) extern "C" fn err(e: E) -> Self {
748                 CResultTempl {
749                         contents: CResultPtr {
750                                 err: Box::into_raw(Box::new(e)),
751                         },
752                         result_ok: false,
753                 }
754         }
755 }
756 impl<O, E> Drop for CResultTempl<O, E> {
757         fn drop(&mut self) {
758                 if self.result_ok {
759                         if unsafe { !self.contents.result.is_null() } {
760                                 let _ = unsafe { Box::from_raw(self.contents.result) };
761                         }
762                 } else if unsafe { !self.contents.err.is_null() } {
763                         let _ = unsafe { Box::from_raw(self.contents.err) };
764                 }
765         }
766 }
767
768 /// Utility to make it easy to set a pointer to null and get its original value in line.
769 pub(crate) trait TakePointer<T> {
770         fn take_ptr(&mut self) -> T;
771 }
772 impl<T> TakePointer<*const T> for *const T {
773         fn take_ptr(&mut self) -> *const T {
774                 let ret = *self;
775                 *self = core::ptr::null();
776                 ret
777         }
778 }
779 impl<T> TakePointer<*mut T> for *mut T {
780         fn take_ptr(&mut self) -> *mut T {
781                 let ret = *self;
782                 *self = core::ptr::null_mut();
783                 ret
784         }
785 }
786
787
788 pub(crate) mod ObjOps {
789         #[cfg(feature = "no-std")]
790         use alloc::boxed::Box;
791
792         #[inline]
793         #[must_use = "returns new dangling pointer"]
794         pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
795                 let ptr = Box::into_raw(Box::new(obj));
796                 nonnull_ptr_to_inner(ptr)
797         }
798         #[inline]
799         pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
800                 if core::mem::size_of::<T>() == 0 {
801                         // We map `None::<T>` as `T { inner: null, .. }` which works great for all
802                         // non-Zero-Sized-Types `T`.
803                         // For ZSTs, we need to differentiate between null implying `None` and null implying
804                         // `Some` with no allocation.
805                         // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
806                         // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
807                         // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
808                         // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
809                         // fine.
810                         // Note that we add 4095 here as at least the Java client assumes that the low bit on
811                         // any heap pointer is 0, which is generally provided by malloc, but which is not true
812                         // for ZSTs "allocated" by `Box::new`.
813                         debug_assert_eq!(ptr as usize, 1);
814                         unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
815                 } else {
816                         // In order to get better test coverage, also increment non-ZST pointers with
817                         // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
818                         #[cfg(test_mod_pointers)]
819                         unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
820                         #[cfg(not(test_mod_pointers))]
821                         unsafe { ptr as *mut T }
822                 }
823         }
824         #[inline]
825         /// Invert nonnull_ptr_to_inner
826         pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
827                 if core::mem::size_of::<T>() == 0 {
828                         unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
829                 } else {
830                         #[cfg(test_mod_pointers)]
831                         unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
832                         #[cfg(not(test_mod_pointers))]
833                         ptr
834                 }
835         }
836 }
837
838 #[cfg(test_mod_pointers)]
839 #[no_mangle]
840 /// This function exists for memory safety testing purposes. It should never be used in production
841 /// code
842 pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
843         if ptr as usize == 1 {
844                 core::ptr::null()
845         } else {
846                 unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
847         }
848 }
849
850 pub(crate) struct SmartPtr<T> {
851         ptr: *mut T,
852 }
853 impl<T> SmartPtr<T> {
854         pub(crate) fn from_obj(o: T) -> Self {
855                 Self { ptr: Box::into_raw(Box::new(o)) }
856         }
857         pub(crate) fn null() -> Self {
858                 Self { ptr: core::ptr::null_mut() }
859         }
860 }
861 impl<T> Drop for SmartPtr<T> {
862         fn drop(&mut self) {
863                 if self.ptr != core::ptr::null_mut() {
864                         let _ = unsafe { Box::from_raw(self.ptr) };
865                 }
866         }
867 }
868 impl<T> core::ops::Deref for SmartPtr<T> {
869         type Target = *mut T;
870         fn deref(&self) -> &*mut T {
871                 &self.ptr
872         }
873 }