1 //! This module contains standard C-mapped types for types not in the original crate.
3 /// Auto-generated C-mapped types for templated containers
6 use bitcoin::Transaction as BitcoinTransaction;
7 use bitcoin::Witness as BitcoinWitness;
8 use bitcoin::hashes::Hash;
9 use bitcoin::secp256k1::PublicKey as SecpPublicKey;
10 use bitcoin::secp256k1::SecretKey as SecpSecretKey;
11 use bitcoin::secp256k1::ecdsa::Signature as SecpSignature;
12 use bitcoin::secp256k1::Error as SecpError;
13 use bitcoin::secp256k1::ecdsa::RecoveryId;
14 use bitcoin::secp256k1::ecdsa::RecoverableSignature as SecpRecoverableSignature;
15 use bitcoin::secp256k1::Scalar as SecpScalar;
17 use bitcoin::util::address;
19 use core::convert::TryInto; // Bindings need at least rustc 1.34
20 use core::ffi::c_void;
22 #[cfg(feature = "std")]
23 pub(crate) use std::io::{self, Cursor, Read};
24 #[cfg(feature = "no-std")]
25 pub(crate) use core2::io::{self, Cursor, Read};
26 #[cfg(feature = "no-std")]
27 use alloc::{boxed::Box, vec::Vec, string::String};
29 use core::convert::TryFrom;
32 /// A dummy struct of which an instance must never exist.
33 /// This corresponds to the Rust type `Infallible`, or, in unstable rust, `!`
34 pub struct NotConstructable {
35 _priv_thing: core::convert::Infallible,
37 impl From<core::convert::Infallible> for NotConstructable {
38 fn from(_: core::convert::Infallible) -> Self { unreachable!(); }
41 /// Integer in the range `0..32`
42 #[derive(PartialEq, Eq, Copy, Clone)]
43 #[allow(non_camel_case_types)]
47 impl From<bech32::u5> for U5 {
48 fn from(o: bech32::u5) -> Self { Self(o.to_u8()) }
50 impl Into<bech32::u5> for U5 {
51 fn into(self) -> bech32::u5 { bech32::u5::try_from_u8(self.0).expect("u5 objects must be in the range 0..32") }
54 /// Unsigned, 128-bit integer.
56 /// Because LLVM implements an incorrect ABI for 128-bit integers, a wrapper type is defined here.
57 /// See https://github.com/rust-lang/rust/issues/54341 for more details.
58 #[derive(PartialEq, Eq, Copy, Clone)]
59 #[allow(non_camel_case_types)]
62 /// The 128-bit integer, as 16 little-endian bytes
63 pub le_bytes: [u8; 16],
67 /// Gets the 128-bit integer, as 16 little-endian bytes
68 pub extern "C" fn U128_le_bytes(val: U128) -> SixteenBytes { SixteenBytes { data: val.le_bytes } }
70 /// Constructs a new U128 from 16 little-endian bytes
71 pub extern "C" fn U128_new(le_bytes: SixteenBytes) -> U128 { U128 { le_bytes: le_bytes.data } }
73 impl From<u128> for U128 {
74 fn from(o: u128) -> Self { Self { le_bytes: o.to_le_bytes() } }
76 impl From<&mut u128> for U128 {
77 fn from(o: &mut u128) -> U128 { Self::from(*o) }
79 impl Into<u128> for U128 {
80 fn into(self) -> u128 { u128::from_le_bytes(self.le_bytes) }
83 /// Integer in the range `0..=16`
84 #[derive(PartialEq, Eq, Copy, Clone)]
86 pub struct WitnessVersion(u8);
88 impl From<address::WitnessVersion> for WitnessVersion {
89 fn from(o: address::WitnessVersion) -> Self { Self(o.to_num()) }
91 impl Into<address::WitnessVersion> for WitnessVersion {
92 fn into(self) -> address::WitnessVersion {
93 address::WitnessVersion::try_from(self.0).expect("WitnessVersion objects must be in the range 0..=16")
99 /// Represents a valid secp256k1 public key serialized in "compressed form" as a 33 byte array.
100 pub struct PublicKey {
101 /// The bytes of the public key
102 pub compressed_form: [u8; 33],
105 pub(crate) fn from_rust(pk: &SecpPublicKey) -> Self {
107 compressed_form: pk.serialize(),
110 pub(crate) fn into_rust(&self) -> SecpPublicKey {
111 SecpPublicKey::from_slice(&self.compressed_form).unwrap()
113 pub(crate) fn is_null(&self) -> bool { self.compressed_form[..] == [0; 33][..] }
114 pub(crate) fn null() -> Self { Self { compressed_form: [0; 33] } }
119 /// Represents a valid secp256k1 secret key serialized as a 32 byte array.
120 pub struct SecretKey {
121 /// The bytes of the secret key
125 // from_rust isn't implemented for a ref since we just return byte array refs directly
126 pub(crate) fn from_rust(sk: SecpSecretKey) -> Self {
127 let mut bytes = [0; 32];
128 bytes.copy_from_slice(&sk[..]);
131 pub(crate) fn into_rust(&self) -> SecpSecretKey {
132 SecpSecretKey::from_slice(&self.bytes).unwrap()
138 /// Represents a secp256k1 signature serialized as two 32-byte numbers
139 pub struct Signature {
140 /// The bytes of the signature in "compact" form
141 pub compact_form: [u8; 64],
144 pub(crate) fn from_rust(pk: &SecpSignature) -> Self {
146 compact_form: pk.serialize_compact(),
149 pub(crate) fn into_rust(&self) -> SecpSignature {
150 SecpSignature::from_compact(&self.compact_form).unwrap()
152 // The following are used for Option<Signature> which we support, but don't use anymore
153 #[allow(unused)] pub(crate) fn is_null(&self) -> bool { self.compact_form[..] == [0; 64][..] }
154 #[allow(unused)] pub(crate) fn null() -> Self { Self { compact_form: [0; 64] } }
159 /// Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which
160 /// allows recovering the exact public key which created the signature given the message.
161 pub struct RecoverableSignature {
162 /// The bytes of the signature in "compact" form plus a "Recovery ID" which allows for
164 pub serialized_form: [u8; 68],
166 impl RecoverableSignature {
167 pub(crate) fn from_rust(pk: &SecpRecoverableSignature) -> Self {
168 let (id, compact_form) = pk.serialize_compact();
169 let mut serialized_form = [0; 68];
170 serialized_form[0..64].copy_from_slice(&compact_form[..]);
171 serialized_form[64..].copy_from_slice(&id.to_i32().to_le_bytes());
172 Self { serialized_form }
174 pub(crate) fn into_rust(&self) -> SecpRecoverableSignature {
176 id.copy_from_slice(&self.serialized_form[64..]);
177 SecpRecoverableSignature::from_compact(&self.serialized_form[0..64],
178 RecoveryId::from_i32(i32::from_le_bytes(id)).expect("Invalid Recovery ID"))
185 /// Represents a scalar value between zero and the secp256k1 curve order, in big endian.
186 pub struct BigEndianScalar {
187 /// The bytes of the scalar value.
188 pub big_endian_bytes: [u8; 32],
190 impl BigEndianScalar {
191 pub(crate) fn from_rust(scalar: &SecpScalar) -> Self {
192 Self { big_endian_bytes: scalar.to_be_bytes() }
194 pub(crate) fn into_rust(&self) -> SecpScalar {
195 SecpScalar::from_be_bytes(self.big_endian_bytes).expect("Scalar greater than the curve order")
200 /// Convenience function for constructing a new BigEndianScalar
201 pub extern "C" fn BigEndianScalar_new(big_endian_bytes: ThirtyTwoBytes) -> BigEndianScalar {
202 BigEndianScalar { big_endian_bytes: big_endian_bytes.data }
206 #[derive(Copy, Clone)]
207 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
208 pub enum Secp256k1Error {
209 /// Signature failed verification
211 /// Badly sized message ("messages" are actually fixed-sized digests; see the MESSAGE_SIZE constant)
219 /// Bad shared secret.
223 /// Invalid tweak for add_assign or mul_assign
225 /// Didn't pass enough memory to context creation with preallocated memory
227 /// Bad set of public keys.
229 /// The only valid parity values are 0 or 1.
232 impl Secp256k1Error {
233 pub(crate) fn from_rust(err: SecpError) -> Self {
235 SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
236 SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
237 SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
238 SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
239 SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
240 SecpError::InvalidSharedSecret => Secp256k1Error::InvalidSharedSecret,
241 SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
242 SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
243 SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
244 SecpError::InvalidPublicKeySum => Secp256k1Error::InvalidPublicKeySum,
245 SecpError::InvalidParityValue(_) => Secp256k1Error::InvalidParityValue,
248 pub(crate) fn into_rust(self) -> SecpError {
249 let invalid_parity = secp256k1::Parity::from_i32(42).unwrap_err();
251 Secp256k1Error::IncorrectSignature => SecpError::IncorrectSignature,
252 Secp256k1Error::InvalidMessage => SecpError::InvalidMessage,
253 Secp256k1Error::InvalidPublicKey => SecpError::InvalidPublicKey,
254 Secp256k1Error::InvalidSignature => SecpError::InvalidSignature,
255 Secp256k1Error::InvalidSecretKey => SecpError::InvalidSecretKey,
256 Secp256k1Error::InvalidSharedSecret => SecpError::InvalidSharedSecret,
257 Secp256k1Error::InvalidRecoveryId => SecpError::InvalidRecoveryId,
258 Secp256k1Error::InvalidTweak => SecpError::InvalidTweak,
259 Secp256k1Error::NotEnoughMemory => SecpError::NotEnoughMemory,
260 Secp256k1Error::InvalidPublicKeySum => SecpError::InvalidPublicKeySum,
261 Secp256k1Error::InvalidParityValue => SecpError::InvalidParityValue(invalid_parity),
267 #[derive(Copy, Clone)]
268 /// Represents an error returned from the bech32 library during validation of some bech32 data
269 pub enum Bech32Error {
270 /// String does not contain the separator character
272 /// The checksum does not match the rest of the data
274 /// The data or human-readable part is too long or too short
276 /// Some part of the string contains an invalid character
278 /// Some part of the data has an invalid value
280 /// The bit conversion failed due to a padding issue
282 /// The whole string must be of one case
286 pub(crate) fn from_rust(err: bech32::Error) -> Self {
288 bech32::Error::MissingSeparator => Self::MissingSeparator,
289 bech32::Error::InvalidChecksum => Self::InvalidChecksum,
290 bech32::Error::InvalidLength => Self::InvalidLength,
291 bech32::Error::InvalidChar(c) => Self::InvalidChar(c as u32),
292 bech32::Error::InvalidData(d) => Self::InvalidData(d),
293 bech32::Error::InvalidPadding => Self::InvalidPadding,
294 bech32::Error::MixedCase => Self::MixedCase,
297 pub(crate) fn into_rust(self) -> bech32::Error {
299 Self::MissingSeparator => bech32::Error::MissingSeparator,
300 Self::InvalidChecksum => bech32::Error::InvalidChecksum,
301 Self::InvalidLength => bech32::Error::InvalidLength,
302 Self::InvalidChar(c) => bech32::Error::InvalidChar(core::char::from_u32(c).expect("Invalid UTF-8 character in Bech32Error::InvalidChar")),
303 Self::InvalidData(d) => bech32::Error::InvalidData(d),
304 Self::InvalidPadding => bech32::Error::InvalidPadding,
305 Self::MixedCase => bech32::Error::MixedCase,
310 /// Creates a new Bech32Error which has the same data as `orig`
311 pub extern "C" fn Bech32Error_clone(orig: &Bech32Error) -> Bech32Error { orig.clone() }
313 /// Releases any memory held by the given `Bech32Error` (which is currently none)
314 pub extern "C" fn Bech32Error_free(o: Bech32Error) { }
317 #[derive(Clone, Copy, PartialEq)]
318 /// Sub-errors which don't have specific information in them use this type.
320 /// Zero-Sized_types aren't consistent across Rust/C/C++, so we add some size here
325 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
326 #[derive(Clone, Copy, PartialEq)]
327 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
349 pub(crate) fn from_rust_kind(err: io::ErrorKind) -> Self {
351 io::ErrorKind::NotFound => IOError::NotFound,
352 io::ErrorKind::PermissionDenied => IOError::PermissionDenied,
353 io::ErrorKind::ConnectionRefused => IOError::ConnectionRefused,
354 io::ErrorKind::ConnectionReset => IOError::ConnectionReset,
355 io::ErrorKind::ConnectionAborted => IOError::ConnectionAborted,
356 io::ErrorKind::NotConnected => IOError::NotConnected,
357 io::ErrorKind::AddrInUse => IOError::AddrInUse,
358 io::ErrorKind::AddrNotAvailable => IOError::AddrNotAvailable,
359 io::ErrorKind::BrokenPipe => IOError::BrokenPipe,
360 io::ErrorKind::AlreadyExists => IOError::AlreadyExists,
361 io::ErrorKind::WouldBlock => IOError::WouldBlock,
362 io::ErrorKind::InvalidInput => IOError::InvalidInput,
363 io::ErrorKind::InvalidData => IOError::InvalidData,
364 io::ErrorKind::TimedOut => IOError::TimedOut,
365 io::ErrorKind::WriteZero => IOError::WriteZero,
366 io::ErrorKind::Interrupted => IOError::Interrupted,
367 io::ErrorKind::Other => IOError::Other,
368 io::ErrorKind::UnexpectedEof => IOError::UnexpectedEof,
372 pub(crate) fn from_rust(err: io::Error) -> Self {
373 Self::from_rust_kind(err.kind())
375 pub(crate) fn to_rust_kind(&self) -> io::ErrorKind {
377 IOError::NotFound => io::ErrorKind::NotFound,
378 IOError::PermissionDenied => io::ErrorKind::PermissionDenied,
379 IOError::ConnectionRefused => io::ErrorKind::ConnectionRefused,
380 IOError::ConnectionReset => io::ErrorKind::ConnectionReset,
381 IOError::ConnectionAborted => io::ErrorKind::ConnectionAborted,
382 IOError::NotConnected => io::ErrorKind::NotConnected,
383 IOError::AddrInUse => io::ErrorKind::AddrInUse,
384 IOError::AddrNotAvailable => io::ErrorKind::AddrNotAvailable,
385 IOError::BrokenPipe => io::ErrorKind::BrokenPipe,
386 IOError::AlreadyExists => io::ErrorKind::AlreadyExists,
387 IOError::WouldBlock => io::ErrorKind::WouldBlock,
388 IOError::InvalidInput => io::ErrorKind::InvalidInput,
389 IOError::InvalidData => io::ErrorKind::InvalidData,
390 IOError::TimedOut => io::ErrorKind::TimedOut,
391 IOError::WriteZero => io::ErrorKind::WriteZero,
392 IOError::Interrupted => io::ErrorKind::Interrupted,
393 IOError::Other => io::ErrorKind::Other,
394 IOError::UnexpectedEof => io::ErrorKind::UnexpectedEof,
397 pub(crate) fn to_rust(&self) -> io::Error {
398 io::Error::new(self.to_rust_kind(), "")
403 /// A serialized transaction, in (pointer, length) form.
405 /// This type optionally owns its own memory, and thus the semantics around access change based on
406 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
407 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
408 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
409 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
410 /// you would be invalid.
412 /// Note that, while it may change in the future, because transactions on the Rust side are stored
413 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
414 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
415 /// `data_is_owned` either set or unset at your discretion.
416 pub struct Transaction {
417 /// The serialized transaction data.
419 /// This is non-const for your convenience, an object passed to Rust is never written to.
421 /// The length of the serialized transaction
423 /// Whether the data pointed to by `data` should be freed or not.
424 pub data_is_owned: bool,
427 fn from_vec(vec: Vec<u8>) -> Self {
428 let datalen = vec.len();
429 let data = Box::into_raw(vec.into_boxed_slice());
431 data: unsafe { (*data).as_mut_ptr() },
436 pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
437 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
438 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
440 pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
441 let vec = ::bitcoin::consensus::encode::serialize(btc);
445 impl Drop for Transaction {
447 if self.data_is_owned && self.datalen != 0 {
448 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
452 impl Clone for Transaction {
453 fn clone(&self) -> Self {
454 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
455 let mut v = Vec::new();
456 v.extend_from_slice(&sl);
461 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
462 pub extern "C" fn Transaction_free(_res: Transaction) { }
465 /// A serialized witness.
467 /// The serialized transaction data.
469 /// This is non-const for your convenience, an object passed to Rust is never written to.
471 /// The length of the serialized transaction
473 /// Whether the data pointed to by `data` should be freed or not.
474 pub data_is_owned: bool,
477 fn from_vec(vec: Vec<u8>) -> Self {
478 let datalen = vec.len();
479 let data = Box::into_raw(vec.into_boxed_slice());
481 data: unsafe { (*data).as_mut_ptr() },
486 pub(crate) fn into_bitcoin(&self) -> BitcoinWitness {
487 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
489 pub(crate) fn from_bitcoin(btc: &BitcoinWitness) -> Self {
490 let vec = ::bitcoin::consensus::encode::serialize(btc);
495 impl Drop for Witness {
497 if self.data_is_owned && self.datalen != 0 {
498 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
502 impl Clone for Witness {
503 fn clone(&self) -> Self {
504 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
505 let mut v = Vec::new();
506 v.extend_from_slice(&sl);
512 /// Creates a new Witness which has the same data as `orig` but with a new buffer.
513 pub extern "C" fn Witness_clone(orig: &Witness) -> Witness { orig.clone() }
516 /// Frees the data pointed to by data
517 pub extern "C" fn Witness_free(_res: Witness) { }
519 pub(crate) fn bitcoin_to_C_outpoint(outpoint: &::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
520 crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: outpoint.txid.into_inner() }, outpoint.vout.try_into().unwrap())
522 pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
524 ::bitcoin::blockdata::transaction::OutPoint {
525 txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
532 /// An input to a transaction.
534 /// This contains the witness, the scriptSig and the previous outpoint and represents a single
535 /// input to a transaction
537 /// The witness which includes any signatures required to spend a segwit output.
538 pub witness: Witness,
539 /// The script_sig which includes signatures requires to spend a pre-segwit output (or a
540 /// P2SH-wrapped segwit output).
541 pub script_sig: derived::CVec_u8Z,
542 /// The sequence number of the transaction input
544 /// The txid of the transaction being spent.
545 pub previous_txid: ThirtyTwoBytes,
546 /// The output index of the transaction being spent.
547 pub previous_vout: u32,
551 pub(crate) fn from_rust(txin: &::bitcoin::blockdata::transaction::TxIn) -> Self {
553 witness: Witness::from_bitcoin(&txin.witness),
554 script_sig: derived::CVec_u8Z::from(txin.script_sig.clone().into_bytes()),
555 sequence: txin.sequence.0,
556 previous_txid: ThirtyTwoBytes { data: txin.previous_output.txid.into_inner() },
557 previous_vout: txin.previous_output.vout,
563 /// Frees the witness and script_sig in a TxIn
564 pub extern "C" fn TxIn_free(_res: TxIn) { }
567 /// Convenience function for constructing a new TxIn
568 pub extern "C" fn TxIn_new(witness: Witness, script_sig: derived::CVec_u8Z, sequence: u32, previous_txid: ThirtyTwoBytes, previous_vout: u32) -> TxIn {
569 TxIn { witness, script_sig, sequence, previous_txid, previous_vout }
575 /// A transaction output including a scriptPubKey and value.
576 /// This type *does* own its own memory, so must be free'd appropriately.
578 /// The script_pubkey in this output
579 pub script_pubkey: derived::CVec_u8Z,
580 /// The value, in satoshis, of this output
585 pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
586 ::bitcoin::blockdata::transaction::TxOut {
587 script_pubkey: self.script_pubkey.into_rust().into(),
591 pub(crate) fn from_rust(txout: &::bitcoin::blockdata::transaction::TxOut) -> Self {
593 script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.clone().into_bytes()),
600 /// Convenience function for constructing a new TxOut
601 pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
602 TxOut { script_pubkey, value }
605 /// Frees the data pointed to by script_pubkey.
606 pub extern "C" fn TxOut_free(_res: TxOut) { }
608 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
609 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
612 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
613 /// own the memory pointed to by data.
615 /// A pointer to the byte buffer
617 /// The number of bytes pointed to by `data`.
621 pub(crate) fn from_slice(s: &[u8]) -> Self {
627 pub(crate) fn to_slice(&self) -> &[u8] {
628 if self.datalen == 0 { return &[]; }
629 unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
631 pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
632 let sl = self.to_slice();
635 pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
636 Self::from_slice(v.as_slice())
639 pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
640 let mut res = Vec::new();
641 r.read_to_end(&mut res).unwrap();
642 derived::CVec_u8Z::from(res)
646 #[derive(Copy, Clone)]
647 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
648 /// look up the corresponding function in rust-lightning's docs.
649 pub struct ThirtyTwoBytes {
650 /// The thirty-two bytes
655 /// A 3-byte byte array.
656 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
659 /// A 4-byte byte array.
660 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
663 /// A 12-byte byte array.
664 pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
667 /// A 16-byte byte array.
668 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
671 /// A 20-byte byte array.
672 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
677 pub struct EightU16s { /** The eight 16-bit integers */ pub data: [u16; 8], }
679 pub(crate) struct VecWriter(pub Vec<u8>);
680 impl lightning::util::ser::Writer for VecWriter {
681 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
682 self.0.extend_from_slice(buf);
686 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
687 let mut out = VecWriter(Vec::new());
688 i.write(&mut out).unwrap();
689 derived::CVec_u8Z::from(out.0)
691 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
692 I::read(&mut s.to_slice())
694 pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
695 I::read(&mut s.to_slice())
697 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
698 I::read(&mut s.to_slice(), args)
702 /// A Rust str object, ie a reference to a UTF8-valid string.
703 /// This is *not* null-terminated so cannot be used directly as a C string!
705 /// A pointer to the string's bytes, in UTF8 encoding
706 pub chars: *const u8,
707 /// The number of bytes (not characters!) pointed to by `chars`
709 /// Whether the data pointed to by `chars` should be freed or not.
710 pub chars_is_owned: bool,
712 impl Into<Str> for &'static str {
713 fn into(self) -> Str {
714 Str { chars: self.as_ptr(), len: self.len(), chars_is_owned: false }
717 impl Into<Str> for &mut &'static str {
718 fn into(self) -> Str {
719 let us: &'static str = *self;
725 pub(crate) fn into_str(&self) -> &'static str {
726 if self.len == 0 { return ""; }
727 core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
729 pub(crate) fn into_string(mut self) -> String {
730 let bytes = if self.len == 0 {
732 } else if self.chars_is_owned {
734 Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
736 self.chars_is_owned = false;
739 let mut ret = Vec::with_capacity(self.len);
740 ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
743 String::from_utf8(bytes).unwrap()
746 impl Into<Str> for String {
747 fn into(self) -> Str {
748 let s = Box::leak(self.into_boxed_str());
749 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
753 fn clone(&self) -> Self {
754 String::from(self.into_str()).into()
760 if self.chars_is_owned && self.len != 0 {
761 let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
766 /// Frees the data buffer, if chars_is_owned is set and len > 0.
767 pub extern "C" fn Str_free(_res: Str) { }
769 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
770 // Thus, they must gracefully handle being completely null in _free.
772 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
773 // everywhere in the containers.
776 pub(crate) union CResultPtr<O, E> {
777 pub(crate) result: *mut O,
778 pub(crate) err: *mut E,
781 pub(crate) struct CResultTempl<O, E> {
782 pub(crate) contents: CResultPtr<O, E>,
783 pub(crate) result_ok: bool,
785 impl<O, E> CResultTempl<O, E> {
786 pub(crate) extern "C" fn ok(o: O) -> Self {
788 contents: CResultPtr {
789 result: Box::into_raw(Box::new(o)),
794 pub(crate) extern "C" fn err(e: E) -> Self {
796 contents: CResultPtr {
797 err: Box::into_raw(Box::new(e)),
803 impl<O, E> Drop for CResultTempl<O, E> {
806 if unsafe { !self.contents.result.is_null() } {
807 let _ = unsafe { Box::from_raw(self.contents.result) };
809 } else if unsafe { !self.contents.err.is_null() } {
810 let _ = unsafe { Box::from_raw(self.contents.err) };
815 /// Utility to make it easy to set a pointer to null and get its original value in line.
816 pub(crate) trait TakePointer<T> {
817 fn take_ptr(&mut self) -> T;
819 impl<T> TakePointer<*const T> for *const T {
820 fn take_ptr(&mut self) -> *const T {
822 *self = core::ptr::null();
826 impl<T> TakePointer<*mut T> for *mut T {
827 fn take_ptr(&mut self) -> *mut T {
829 *self = core::ptr::null_mut();
835 pub(crate) mod ObjOps {
836 #[cfg(feature = "no-std")]
837 use alloc::boxed::Box;
840 #[must_use = "returns new dangling pointer"]
841 pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
842 let ptr = Box::into_raw(Box::new(obj));
843 nonnull_ptr_to_inner(ptr)
846 pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
847 if core::mem::size_of::<T>() == 0 {
848 // We map `None::<T>` as `T { inner: null, .. }` which works great for all
849 // non-Zero-Sized-Types `T`.
850 // For ZSTs, we need to differentiate between null implying `None` and null implying
851 // `Some` with no allocation.
852 // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
853 // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
854 // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
855 // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
857 // Note that we add 4095 here as at least the Java client assumes that the low bit on
858 // any heap pointer is 0, which is generally provided by malloc, but which is not true
859 // for ZSTs "allocated" by `Box::new`.
860 debug_assert_eq!(ptr as usize, 1);
861 unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
863 // In order to get better test coverage, also increment non-ZST pointers with
864 // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
865 #[cfg(test_mod_pointers)]
866 unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
867 #[cfg(not(test_mod_pointers))]
868 unsafe { ptr as *mut T }
872 /// Invert nonnull_ptr_to_inner
873 pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
874 if core::mem::size_of::<T>() == 0 {
875 unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
877 #[cfg(test_mod_pointers)]
878 unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
879 #[cfg(not(test_mod_pointers))]
885 #[cfg(test_mod_pointers)]
887 /// This function exists for memory safety testing purposes. It should never be used in production
889 pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
890 if ptr as usize == 1 {
893 unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
897 pub(crate) struct SmartPtr<T> {
900 impl<T> SmartPtr<T> {
901 pub(crate) fn from_obj(o: T) -> Self {
902 Self { ptr: Box::into_raw(Box::new(o)) }
904 pub(crate) fn null() -> Self {
905 Self { ptr: core::ptr::null_mut() }
908 impl<T> Drop for SmartPtr<T> {
910 if self.ptr != core::ptr::null_mut() {
911 let _ = unsafe { Box::from_raw(self.ptr) };
915 impl<T> core::ops::Deref for SmartPtr<T> {
916 type Target = *mut T;
917 fn deref(&self) -> &*mut T {