Add a `TweakedPubKey` to mirror `bitcoin::key::TweakedPublicKey`
[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
296 #[repr(C)]
297 #[derive(Copy, Clone)]
298 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
299 pub enum Secp256k1Error {
300         /// Signature failed verification
301         IncorrectSignature,
302         /// Badly sized message ("messages" are actually fixed-sized digests; see the MESSAGE_SIZE constant)
303         InvalidMessage,
304         /// Bad public key
305         InvalidPublicKey,
306         /// Bad signature
307         InvalidSignature,
308         /// Bad secret key
309         InvalidSecretKey,
310         /// Bad shared secret.
311         InvalidSharedSecret,
312         /// Bad recovery id
313         InvalidRecoveryId,
314         /// Invalid tweak for add_assign or mul_assign
315         InvalidTweak,
316         /// Didn't pass enough memory to context creation with preallocated memory
317         NotEnoughMemory,
318         /// Bad set of public keys.
319         InvalidPublicKeySum,
320         /// The only valid parity values are 0 or 1.
321         InvalidParityValue,
322 }
323 impl Secp256k1Error {
324         pub(crate) fn from_rust(err: SecpError) -> Self {
325                 match err {
326                         SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
327                         SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
328                         SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
329                         SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
330                         SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
331                         SecpError::InvalidSharedSecret => Secp256k1Error::InvalidSharedSecret,
332                         SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
333                         SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
334                         SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
335                         SecpError::InvalidPublicKeySum => Secp256k1Error::InvalidPublicKeySum,
336                         SecpError::InvalidParityValue(_) => Secp256k1Error::InvalidParityValue,
337                 }
338         }
339         pub(crate) fn into_rust(self) -> SecpError {
340                 let invalid_parity = secp256k1::Parity::from_i32(42).unwrap_err();
341                 match self {
342                         Secp256k1Error::IncorrectSignature => SecpError::IncorrectSignature,
343                         Secp256k1Error::InvalidMessage => SecpError::InvalidMessage,
344                         Secp256k1Error::InvalidPublicKey => SecpError::InvalidPublicKey,
345                         Secp256k1Error::InvalidSignature => SecpError::InvalidSignature,
346                         Secp256k1Error::InvalidSecretKey => SecpError::InvalidSecretKey,
347                         Secp256k1Error::InvalidSharedSecret => SecpError::InvalidSharedSecret,
348                         Secp256k1Error::InvalidRecoveryId => SecpError::InvalidRecoveryId,
349                         Secp256k1Error::InvalidTweak => SecpError::InvalidTweak,
350                         Secp256k1Error::NotEnoughMemory => SecpError::NotEnoughMemory,
351                         Secp256k1Error::InvalidPublicKeySum => SecpError::InvalidPublicKeySum,
352                         Secp256k1Error::InvalidParityValue => SecpError::InvalidParityValue(invalid_parity),
353                 }
354         }
355 }
356
357 #[repr(C)]
358 #[derive(Copy, Clone)]
359 /// Represents an error returned from the bech32 library during validation of some bech32 data
360 pub enum Bech32Error {
361         /// String does not contain the separator character
362         MissingSeparator,
363         /// The checksum does not match the rest of the data
364         InvalidChecksum,
365         /// The data or human-readable part is too long or too short
366         InvalidLength,
367         /// Some part of the string contains an invalid character
368         InvalidChar(u32),
369         /// Some part of the data has an invalid value
370         InvalidData(u8),
371         /// The bit conversion failed due to a padding issue
372         InvalidPadding,
373         /// The whole string must be of one case
374         MixedCase,
375 }
376 impl Bech32Error {
377         pub(crate) fn from_rust(err: bech32::Error) -> Self {
378                 match err {
379                         bech32::Error::MissingSeparator => Self::MissingSeparator,
380                         bech32::Error::InvalidChecksum => Self::InvalidChecksum,
381                         bech32::Error::InvalidLength => Self::InvalidLength,
382                         bech32::Error::InvalidChar(c) => Self::InvalidChar(c as u32),
383                         bech32::Error::InvalidData(d) => Self::InvalidData(d),
384                         bech32::Error::InvalidPadding => Self::InvalidPadding,
385                         bech32::Error::MixedCase => Self::MixedCase,
386                 }
387         }
388         pub(crate) fn into_rust(self) -> bech32::Error {
389                 match self {
390                         Self::MissingSeparator => bech32::Error::MissingSeparator,
391                         Self::InvalidChecksum => bech32::Error::InvalidChecksum,
392                         Self::InvalidLength => bech32::Error::InvalidLength,
393                         Self::InvalidChar(c) => bech32::Error::InvalidChar(core::char::from_u32(c).expect("Invalid UTF-8 character in Bech32Error::InvalidChar")),
394                         Self::InvalidData(d) => bech32::Error::InvalidData(d),
395                         Self::InvalidPadding => bech32::Error::InvalidPadding,
396                         Self::MixedCase => bech32::Error::MixedCase,
397                 }
398         }
399 }
400 #[no_mangle]
401 /// Creates a new Bech32Error which has the same data as `orig`
402 pub extern "C" fn Bech32Error_clone(orig: &Bech32Error) -> Bech32Error { orig.clone() }
403 #[no_mangle]
404 /// Releases any memory held by the given `Bech32Error` (which is currently none)
405 pub extern "C" fn Bech32Error_free(o: Bech32Error) { }
406
407 #[repr(C)]
408 #[derive(Clone, Copy, PartialEq)]
409 /// Sub-errors which don't have specific information in them use this type.
410 pub struct Error {
411         /// Zero-Sized_types aren't consistent across Rust/C/C++, so we add some size here
412         pub _dummy: u8,
413 }
414
415 #[repr(C)]
416 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
417 #[derive(Clone, Copy, PartialEq)]
418 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
419 pub enum IOError {
420         NotFound,
421         PermissionDenied,
422         ConnectionRefused,
423         ConnectionReset,
424         ConnectionAborted,
425         NotConnected,
426         AddrInUse,
427         AddrNotAvailable,
428         BrokenPipe,
429         AlreadyExists,
430         WouldBlock,
431         InvalidInput,
432         InvalidData,
433         TimedOut,
434         WriteZero,
435         Interrupted,
436         Other,
437         UnexpectedEof,
438 }
439 impl IOError {
440         pub(crate) fn from_rust_kind(err: io::ErrorKind) -> Self {
441                 match err {
442                         io::ErrorKind::NotFound => IOError::NotFound,
443                         io::ErrorKind::PermissionDenied => IOError::PermissionDenied,
444                         io::ErrorKind::ConnectionRefused => IOError::ConnectionRefused,
445                         io::ErrorKind::ConnectionReset => IOError::ConnectionReset,
446                         io::ErrorKind::ConnectionAborted => IOError::ConnectionAborted,
447                         io::ErrorKind::NotConnected => IOError::NotConnected,
448                         io::ErrorKind::AddrInUse => IOError::AddrInUse,
449                         io::ErrorKind::AddrNotAvailable => IOError::AddrNotAvailable,
450                         io::ErrorKind::BrokenPipe => IOError::BrokenPipe,
451                         io::ErrorKind::AlreadyExists => IOError::AlreadyExists,
452                         io::ErrorKind::WouldBlock => IOError::WouldBlock,
453                         io::ErrorKind::InvalidInput => IOError::InvalidInput,
454                         io::ErrorKind::InvalidData => IOError::InvalidData,
455                         io::ErrorKind::TimedOut => IOError::TimedOut,
456                         io::ErrorKind::WriteZero => IOError::WriteZero,
457                         io::ErrorKind::Interrupted => IOError::Interrupted,
458                         io::ErrorKind::Other => IOError::Other,
459                         io::ErrorKind::UnexpectedEof => IOError::UnexpectedEof,
460                         _ => IOError::Other,
461                 }
462         }
463         pub(crate) fn from_rust(err: io::Error) -> Self {
464                 Self::from_rust_kind(err.kind())
465         }
466         pub(crate) fn to_rust_kind(&self) -> io::ErrorKind {
467                 match self {
468                         IOError::NotFound => io::ErrorKind::NotFound,
469                         IOError::PermissionDenied => io::ErrorKind::PermissionDenied,
470                         IOError::ConnectionRefused => io::ErrorKind::ConnectionRefused,
471                         IOError::ConnectionReset => io::ErrorKind::ConnectionReset,
472                         IOError::ConnectionAborted => io::ErrorKind::ConnectionAborted,
473                         IOError::NotConnected => io::ErrorKind::NotConnected,
474                         IOError::AddrInUse => io::ErrorKind::AddrInUse,
475                         IOError::AddrNotAvailable => io::ErrorKind::AddrNotAvailable,
476                         IOError::BrokenPipe => io::ErrorKind::BrokenPipe,
477                         IOError::AlreadyExists => io::ErrorKind::AlreadyExists,
478                         IOError::WouldBlock => io::ErrorKind::WouldBlock,
479                         IOError::InvalidInput => io::ErrorKind::InvalidInput,
480                         IOError::InvalidData => io::ErrorKind::InvalidData,
481                         IOError::TimedOut => io::ErrorKind::TimedOut,
482                         IOError::WriteZero => io::ErrorKind::WriteZero,
483                         IOError::Interrupted => io::ErrorKind::Interrupted,
484                         IOError::Other => io::ErrorKind::Other,
485                         IOError::UnexpectedEof => io::ErrorKind::UnexpectedEof,
486                 }
487         }
488         pub(crate) fn to_rust(&self) -> io::Error {
489                 io::Error::new(self.to_rust_kind(), "")
490         }
491 }
492
493 #[repr(C)]
494 /// A serialized transaction, in (pointer, length) form.
495 ///
496 /// This type optionally owns its own memory, and thus the semantics around access change based on
497 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
498 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
499 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
500 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
501 /// you would be invalid.
502 ///
503 /// Note that, while it may change in the future, because transactions on the Rust side are stored
504 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
505 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
506 /// `data_is_owned` either set or unset at your discretion.
507 pub struct Transaction {
508         /// The serialized transaction data.
509         ///
510         /// This is non-const for your convenience, an object passed to Rust is never written to.
511         pub data: *mut u8,
512         /// The length of the serialized transaction
513         pub datalen: usize,
514         /// Whether the data pointed to by `data` should be freed or not.
515         pub data_is_owned: bool,
516 }
517 impl Transaction {
518         fn from_vec(vec: Vec<u8>) -> Self {
519                 let datalen = vec.len();
520                 let data = Box::into_raw(vec.into_boxed_slice());
521                 Self {
522                         data: unsafe { (*data).as_mut_ptr() },
523                         datalen,
524                         data_is_owned: true,
525                 }
526         }
527         pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
528                 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
529                 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
530         }
531         pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
532                 let vec = ::bitcoin::consensus::encode::serialize(btc);
533                 Self::from_vec(vec)
534         }
535 }
536 impl Drop for Transaction {
537         fn drop(&mut self) {
538                 if self.data_is_owned && self.datalen != 0 {
539                         let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
540                 }
541         }
542 }
543 impl Clone for Transaction {
544         fn clone(&self) -> Self {
545                 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
546                 let mut v = Vec::new();
547                 v.extend_from_slice(&sl);
548                 Self::from_vec(v)
549         }
550 }
551 #[no_mangle]
552 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
553 pub extern "C" fn Transaction_free(_res: Transaction) { }
554
555 #[repr(C)]
556 /// A serialized witness.
557 pub struct Witness {
558         /// The serialized transaction data.
559         ///
560         /// This is non-const for your convenience, an object passed to Rust is never written to.
561         pub data: *mut u8,
562         /// The length of the serialized transaction
563         pub datalen: usize,
564         /// Whether the data pointed to by `data` should be freed or not.
565         pub data_is_owned: bool,
566 }
567 impl Witness {
568         fn from_vec(vec: Vec<u8>) -> Self {
569                 let datalen = vec.len();
570                 let data = Box::into_raw(vec.into_boxed_slice());
571                 Self {
572                         data: unsafe { (*data).as_mut_ptr() },
573                         datalen,
574                         data_is_owned: true,
575                 }
576         }
577         pub(crate) fn into_bitcoin(&self) -> BitcoinWitness {
578                 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
579         }
580         pub(crate) fn from_bitcoin(btc: &BitcoinWitness) -> Self {
581                 let vec = ::bitcoin::consensus::encode::serialize(btc);
582                 Self::from_vec(vec)
583         }
584 }
585
586 impl Drop for Witness {
587         fn drop(&mut self) {
588                 if self.data_is_owned && self.datalen != 0 {
589                         let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
590                 }
591         }
592 }
593 impl Clone for Witness {
594         fn clone(&self) -> Self {
595                 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
596                 let mut v = Vec::new();
597                 v.extend_from_slice(&sl);
598                 Self::from_vec(v)
599         }
600 }
601
602 #[no_mangle]
603 /// Creates a new Witness which has the same data as `orig` but with a new buffer.
604 pub extern "C" fn Witness_clone(orig: &Witness) -> Witness { orig.clone() }
605
606 #[no_mangle]
607 /// Frees the data pointed to by data
608 pub extern "C" fn Witness_free(_res: Witness) { }
609
610 pub(crate) fn bitcoin_to_C_outpoint(outpoint: &::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
611         crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: *outpoint.txid.as_ref() }, outpoint.vout.try_into().unwrap())
612 }
613 pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
614         unsafe {
615                 ::bitcoin::blockdata::transaction::OutPoint {
616                         txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
617                 }
618         }
619 }
620
621 #[repr(C)]
622 #[derive(Clone)]
623 /// An input to a transaction.
624 ///
625 /// This contains the witness, the scriptSig and the previous outpoint and represents a single
626 /// input to a transaction
627 pub struct TxIn {
628         /// The witness which includes any signatures required to spend a segwit output.
629         pub witness: Witness,
630         /// The script_sig which includes signatures requires to spend a pre-segwit output (or a
631         /// P2SH-wrapped segwit output).
632         pub script_sig: derived::CVec_u8Z,
633         /// The sequence number of the transaction input
634         pub sequence: u32,
635         /// The txid of the transaction being spent.
636         pub previous_txid: ThirtyTwoBytes,
637         /// The output index of the transaction being spent.
638         pub previous_vout: u32,
639 }
640
641 impl TxIn {
642         pub(crate) fn from_rust(txin: &::bitcoin::blockdata::transaction::TxIn) -> Self {
643                 TxIn {
644                         witness: Witness::from_bitcoin(&txin.witness),
645                         script_sig: derived::CVec_u8Z::from(txin.script_sig.clone().into_bytes()),
646                         sequence: txin.sequence.0,
647                         previous_txid: ThirtyTwoBytes { data: *txin.previous_output.txid.as_ref() },
648                         previous_vout: txin.previous_output.vout,
649                 }
650         }
651 }
652 #[no_mangle]
653 /// Convenience function for constructing a new TxIn
654 pub extern "C" fn TxIn_new(witness: Witness, script_sig: derived::CVec_u8Z, sequence: u32, previous_txid: ThirtyTwoBytes, previous_vout: u32) -> TxIn {
655         TxIn { witness, script_sig, sequence, previous_txid, previous_vout }
656 }
657 #[no_mangle]
658 /// Gets the `witness` in the given `TxIn`.
659 pub extern "C" fn TxIn_get_witness(txin: &TxIn) -> Witness {
660         txin.witness.clone()
661 }
662 #[no_mangle]
663 /// Gets the `script_sig` in the given `TxIn`.
664 pub extern "C" fn TxIn_get_script_sig(txin: &TxIn) -> u8slice {
665         u8slice::from_vec(&txin.script_sig)
666 }
667 #[no_mangle]
668 /// Gets the `sequence` in the given `TxIn`.
669 pub extern "C" fn TxIn_get_sequence(txin: &TxIn) -> u32 {
670         txin.sequence
671 }
672 #[no_mangle]
673 /// Gets the previous outpoint txid in the given `TxIn`.
674 pub extern "C" fn TxIn_get_previous_txid(txin: &TxIn) -> ThirtyTwoBytes {
675         txin.previous_txid
676 }
677 #[no_mangle]
678 /// Gets the previout outpoint index in the given `TxIn`.
679 pub extern "C" fn TxIn_get_previous_vout(txin: &TxIn) -> u32 {
680         txin.previous_vout
681 }
682 #[no_mangle]
683 /// Frees the witness and script_sig in a TxIn
684 pub extern "C" fn TxIn_free(_res: TxIn) { }
685
686 #[repr(C)]
687 #[derive(Clone)]
688 /// A transaction output including a scriptPubKey and value.
689 /// This type *does* own its own memory, so must be free'd appropriately.
690 pub struct TxOut {
691         /// The script_pubkey in this output
692         pub script_pubkey: derived::CVec_u8Z,
693         /// The value, in satoshis, of this output
694         pub value: u64,
695 }
696
697 impl TxOut {
698         pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
699                 ::bitcoin::blockdata::transaction::TxOut {
700                         script_pubkey: self.script_pubkey.into_rust().into(),
701                         value: self.value,
702                 }
703         }
704         pub(crate) fn from_rust(txout: &::bitcoin::blockdata::transaction::TxOut) -> Self {
705                 Self {
706                         script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.clone().into_bytes()),
707                         value: txout.value
708                 }
709         }
710 }
711
712 #[no_mangle]
713 /// Convenience function for constructing a new TxOut
714 pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
715         TxOut { script_pubkey, value }
716 }
717 #[no_mangle]
718 /// Gets the `script_pubkey` in the given `TxOut`.
719 pub extern "C" fn TxOut_get_script_pubkey(txout: &TxOut) -> u8slice {
720         u8slice::from_vec(&txout.script_pubkey)
721 }
722 #[no_mangle]
723 /// Gets the value in the given `TxOut`.
724 pub extern "C" fn TxOut_get_value(txout: &TxOut) -> u64 {
725         txout.value
726 }
727 #[no_mangle]
728 /// Frees the data pointed to by script_pubkey.
729 pub extern "C" fn TxOut_free(_res: TxOut) { }
730 #[no_mangle]
731 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
732 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
733
734 #[repr(C)]
735 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
736 /// own the memory pointed to by data.
737 pub struct u8slice {
738         /// A pointer to the byte buffer
739         pub data: *const u8,
740         /// The number of bytes pointed to by `data`.
741         pub datalen: usize
742 }
743 impl u8slice {
744         pub(crate) fn from_slice(s: &[u8]) -> Self {
745                 Self {
746                         data: s.as_ptr(),
747                         datalen: s.len(),
748                 }
749         }
750         pub(crate) fn to_slice(&self) -> &[u8] {
751                 if self.datalen == 0 { return &[]; }
752                 unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
753         }
754         pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
755                 let sl = self.to_slice();
756                 Cursor::new(sl)
757         }
758         pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
759                 Self::from_slice(v.as_slice())
760         }
761 }
762 pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
763         let mut res = Vec::new();
764         r.read_to_end(&mut res).unwrap();
765         derived::CVec_u8Z::from(res)
766 }
767
768 #[repr(C)]
769 #[derive(Copy, Clone)]
770 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
771 /// look up the corresponding function in rust-lightning's docs.
772 pub struct ThirtyTwoBytes {
773         /// The thirty-two bytes
774         pub data: [u8; 32],
775 }
776
777 #[repr(C)]
778 /// A 3-byte byte array.
779 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
780 #[derive(Clone)]
781 #[repr(C)]
782 /// A 4-byte byte array.
783 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
784 #[derive(Clone)]
785 #[repr(C)]
786 /// A 12-byte byte array.
787 pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
788 #[derive(Clone)]
789 #[repr(C)]
790 /// A 16-byte byte array.
791 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
792 #[derive(Clone)]
793 #[repr(C)]
794 /// A 20-byte byte array.
795 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
796
797 #[derive(Clone)]
798 #[repr(C)]
799 /// 32 u16s
800 pub struct ThirtyTwoU16s { /** The thirty-two 16-bit integers */ pub data: [u16; 32], }
801
802 pub(crate) struct VecWriter(pub Vec<u8>);
803 impl lightning::util::ser::Writer for VecWriter {
804         fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
805                 self.0.extend_from_slice(buf);
806                 Ok(())
807         }
808 }
809 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
810         let mut out = VecWriter(Vec::new());
811         i.write(&mut out).unwrap();
812         derived::CVec_u8Z::from(out.0)
813 }
814 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
815         I::read(&mut s.to_slice())
816 }
817 pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
818         I::read(&mut s.to_slice())
819 }
820 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
821         I::read(&mut s.to_slice(), args)
822 }
823
824 #[repr(C)]
825 /// A Rust str object, ie a reference to a UTF8-valid string.
826 /// This is *not* null-terminated so cannot be used directly as a C string!
827 pub struct Str {
828         /// A pointer to the string's bytes, in UTF8 encoding
829         pub chars: *const u8,
830         /// The number of bytes (not characters!) pointed to by `chars`
831         pub len: usize,
832         /// Whether the data pointed to by `chars` should be freed or not.
833         pub chars_is_owned: bool,
834 }
835 impl Into<Str> for &str {
836         fn into(self) -> Str {
837                 self.to_owned().into()
838         }
839 }
840 impl Into<Str> for &mut &str {
841         fn into(self) -> Str {
842                 let us: &str = *self;
843                 us.into()
844         }
845 }
846
847 impl Str {
848         pub(crate) fn into_str(&self) -> &'static str {
849                 if self.len == 0 { return ""; }
850                 core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
851         }
852         pub(crate) fn into_string(mut self) -> String {
853                 let bytes = if self.len == 0 {
854                         Vec::new()
855                 } else if self.chars_is_owned {
856                         let ret = unsafe {
857                                 Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
858                         }.into();
859                         self.chars_is_owned = false;
860                         ret
861                 } else {
862                         let mut ret = Vec::with_capacity(self.len);
863                         ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
864                         ret
865                 };
866                 String::from_utf8(bytes).unwrap()
867         }
868         #[cfg(feature = "std")]
869         pub(crate) fn into_pathbuf(mut self) -> std::path::PathBuf {
870                 std::path::PathBuf::from(self.into_string())
871         }
872 }
873 impl Into<Str> for String {
874         fn into(self) -> Str {
875                 let s = Box::leak(self.into_boxed_str());
876                 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
877         }
878 }
879 #[cfg(feature = "std")]
880 impl Into<Str> for std::path::PathBuf {
881         fn into(self) -> Str {
882                 self.into_os_string().into_string().expect("We expect paths to be UTF-8 valid").into()
883         }
884 }
885 impl Clone for Str {
886         fn clone(&self) -> Self {
887                 String::from(self.into_str()).into()
888         }
889 }
890
891 impl Drop for Str {
892         fn drop(&mut self) {
893                 if self.chars_is_owned && self.len != 0 {
894                         let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
895                 }
896         }
897 }
898 #[no_mangle]
899 /// Frees the data buffer, if chars_is_owned is set and len > 0.
900 pub extern "C" fn Str_free(_res: Str) { }
901
902 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
903 // Thus, they must gracefully handle being completely null in _free.
904
905 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
906 // everywhere in the containers.
907
908 #[repr(C)]
909 pub(crate) union CResultPtr<O, E> {
910         pub(crate) result: *mut O,
911         pub(crate) err: *mut E,
912 }
913 #[repr(C)]
914 pub(crate) struct CResultTempl<O, E> {
915         pub(crate) contents: CResultPtr<O, E>,
916         pub(crate) result_ok: bool,
917 }
918 impl<O, E> CResultTempl<O, E> {
919         pub(crate) extern "C" fn ok(o: O) -> Self {
920                 CResultTempl {
921                         contents: CResultPtr {
922                                 result: Box::into_raw(Box::new(o)),
923                         },
924                         result_ok: true,
925                 }
926         }
927         pub(crate) extern "C" fn err(e: E) -> Self {
928                 CResultTempl {
929                         contents: CResultPtr {
930                                 err: Box::into_raw(Box::new(e)),
931                         },
932                         result_ok: false,
933                 }
934         }
935 }
936 impl<O, E> Drop for CResultTempl<O, E> {
937         fn drop(&mut self) {
938                 if self.result_ok {
939                         if unsafe { !self.contents.result.is_null() } {
940                                 let _ = unsafe { Box::from_raw(self.contents.result) };
941                         }
942                 } else if unsafe { !self.contents.err.is_null() } {
943                         let _ = unsafe { Box::from_raw(self.contents.err) };
944                 }
945         }
946 }
947
948 /// Utility to make it easy to set a pointer to null and get its original value in line.
949 pub(crate) trait TakePointer<T> {
950         fn take_ptr(&mut self) -> T;
951 }
952 impl<T> TakePointer<*const T> for *const T {
953         fn take_ptr(&mut self) -> *const T {
954                 let ret = *self;
955                 *self = core::ptr::null();
956                 ret
957         }
958 }
959 impl<T> TakePointer<*mut T> for *mut T {
960         fn take_ptr(&mut self) -> *mut T {
961                 let ret = *self;
962                 *self = core::ptr::null_mut();
963                 ret
964         }
965 }
966
967
968 pub(crate) mod ObjOps {
969         #[cfg(feature = "no-std")]
970         use alloc::boxed::Box;
971
972         #[inline]
973         #[must_use = "returns new dangling pointer"]
974         pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
975                 let ptr = Box::into_raw(Box::new(obj));
976                 nonnull_ptr_to_inner(ptr)
977         }
978         #[inline]
979         pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
980                 if core::mem::size_of::<T>() == 0 {
981                         // We map `None::<T>` as `T { inner: null, .. }` which works great for all
982                         // non-Zero-Sized-Types `T`.
983                         // For ZSTs, we need to differentiate between null implying `None` and null implying
984                         // `Some` with no allocation.
985                         // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
986                         // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
987                         // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
988                         // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
989                         // fine.
990                         // Note that we add 4095 here as at least the Java client assumes that the low bit on
991                         // any heap pointer is 0, which is generally provided by malloc, but which is not true
992                         // for ZSTs "allocated" by `Box::new`.
993                         debug_assert_eq!(ptr as usize, 1);
994                         unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
995                 } else {
996                         // In order to get better test coverage, also increment non-ZST pointers with
997                         // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
998                         #[cfg(test_mod_pointers)]
999                         unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
1000                         #[cfg(not(test_mod_pointers))]
1001                         unsafe { ptr as *mut T }
1002                 }
1003         }
1004         #[inline]
1005         /// Invert nonnull_ptr_to_inner
1006         pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
1007                 if core::mem::size_of::<T>() == 0 {
1008                         unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
1009                 } else {
1010                         #[cfg(test_mod_pointers)]
1011                         unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
1012                         #[cfg(not(test_mod_pointers))]
1013                         ptr
1014                 }
1015         }
1016 }
1017
1018 #[cfg(test_mod_pointers)]
1019 #[no_mangle]
1020 /// This function exists for memory safety testing purposes. It should never be used in production
1021 /// code
1022 pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
1023         if ptr as usize == 1 {
1024                 core::ptr::null()
1025         } else {
1026                 unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
1027         }
1028 }
1029
1030 pub(crate) struct SmartPtr<T> {
1031         ptr: *mut T,
1032 }
1033 impl<T> SmartPtr<T> {
1034         pub(crate) fn from_obj(o: T) -> Self {
1035                 Self { ptr: Box::into_raw(Box::new(o)) }
1036         }
1037         pub(crate) fn null() -> Self {
1038                 Self { ptr: core::ptr::null_mut() }
1039         }
1040 }
1041 impl<T> Drop for SmartPtr<T> {
1042         fn drop(&mut self) {
1043                 if self.ptr != core::ptr::null_mut() {
1044                         let _ = unsafe { Box::from_raw(self.ptr) };
1045                 }
1046         }
1047 }
1048 impl<T> core::ops::Deref for SmartPtr<T> {
1049         type Target = *mut T;
1050         fn deref(&self) -> &*mut T {
1051                 &self.ptr
1052         }
1053 }