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