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