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 ECDSASecpSignature;
12 use bitcoin::secp256k1::schnorr::Signature as SchnorrSecpSignature;
13 use bitcoin::secp256k1::Error as SecpError;
14 use bitcoin::secp256k1::ecdsa::RecoveryId;
15 use bitcoin::secp256k1::ecdsa::RecoverableSignature as SecpRecoverableSignature;
16 use bitcoin::secp256k1::Scalar as SecpScalar;
18 use bitcoin::util::address;
20 use core::convert::TryInto; // Bindings need at least rustc 1.34
21 use alloc::borrow::ToOwned;
22 use core::ffi::c_void;
24 #[cfg(feature = "std")]
25 pub(crate) use std::io::{self, Cursor, Read};
26 #[cfg(feature = "no-std")]
27 pub(crate) use core2::io::{self, Cursor, Read};
28 #[cfg(feature = "no-std")]
29 use alloc::{boxed::Box, vec::Vec, string::String};
31 use core::convert::TryFrom;
34 /// A dummy struct of which an instance must never exist.
35 /// This corresponds to the Rust type `Infallible`, or, in unstable rust, `!`
36 pub struct NotConstructable {
37 _priv_thing: core::convert::Infallible,
39 impl From<core::convert::Infallible> for NotConstructable {
40 fn from(_: core::convert::Infallible) -> Self { unreachable!(); }
43 /// Integer in the range `0..32`
44 #[derive(PartialEq, Eq, Copy, Clone)]
45 #[allow(non_camel_case_types)]
49 impl From<bech32::u5> for U5 {
50 fn from(o: bech32::u5) -> Self { Self(o.to_u8()) }
52 impl Into<bech32::u5> for U5 {
53 fn into(self) -> bech32::u5 { bech32::u5::try_from_u8(self.0).expect("u5 objects must be in the range 0..32") }
56 /// Unsigned, 128-bit integer.
58 /// Because LLVM implements an incorrect ABI for 128-bit integers, a wrapper type is defined here.
59 /// See https://github.com/rust-lang/rust/issues/54341 for more details.
60 #[derive(PartialEq, Eq, Copy, Clone)]
61 #[allow(non_camel_case_types)]
64 /// The 128-bit integer, as 16 little-endian bytes
65 pub le_bytes: [u8; 16],
69 /// Gets the 128-bit integer, as 16 little-endian bytes
70 pub extern "C" fn U128_le_bytes(val: U128) -> SixteenBytes { SixteenBytes { data: val.le_bytes } }
72 /// Constructs a new U128 from 16 little-endian bytes
73 pub extern "C" fn U128_new(le_bytes: SixteenBytes) -> U128 { U128 { le_bytes: le_bytes.data } }
75 impl From<u128> for U128 {
76 fn from(o: u128) -> Self { Self { le_bytes: o.to_le_bytes() } }
78 impl From<&mut u128> for U128 {
79 fn from(o: &mut u128) -> U128 { Self::from(*o) }
81 impl Into<u128> for U128 {
82 fn into(self) -> u128 { u128::from_le_bytes(self.le_bytes) }
85 /// Integer in the range `0..=16`
86 #[derive(PartialEq, Eq, Copy, Clone)]
88 pub struct WitnessVersion(u8);
90 impl From<address::WitnessVersion> for WitnessVersion {
91 fn from(o: address::WitnessVersion) -> Self { Self(o.to_num()) }
93 impl Into<address::WitnessVersion> for WitnessVersion {
94 fn into(self) -> address::WitnessVersion {
95 address::WitnessVersion::try_from(self.0).expect("WitnessVersion objects must be in the range 0..=16")
101 /// Represents a valid secp256k1 public key serialized in "compressed form" as a 33 byte array.
102 pub struct PublicKey {
103 /// The bytes of the public key
104 pub compressed_form: [u8; 33],
107 pub(crate) fn from_rust(pk: &SecpPublicKey) -> Self {
109 compressed_form: pk.serialize(),
112 pub(crate) fn into_rust(&self) -> SecpPublicKey {
113 SecpPublicKey::from_slice(&self.compressed_form).unwrap()
115 pub(crate) fn is_null(&self) -> bool { self.compressed_form[..] == [0; 33][..] }
116 pub(crate) fn null() -> Self { Self { compressed_form: [0; 33] } }
121 /// Represents a valid secp256k1 secret key serialized as a 32 byte array.
122 pub struct SecretKey {
123 /// The bytes of the secret key
127 // from_rust isn't implemented for a ref since we just return byte array refs directly
128 pub(crate) fn from_rust(sk: SecpSecretKey) -> Self {
129 let mut bytes = [0; 32];
130 bytes.copy_from_slice(&sk[..]);
133 pub(crate) fn into_rust(&self) -> SecpSecretKey {
134 SecpSecretKey::from_slice(&self.bytes).unwrap()
140 /// Represents a secp256k1 ECDSA signature serialized as two 32-byte numbers
141 pub struct ECDSASignature {
142 /// The bytes of the signature in "compact" form
143 pub compact_form: [u8; 64],
145 impl ECDSASignature {
146 pub(crate) fn from_rust(pk: &ECDSASecpSignature) -> Self {
148 compact_form: pk.serialize_compact(),
151 pub(crate) fn into_rust(&self) -> ECDSASecpSignature {
152 ECDSASecpSignature::from_compact(&self.compact_form).unwrap()
158 /// Represents a secp256k1 Schnorr signature serialized as two 32-byte numbers
159 pub struct SchnorrSignature {
160 /// The bytes of the signature as two 32-byte numbers
161 pub compact_form: [u8; 64],
163 impl SchnorrSignature {
164 pub(crate) fn from_rust(pk: &SchnorrSecpSignature) -> Self {
166 compact_form: pk.as_ref().clone(),
169 pub(crate) fn into_rust(&self) -> SchnorrSecpSignature {
170 SchnorrSecpSignature::from_slice(&self.compact_form).unwrap()
176 /// Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which
177 /// allows recovering the exact public key which created the signature given the message.
178 pub struct RecoverableSignature {
179 /// The bytes of the signature in "compact" form plus a "Recovery ID" which allows for
181 pub serialized_form: [u8; 68],
183 impl RecoverableSignature {
184 pub(crate) fn from_rust(pk: &SecpRecoverableSignature) -> Self {
185 let (id, compact_form) = pk.serialize_compact();
186 let mut serialized_form = [0; 68];
187 serialized_form[0..64].copy_from_slice(&compact_form[..]);
188 serialized_form[64..].copy_from_slice(&id.to_i32().to_le_bytes());
189 Self { serialized_form }
191 pub(crate) fn into_rust(&self) -> SecpRecoverableSignature {
193 id.copy_from_slice(&self.serialized_form[64..]);
194 SecpRecoverableSignature::from_compact(&self.serialized_form[0..64],
195 RecoveryId::from_i32(i32::from_le_bytes(id)).expect("Invalid Recovery ID"))
202 /// Represents a scalar value between zero and the secp256k1 curve order, in big endian.
203 pub struct BigEndianScalar {
204 /// The bytes of the scalar value.
205 pub big_endian_bytes: [u8; 32],
207 impl BigEndianScalar {
208 pub(crate) fn from_rust(scalar: &SecpScalar) -> Self {
209 Self { big_endian_bytes: scalar.to_be_bytes() }
211 pub(crate) fn into_rust(&self) -> SecpScalar {
212 SecpScalar::from_be_bytes(self.big_endian_bytes).expect("Scalar greater than the curve order")
217 /// Convenience function for constructing a new BigEndianScalar
218 pub extern "C" fn BigEndianScalar_new(big_endian_bytes: ThirtyTwoBytes) -> BigEndianScalar {
219 BigEndianScalar { big_endian_bytes: big_endian_bytes.data }
223 #[derive(Copy, Clone)]
224 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
225 pub enum Secp256k1Error {
226 /// Signature failed verification
228 /// Badly sized message ("messages" are actually fixed-sized digests; see the MESSAGE_SIZE constant)
236 /// Bad shared secret.
240 /// Invalid tweak for add_assign or mul_assign
242 /// Didn't pass enough memory to context creation with preallocated memory
244 /// Bad set of public keys.
246 /// The only valid parity values are 0 or 1.
249 impl Secp256k1Error {
250 pub(crate) fn from_rust(err: SecpError) -> Self {
252 SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
253 SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
254 SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
255 SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
256 SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
257 SecpError::InvalidSharedSecret => Secp256k1Error::InvalidSharedSecret,
258 SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
259 SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
260 SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
261 SecpError::InvalidPublicKeySum => Secp256k1Error::InvalidPublicKeySum,
262 SecpError::InvalidParityValue(_) => Secp256k1Error::InvalidParityValue,
265 pub(crate) fn into_rust(self) -> SecpError {
266 let invalid_parity = secp256k1::Parity::from_i32(42).unwrap_err();
268 Secp256k1Error::IncorrectSignature => SecpError::IncorrectSignature,
269 Secp256k1Error::InvalidMessage => SecpError::InvalidMessage,
270 Secp256k1Error::InvalidPublicKey => SecpError::InvalidPublicKey,
271 Secp256k1Error::InvalidSignature => SecpError::InvalidSignature,
272 Secp256k1Error::InvalidSecretKey => SecpError::InvalidSecretKey,
273 Secp256k1Error::InvalidSharedSecret => SecpError::InvalidSharedSecret,
274 Secp256k1Error::InvalidRecoveryId => SecpError::InvalidRecoveryId,
275 Secp256k1Error::InvalidTweak => SecpError::InvalidTweak,
276 Secp256k1Error::NotEnoughMemory => SecpError::NotEnoughMemory,
277 Secp256k1Error::InvalidPublicKeySum => SecpError::InvalidPublicKeySum,
278 Secp256k1Error::InvalidParityValue => SecpError::InvalidParityValue(invalid_parity),
284 #[derive(Copy, Clone)]
285 /// Represents an error returned from the bech32 library during validation of some bech32 data
286 pub enum Bech32Error {
287 /// String does not contain the separator character
289 /// The checksum does not match the rest of the data
291 /// The data or human-readable part is too long or too short
293 /// Some part of the string contains an invalid character
295 /// Some part of the data has an invalid value
297 /// The bit conversion failed due to a padding issue
299 /// The whole string must be of one case
303 pub(crate) fn from_rust(err: bech32::Error) -> Self {
305 bech32::Error::MissingSeparator => Self::MissingSeparator,
306 bech32::Error::InvalidChecksum => Self::InvalidChecksum,
307 bech32::Error::InvalidLength => Self::InvalidLength,
308 bech32::Error::InvalidChar(c) => Self::InvalidChar(c as u32),
309 bech32::Error::InvalidData(d) => Self::InvalidData(d),
310 bech32::Error::InvalidPadding => Self::InvalidPadding,
311 bech32::Error::MixedCase => Self::MixedCase,
314 pub(crate) fn into_rust(self) -> bech32::Error {
316 Self::MissingSeparator => bech32::Error::MissingSeparator,
317 Self::InvalidChecksum => bech32::Error::InvalidChecksum,
318 Self::InvalidLength => bech32::Error::InvalidLength,
319 Self::InvalidChar(c) => bech32::Error::InvalidChar(core::char::from_u32(c).expect("Invalid UTF-8 character in Bech32Error::InvalidChar")),
320 Self::InvalidData(d) => bech32::Error::InvalidData(d),
321 Self::InvalidPadding => bech32::Error::InvalidPadding,
322 Self::MixedCase => bech32::Error::MixedCase,
327 /// Creates a new Bech32Error which has the same data as `orig`
328 pub extern "C" fn Bech32Error_clone(orig: &Bech32Error) -> Bech32Error { orig.clone() }
330 /// Releases any memory held by the given `Bech32Error` (which is currently none)
331 pub extern "C" fn Bech32Error_free(o: Bech32Error) { }
334 #[derive(Clone, Copy, PartialEq)]
335 /// Sub-errors which don't have specific information in them use this type.
337 /// Zero-Sized_types aren't consistent across Rust/C/C++, so we add some size here
342 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
343 #[derive(Clone, Copy, PartialEq)]
344 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
366 pub(crate) fn from_rust_kind(err: io::ErrorKind) -> Self {
368 io::ErrorKind::NotFound => IOError::NotFound,
369 io::ErrorKind::PermissionDenied => IOError::PermissionDenied,
370 io::ErrorKind::ConnectionRefused => IOError::ConnectionRefused,
371 io::ErrorKind::ConnectionReset => IOError::ConnectionReset,
372 io::ErrorKind::ConnectionAborted => IOError::ConnectionAborted,
373 io::ErrorKind::NotConnected => IOError::NotConnected,
374 io::ErrorKind::AddrInUse => IOError::AddrInUse,
375 io::ErrorKind::AddrNotAvailable => IOError::AddrNotAvailable,
376 io::ErrorKind::BrokenPipe => IOError::BrokenPipe,
377 io::ErrorKind::AlreadyExists => IOError::AlreadyExists,
378 io::ErrorKind::WouldBlock => IOError::WouldBlock,
379 io::ErrorKind::InvalidInput => IOError::InvalidInput,
380 io::ErrorKind::InvalidData => IOError::InvalidData,
381 io::ErrorKind::TimedOut => IOError::TimedOut,
382 io::ErrorKind::WriteZero => IOError::WriteZero,
383 io::ErrorKind::Interrupted => IOError::Interrupted,
384 io::ErrorKind::Other => IOError::Other,
385 io::ErrorKind::UnexpectedEof => IOError::UnexpectedEof,
389 pub(crate) fn from_rust(err: io::Error) -> Self {
390 Self::from_rust_kind(err.kind())
392 pub(crate) fn to_rust_kind(&self) -> io::ErrorKind {
394 IOError::NotFound => io::ErrorKind::NotFound,
395 IOError::PermissionDenied => io::ErrorKind::PermissionDenied,
396 IOError::ConnectionRefused => io::ErrorKind::ConnectionRefused,
397 IOError::ConnectionReset => io::ErrorKind::ConnectionReset,
398 IOError::ConnectionAborted => io::ErrorKind::ConnectionAborted,
399 IOError::NotConnected => io::ErrorKind::NotConnected,
400 IOError::AddrInUse => io::ErrorKind::AddrInUse,
401 IOError::AddrNotAvailable => io::ErrorKind::AddrNotAvailable,
402 IOError::BrokenPipe => io::ErrorKind::BrokenPipe,
403 IOError::AlreadyExists => io::ErrorKind::AlreadyExists,
404 IOError::WouldBlock => io::ErrorKind::WouldBlock,
405 IOError::InvalidInput => io::ErrorKind::InvalidInput,
406 IOError::InvalidData => io::ErrorKind::InvalidData,
407 IOError::TimedOut => io::ErrorKind::TimedOut,
408 IOError::WriteZero => io::ErrorKind::WriteZero,
409 IOError::Interrupted => io::ErrorKind::Interrupted,
410 IOError::Other => io::ErrorKind::Other,
411 IOError::UnexpectedEof => io::ErrorKind::UnexpectedEof,
414 pub(crate) fn to_rust(&self) -> io::Error {
415 io::Error::new(self.to_rust_kind(), "")
420 /// A serialized transaction, in (pointer, length) form.
422 /// This type optionally owns its own memory, and thus the semantics around access change based on
423 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
424 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
425 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
426 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
427 /// you would be invalid.
429 /// Note that, while it may change in the future, because transactions on the Rust side are stored
430 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
431 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
432 /// `data_is_owned` either set or unset at your discretion.
433 pub struct Transaction {
434 /// The serialized transaction data.
436 /// This is non-const for your convenience, an object passed to Rust is never written to.
438 /// The length of the serialized transaction
440 /// Whether the data pointed to by `data` should be freed or not.
441 pub data_is_owned: bool,
444 fn from_vec(vec: Vec<u8>) -> Self {
445 let datalen = vec.len();
446 let data = Box::into_raw(vec.into_boxed_slice());
448 data: unsafe { (*data).as_mut_ptr() },
453 pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
454 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
455 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
457 pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
458 let vec = ::bitcoin::consensus::encode::serialize(btc);
462 impl Drop for Transaction {
464 if self.data_is_owned && self.datalen != 0 {
465 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
469 impl Clone for Transaction {
470 fn clone(&self) -> Self {
471 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
472 let mut v = Vec::new();
473 v.extend_from_slice(&sl);
478 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
479 pub extern "C" fn Transaction_free(_res: Transaction) { }
482 /// A serialized witness.
484 /// The serialized transaction data.
486 /// This is non-const for your convenience, an object passed to Rust is never written to.
488 /// The length of the serialized transaction
490 /// Whether the data pointed to by `data` should be freed or not.
491 pub data_is_owned: bool,
494 fn from_vec(vec: Vec<u8>) -> Self {
495 let datalen = vec.len();
496 let data = Box::into_raw(vec.into_boxed_slice());
498 data: unsafe { (*data).as_mut_ptr() },
503 pub(crate) fn into_bitcoin(&self) -> BitcoinWitness {
504 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
506 pub(crate) fn from_bitcoin(btc: &BitcoinWitness) -> Self {
507 let vec = ::bitcoin::consensus::encode::serialize(btc);
512 impl Drop for Witness {
514 if self.data_is_owned && self.datalen != 0 {
515 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
519 impl Clone for Witness {
520 fn clone(&self) -> Self {
521 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
522 let mut v = Vec::new();
523 v.extend_from_slice(&sl);
529 /// Creates a new Witness which has the same data as `orig` but with a new buffer.
530 pub extern "C" fn Witness_clone(orig: &Witness) -> Witness { orig.clone() }
533 /// Frees the data pointed to by data
534 pub extern "C" fn Witness_free(_res: Witness) { }
536 pub(crate) fn bitcoin_to_C_outpoint(outpoint: &::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
537 crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: outpoint.txid.into_inner() }, outpoint.vout.try_into().unwrap())
539 pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
541 ::bitcoin::blockdata::transaction::OutPoint {
542 txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
549 /// An input to a transaction.
551 /// This contains the witness, the scriptSig and the previous outpoint and represents a single
552 /// input to a transaction
554 /// The witness which includes any signatures required to spend a segwit output.
555 pub witness: Witness,
556 /// The script_sig which includes signatures requires to spend a pre-segwit output (or a
557 /// P2SH-wrapped segwit output).
558 pub script_sig: derived::CVec_u8Z,
559 /// The sequence number of the transaction input
561 /// The txid of the transaction being spent.
562 pub previous_txid: ThirtyTwoBytes,
563 /// The output index of the transaction being spent.
564 pub previous_vout: u32,
568 pub(crate) fn from_rust(txin: &::bitcoin::blockdata::transaction::TxIn) -> Self {
570 witness: Witness::from_bitcoin(&txin.witness),
571 script_sig: derived::CVec_u8Z::from(txin.script_sig.clone().into_bytes()),
572 sequence: txin.sequence.0,
573 previous_txid: ThirtyTwoBytes { data: txin.previous_output.txid.into_inner() },
574 previous_vout: txin.previous_output.vout,
580 /// Frees the witness and script_sig in a TxIn
581 pub extern "C" fn TxIn_free(_res: TxIn) { }
584 /// Convenience function for constructing a new TxIn
585 pub extern "C" fn TxIn_new(witness: Witness, script_sig: derived::CVec_u8Z, sequence: u32, previous_txid: ThirtyTwoBytes, previous_vout: u32) -> TxIn {
586 TxIn { witness, script_sig, sequence, previous_txid, previous_vout }
592 /// A transaction output including a scriptPubKey and value.
593 /// This type *does* own its own memory, so must be free'd appropriately.
595 /// The script_pubkey in this output
596 pub script_pubkey: derived::CVec_u8Z,
597 /// The value, in satoshis, of this output
602 pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
603 ::bitcoin::blockdata::transaction::TxOut {
604 script_pubkey: self.script_pubkey.into_rust().into(),
608 pub(crate) fn from_rust(txout: &::bitcoin::blockdata::transaction::TxOut) -> Self {
610 script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.clone().into_bytes()),
617 /// Convenience function for constructing a new TxOut
618 pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
619 TxOut { script_pubkey, value }
622 /// Frees the data pointed to by script_pubkey.
623 pub extern "C" fn TxOut_free(_res: TxOut) { }
625 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
626 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
629 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
630 /// own the memory pointed to by data.
632 /// A pointer to the byte buffer
634 /// The number of bytes pointed to by `data`.
638 pub(crate) fn from_slice(s: &[u8]) -> Self {
644 pub(crate) fn to_slice(&self) -> &[u8] {
645 if self.datalen == 0 { return &[]; }
646 unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
648 pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
649 let sl = self.to_slice();
652 pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
653 Self::from_slice(v.as_slice())
656 pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
657 let mut res = Vec::new();
658 r.read_to_end(&mut res).unwrap();
659 derived::CVec_u8Z::from(res)
663 #[derive(Copy, Clone)]
664 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
665 /// look up the corresponding function in rust-lightning's docs.
666 pub struct ThirtyTwoBytes {
667 /// The thirty-two bytes
672 /// A 3-byte byte array.
673 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
676 /// A 4-byte byte array.
677 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
680 /// A 12-byte byte array.
681 pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
684 /// A 16-byte byte array.
685 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
688 /// A 20-byte byte array.
689 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
694 pub struct ThirtyTwoU16s { /** The thirty-two 16-bit integers */ pub data: [u16; 32], }
696 pub(crate) struct VecWriter(pub Vec<u8>);
697 impl lightning::util::ser::Writer for VecWriter {
698 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
699 self.0.extend_from_slice(buf);
703 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
704 let mut out = VecWriter(Vec::new());
705 i.write(&mut out).unwrap();
706 derived::CVec_u8Z::from(out.0)
708 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
709 I::read(&mut s.to_slice())
711 pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
712 I::read(&mut s.to_slice())
714 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
715 I::read(&mut s.to_slice(), args)
719 /// A Rust str object, ie a reference to a UTF8-valid string.
720 /// This is *not* null-terminated so cannot be used directly as a C string!
722 /// A pointer to the string's bytes, in UTF8 encoding
723 pub chars: *const u8,
724 /// The number of bytes (not characters!) pointed to by `chars`
726 /// Whether the data pointed to by `chars` should be freed or not.
727 pub chars_is_owned: bool,
729 impl Into<Str> for &str {
730 fn into(self) -> Str {
731 self.to_owned().into()
734 impl Into<Str> for &mut &str {
735 fn into(self) -> Str {
736 let us: &str = *self;
742 pub(crate) fn into_str(&self) -> &'static str {
743 if self.len == 0 { return ""; }
744 core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
746 pub(crate) fn into_string(mut self) -> String {
747 let bytes = if self.len == 0 {
749 } else if self.chars_is_owned {
751 Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
753 self.chars_is_owned = false;
756 let mut ret = Vec::with_capacity(self.len);
757 ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
760 String::from_utf8(bytes).unwrap()
762 #[cfg(feature = "std")]
763 pub(crate) fn into_pathbuf(mut self) -> std::path::PathBuf {
764 std::path::PathBuf::from(self.into_string())
767 impl Into<Str> for String {
768 fn into(self) -> Str {
769 let s = Box::leak(self.into_boxed_str());
770 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
773 #[cfg(feature = "std")]
774 impl Into<Str> for std::path::PathBuf {
775 fn into(self) -> Str {
776 self.into_os_string().into_string().expect("We expect paths to be UTF-8 valid").into()
780 fn clone(&self) -> Self {
781 String::from(self.into_str()).into()
787 if self.chars_is_owned && self.len != 0 {
788 let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
793 /// Frees the data buffer, if chars_is_owned is set and len > 0.
794 pub extern "C" fn Str_free(_res: Str) { }
796 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
797 // Thus, they must gracefully handle being completely null in _free.
799 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
800 // everywhere in the containers.
803 pub(crate) union CResultPtr<O, E> {
804 pub(crate) result: *mut O,
805 pub(crate) err: *mut E,
808 pub(crate) struct CResultTempl<O, E> {
809 pub(crate) contents: CResultPtr<O, E>,
810 pub(crate) result_ok: bool,
812 impl<O, E> CResultTempl<O, E> {
813 pub(crate) extern "C" fn ok(o: O) -> Self {
815 contents: CResultPtr {
816 result: Box::into_raw(Box::new(o)),
821 pub(crate) extern "C" fn err(e: E) -> Self {
823 contents: CResultPtr {
824 err: Box::into_raw(Box::new(e)),
830 impl<O, E> Drop for CResultTempl<O, E> {
833 if unsafe { !self.contents.result.is_null() } {
834 let _ = unsafe { Box::from_raw(self.contents.result) };
836 } else if unsafe { !self.contents.err.is_null() } {
837 let _ = unsafe { Box::from_raw(self.contents.err) };
842 /// Utility to make it easy to set a pointer to null and get its original value in line.
843 pub(crate) trait TakePointer<T> {
844 fn take_ptr(&mut self) -> T;
846 impl<T> TakePointer<*const T> for *const T {
847 fn take_ptr(&mut self) -> *const T {
849 *self = core::ptr::null();
853 impl<T> TakePointer<*mut T> for *mut T {
854 fn take_ptr(&mut self) -> *mut T {
856 *self = core::ptr::null_mut();
862 pub(crate) mod ObjOps {
863 #[cfg(feature = "no-std")]
864 use alloc::boxed::Box;
867 #[must_use = "returns new dangling pointer"]
868 pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
869 let ptr = Box::into_raw(Box::new(obj));
870 nonnull_ptr_to_inner(ptr)
873 pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
874 if core::mem::size_of::<T>() == 0 {
875 // We map `None::<T>` as `T { inner: null, .. }` which works great for all
876 // non-Zero-Sized-Types `T`.
877 // For ZSTs, we need to differentiate between null implying `None` and null implying
878 // `Some` with no allocation.
879 // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
880 // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
881 // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
882 // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
884 // Note that we add 4095 here as at least the Java client assumes that the low bit on
885 // any heap pointer is 0, which is generally provided by malloc, but which is not true
886 // for ZSTs "allocated" by `Box::new`.
887 debug_assert_eq!(ptr as usize, 1);
888 unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
890 // In order to get better test coverage, also increment non-ZST pointers with
891 // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
892 #[cfg(test_mod_pointers)]
893 unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
894 #[cfg(not(test_mod_pointers))]
895 unsafe { ptr as *mut T }
899 /// Invert nonnull_ptr_to_inner
900 pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
901 if core::mem::size_of::<T>() == 0 {
902 unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
904 #[cfg(test_mod_pointers)]
905 unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
906 #[cfg(not(test_mod_pointers))]
912 #[cfg(test_mod_pointers)]
914 /// This function exists for memory safety testing purposes. It should never be used in production
916 pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
917 if ptr as usize == 1 {
920 unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
924 pub(crate) struct SmartPtr<T> {
927 impl<T> SmartPtr<T> {
928 pub(crate) fn from_obj(o: T) -> Self {
929 Self { ptr: Box::into_raw(Box::new(o)) }
931 pub(crate) fn null() -> Self {
932 Self { ptr: core::ptr::null_mut() }
935 impl<T> Drop for SmartPtr<T> {
937 if self.ptr != core::ptr::null_mut() {
938 let _ = unsafe { Box::from_raw(self.ptr) };
942 impl<T> core::ops::Deref for SmartPtr<T> {
943 type Target = *mut T;
944 fn deref(&self) -> &*mut T {