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