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;
9 use bitcoin::address::WitnessProgram as BitcoinWitnessProgram;
10 use bitcoin::hashes::Hash;
11 use bitcoin::secp256k1::PublicKey as SecpPublicKey;
12 use bitcoin::secp256k1::SecretKey as SecpSecretKey;
13 use bitcoin::secp256k1::ecdsa::Signature as ECDSASecpSignature;
14 use bitcoin::secp256k1::schnorr::Signature as SchnorrSecpSignature;
15 use bitcoin::secp256k1::Error as SecpError;
16 use bitcoin::secp256k1::ecdsa::RecoveryId;
17 use bitcoin::secp256k1::ecdsa::RecoverableSignature as SecpRecoverableSignature;
18 use bitcoin::secp256k1::Scalar as SecpScalar;
21 use core::convert::TryInto; // Bindings need at least rustc 1.34
22 use alloc::borrow::ToOwned;
23 use core::ffi::c_void;
25 #[cfg(feature = "std")]
26 pub(crate) use std::io::{self, Cursor, Read};
27 #[cfg(feature = "no-std")]
28 pub(crate) use core2::io::{self, Cursor, Read};
29 #[cfg(feature = "no-std")]
30 use alloc::{boxed::Box, vec::Vec, string::String};
32 use core::convert::TryFrom;
35 /// A dummy struct of which an instance must never exist.
36 /// This corresponds to the Rust type `Infallible`, or, in unstable rust, `!`
37 pub struct NotConstructable {
38 _priv_thing: core::convert::Infallible,
40 impl From<core::convert::Infallible> for NotConstructable {
41 fn from(_: core::convert::Infallible) -> Self { unreachable!(); }
44 /// Integer in the range `0..32`
45 #[derive(PartialEq, Eq, Copy, Clone)]
46 #[allow(non_camel_case_types)]
50 impl From<bech32::u5> for U5 {
51 fn from(o: bech32::u5) -> Self { Self(o.to_u8()) }
53 impl Into<bech32::u5> for U5 {
54 fn into(self) -> bech32::u5 { bech32::u5::try_from_u8(self.0).expect("u5 objects must be in the range 0..32") }
57 /// Unsigned, 128-bit integer.
59 /// Because LLVM implements an incorrect ABI for 128-bit integers, a wrapper type is defined here.
60 /// See https://github.com/rust-lang/rust/issues/54341 for more details.
61 #[derive(PartialEq, Eq, Copy, Clone)]
62 #[allow(non_camel_case_types)]
65 /// The 128-bit integer, as 16 little-endian bytes
66 pub le_bytes: [u8; 16],
70 /// Gets the 128-bit integer, as 16 little-endian bytes
71 pub extern "C" fn U128_le_bytes(val: U128) -> SixteenBytes { SixteenBytes { data: val.le_bytes } }
73 /// Constructs a new U128 from 16 little-endian bytes
74 pub extern "C" fn U128_new(le_bytes: SixteenBytes) -> U128 { U128 { le_bytes: le_bytes.data } }
76 impl From<u128> for U128 {
77 fn from(o: u128) -> Self { Self { le_bytes: o.to_le_bytes() } }
79 impl From<&mut u128> for U128 {
80 fn from(o: &mut u128) -> U128 { Self::from(*o) }
82 impl Into<u128> for U128 {
83 fn into(self) -> u128 { u128::from_le_bytes(self.le_bytes) }
86 /// Integer in the range `0..=16`
87 #[derive(PartialEq, Eq, Copy, Clone)]
89 pub struct WitnessVersion(u8);
91 impl From<address::WitnessVersion> for WitnessVersion {
92 fn from(o: address::WitnessVersion) -> Self { Self(o.to_num()) }
94 impl Into<address::WitnessVersion> for WitnessVersion {
95 fn into(self) -> address::WitnessVersion {
96 address::WitnessVersion::try_from(self.0).expect("WitnessVersion objects must be in the range 0..=16")
100 /// A segregated witness version byte and script bytes
103 pub struct WitnessProgram {
104 version: WitnessVersion,
105 program: derived::CVec_u8Z,
107 impl WitnessProgram {
108 pub(crate) fn from_bitcoin(o: BitcoinWitnessProgram) -> Self {
110 version: o.version().into(),
111 program: o.program().as_bytes().to_vec().into(),
114 pub(crate) fn into_bitcoin(mut self) -> BitcoinWitnessProgram {
115 BitcoinWitnessProgram::new(
117 self.program.into_rust(),
118 ).expect("Program length was previously checked")
123 /// Constructs a new WitnessProgram given a version and program bytes.
125 /// The program MUST be at least 2 bytes and no longer than 40 bytes long.
126 /// Further, if the version is 0, the program MUST be either exactly 20 or exactly 32 bytes long.
127 pub extern "C" fn WitnessProgram_new(version: WitnessVersion, program: derived::CVec_u8Z) -> WitnessProgram {
128 assert!(program.datalen >= 2, "WitnessProgram program lengths must be at least 2 bytes long");
129 assert!(program.datalen <= 40, "WitnessProgram program lengths must be no longer than 40 bytes");
131 assert!(program.datalen == 20 || program.datalen == 32, "WitnessProgram program length must be 20 or 32 for version-0 programs");
133 WitnessProgram { version, program }
136 /// Gets the `WitnessVersion` of the given `WitnessProgram`
137 pub extern "C" fn WitnessProgram_get_version(prog: &WitnessProgram) -> WitnessVersion {
141 /// Gets the witness program bytes of the given `WitnessProgram`
142 pub extern "C" fn WitnessProgram_get_program(prog: &WitnessProgram) -> u8slice {
143 u8slice::from_vec(&prog.program)
146 /// Creates a new WitnessProgram which has the same data as `orig`
147 pub extern "C" fn WitnessProgram_clone(orig: &WitnessProgram) -> WitnessProgram { orig.clone() }
149 /// Releases any memory held by the given `WitnessProgram` (which is currently none)
150 pub extern "C" fn WitnessProgram_free(o: WitnessProgram) { }
154 /// Represents a valid secp256k1 public key serialized in "compressed form" as a 33 byte array.
155 pub struct PublicKey {
156 /// The bytes of the public key
157 pub compressed_form: [u8; 33],
160 pub(crate) fn from_rust(pk: &SecpPublicKey) -> Self {
162 compressed_form: pk.serialize(),
165 pub(crate) fn into_rust(&self) -> SecpPublicKey {
166 SecpPublicKey::from_slice(&self.compressed_form).unwrap()
168 pub(crate) fn is_null(&self) -> bool { self.compressed_form[..] == [0; 33][..] }
169 pub(crate) fn null() -> Self { Self { compressed_form: [0; 33] } }
174 /// Represents a valid secp256k1 secret key serialized as a 32 byte array.
175 pub struct SecretKey {
176 /// The bytes of the secret key
180 // from_rust isn't implemented for a ref since we just return byte array refs directly
181 pub(crate) fn from_rust(sk: SecpSecretKey) -> Self {
182 let mut bytes = [0; 32];
183 bytes.copy_from_slice(&sk[..]);
186 pub(crate) fn into_rust(&self) -> SecpSecretKey {
187 SecpSecretKey::from_slice(&self.bytes).unwrap()
193 /// Represents a secp256k1 ECDSA signature serialized as two 32-byte numbers
194 pub struct ECDSASignature {
195 /// The bytes of the signature in "compact" form
196 pub compact_form: [u8; 64],
198 impl ECDSASignature {
199 pub(crate) fn from_rust(pk: &ECDSASecpSignature) -> Self {
201 compact_form: pk.serialize_compact(),
204 pub(crate) fn into_rust(&self) -> ECDSASecpSignature {
205 ECDSASecpSignature::from_compact(&self.compact_form).unwrap()
211 /// Represents a secp256k1 Schnorr signature serialized as two 32-byte numbers
212 pub struct SchnorrSignature {
213 /// The bytes of the signature as two 32-byte numbers
214 pub compact_form: [u8; 64],
216 impl SchnorrSignature {
217 pub(crate) fn from_rust(pk: &SchnorrSecpSignature) -> Self {
219 compact_form: pk.as_ref().clone(),
222 pub(crate) fn into_rust(&self) -> SchnorrSecpSignature {
223 SchnorrSecpSignature::from_slice(&self.compact_form).unwrap()
229 /// Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which
230 /// allows recovering the exact public key which created the signature given the message.
231 pub struct RecoverableSignature {
232 /// The bytes of the signature in "compact" form plus a "Recovery ID" which allows for
234 pub serialized_form: [u8; 68],
236 impl RecoverableSignature {
237 pub(crate) fn from_rust(pk: &SecpRecoverableSignature) -> Self {
238 let (id, compact_form) = pk.serialize_compact();
239 let mut serialized_form = [0; 68];
240 serialized_form[0..64].copy_from_slice(&compact_form[..]);
241 serialized_form[64..].copy_from_slice(&id.to_i32().to_le_bytes());
242 Self { serialized_form }
244 pub(crate) fn into_rust(&self) -> SecpRecoverableSignature {
246 id.copy_from_slice(&self.serialized_form[64..]);
247 SecpRecoverableSignature::from_compact(&self.serialized_form[0..64],
248 RecoveryId::from_i32(i32::from_le_bytes(id)).expect("Invalid Recovery ID"))
255 /// Represents a scalar value between zero and the secp256k1 curve order, in big endian.
256 pub struct BigEndianScalar {
257 /// The bytes of the scalar value.
258 pub big_endian_bytes: [u8; 32],
260 impl BigEndianScalar {
261 pub(crate) fn from_rust(scalar: &SecpScalar) -> Self {
262 Self { big_endian_bytes: scalar.to_be_bytes() }
264 pub(crate) fn into_rust(&self) -> SecpScalar {
265 SecpScalar::from_be_bytes(self.big_endian_bytes).expect("Scalar greater than the curve order")
270 /// Convenience function for constructing a new BigEndianScalar
271 pub extern "C" fn BigEndianScalar_new(big_endian_bytes: ThirtyTwoBytes) -> BigEndianScalar {
272 BigEndianScalar { big_endian_bytes: big_endian_bytes.data }
276 #[derive(Copy, Clone)]
277 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
278 pub enum Secp256k1Error {
279 /// Signature failed verification
281 /// Badly sized message ("messages" are actually fixed-sized digests; see the MESSAGE_SIZE constant)
289 /// Bad shared secret.
293 /// Invalid tweak for add_assign or mul_assign
295 /// Didn't pass enough memory to context creation with preallocated memory
297 /// Bad set of public keys.
299 /// The only valid parity values are 0 or 1.
302 impl Secp256k1Error {
303 pub(crate) fn from_rust(err: SecpError) -> Self {
305 SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
306 SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
307 SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
308 SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
309 SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
310 SecpError::InvalidSharedSecret => Secp256k1Error::InvalidSharedSecret,
311 SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
312 SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
313 SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
314 SecpError::InvalidPublicKeySum => Secp256k1Error::InvalidPublicKeySum,
315 SecpError::InvalidParityValue(_) => Secp256k1Error::InvalidParityValue,
318 pub(crate) fn into_rust(self) -> SecpError {
319 let invalid_parity = secp256k1::Parity::from_i32(42).unwrap_err();
321 Secp256k1Error::IncorrectSignature => SecpError::IncorrectSignature,
322 Secp256k1Error::InvalidMessage => SecpError::InvalidMessage,
323 Secp256k1Error::InvalidPublicKey => SecpError::InvalidPublicKey,
324 Secp256k1Error::InvalidSignature => SecpError::InvalidSignature,
325 Secp256k1Error::InvalidSecretKey => SecpError::InvalidSecretKey,
326 Secp256k1Error::InvalidSharedSecret => SecpError::InvalidSharedSecret,
327 Secp256k1Error::InvalidRecoveryId => SecpError::InvalidRecoveryId,
328 Secp256k1Error::InvalidTweak => SecpError::InvalidTweak,
329 Secp256k1Error::NotEnoughMemory => SecpError::NotEnoughMemory,
330 Secp256k1Error::InvalidPublicKeySum => SecpError::InvalidPublicKeySum,
331 Secp256k1Error::InvalidParityValue => SecpError::InvalidParityValue(invalid_parity),
337 #[derive(Copy, Clone)]
338 /// Represents an error returned from the bech32 library during validation of some bech32 data
339 pub enum Bech32Error {
340 /// String does not contain the separator character
342 /// The checksum does not match the rest of the data
344 /// The data or human-readable part is too long or too short
346 /// Some part of the string contains an invalid character
348 /// Some part of the data has an invalid value
350 /// The bit conversion failed due to a padding issue
352 /// The whole string must be of one case
356 pub(crate) fn from_rust(err: bech32::Error) -> Self {
358 bech32::Error::MissingSeparator => Self::MissingSeparator,
359 bech32::Error::InvalidChecksum => Self::InvalidChecksum,
360 bech32::Error::InvalidLength => Self::InvalidLength,
361 bech32::Error::InvalidChar(c) => Self::InvalidChar(c as u32),
362 bech32::Error::InvalidData(d) => Self::InvalidData(d),
363 bech32::Error::InvalidPadding => Self::InvalidPadding,
364 bech32::Error::MixedCase => Self::MixedCase,
367 pub(crate) fn into_rust(self) -> bech32::Error {
369 Self::MissingSeparator => bech32::Error::MissingSeparator,
370 Self::InvalidChecksum => bech32::Error::InvalidChecksum,
371 Self::InvalidLength => bech32::Error::InvalidLength,
372 Self::InvalidChar(c) => bech32::Error::InvalidChar(core::char::from_u32(c).expect("Invalid UTF-8 character in Bech32Error::InvalidChar")),
373 Self::InvalidData(d) => bech32::Error::InvalidData(d),
374 Self::InvalidPadding => bech32::Error::InvalidPadding,
375 Self::MixedCase => bech32::Error::MixedCase,
380 /// Creates a new Bech32Error which has the same data as `orig`
381 pub extern "C" fn Bech32Error_clone(orig: &Bech32Error) -> Bech32Error { orig.clone() }
383 /// Releases any memory held by the given `Bech32Error` (which is currently none)
384 pub extern "C" fn Bech32Error_free(o: Bech32Error) { }
387 #[derive(Clone, Copy, PartialEq)]
388 /// Sub-errors which don't have specific information in them use this type.
390 /// Zero-Sized_types aren't consistent across Rust/C/C++, so we add some size here
395 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
396 #[derive(Clone, Copy, PartialEq)]
397 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
419 pub(crate) fn from_rust_kind(err: io::ErrorKind) -> Self {
421 io::ErrorKind::NotFound => IOError::NotFound,
422 io::ErrorKind::PermissionDenied => IOError::PermissionDenied,
423 io::ErrorKind::ConnectionRefused => IOError::ConnectionRefused,
424 io::ErrorKind::ConnectionReset => IOError::ConnectionReset,
425 io::ErrorKind::ConnectionAborted => IOError::ConnectionAborted,
426 io::ErrorKind::NotConnected => IOError::NotConnected,
427 io::ErrorKind::AddrInUse => IOError::AddrInUse,
428 io::ErrorKind::AddrNotAvailable => IOError::AddrNotAvailable,
429 io::ErrorKind::BrokenPipe => IOError::BrokenPipe,
430 io::ErrorKind::AlreadyExists => IOError::AlreadyExists,
431 io::ErrorKind::WouldBlock => IOError::WouldBlock,
432 io::ErrorKind::InvalidInput => IOError::InvalidInput,
433 io::ErrorKind::InvalidData => IOError::InvalidData,
434 io::ErrorKind::TimedOut => IOError::TimedOut,
435 io::ErrorKind::WriteZero => IOError::WriteZero,
436 io::ErrorKind::Interrupted => IOError::Interrupted,
437 io::ErrorKind::Other => IOError::Other,
438 io::ErrorKind::UnexpectedEof => IOError::UnexpectedEof,
442 pub(crate) fn from_rust(err: io::Error) -> Self {
443 Self::from_rust_kind(err.kind())
445 pub(crate) fn to_rust_kind(&self) -> io::ErrorKind {
447 IOError::NotFound => io::ErrorKind::NotFound,
448 IOError::PermissionDenied => io::ErrorKind::PermissionDenied,
449 IOError::ConnectionRefused => io::ErrorKind::ConnectionRefused,
450 IOError::ConnectionReset => io::ErrorKind::ConnectionReset,
451 IOError::ConnectionAborted => io::ErrorKind::ConnectionAborted,
452 IOError::NotConnected => io::ErrorKind::NotConnected,
453 IOError::AddrInUse => io::ErrorKind::AddrInUse,
454 IOError::AddrNotAvailable => io::ErrorKind::AddrNotAvailable,
455 IOError::BrokenPipe => io::ErrorKind::BrokenPipe,
456 IOError::AlreadyExists => io::ErrorKind::AlreadyExists,
457 IOError::WouldBlock => io::ErrorKind::WouldBlock,
458 IOError::InvalidInput => io::ErrorKind::InvalidInput,
459 IOError::InvalidData => io::ErrorKind::InvalidData,
460 IOError::TimedOut => io::ErrorKind::TimedOut,
461 IOError::WriteZero => io::ErrorKind::WriteZero,
462 IOError::Interrupted => io::ErrorKind::Interrupted,
463 IOError::Other => io::ErrorKind::Other,
464 IOError::UnexpectedEof => io::ErrorKind::UnexpectedEof,
467 pub(crate) fn to_rust(&self) -> io::Error {
468 io::Error::new(self.to_rust_kind(), "")
473 /// A serialized transaction, in (pointer, length) form.
475 /// This type optionally owns its own memory, and thus the semantics around access change based on
476 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
477 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
478 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
479 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
480 /// you would be invalid.
482 /// Note that, while it may change in the future, because transactions on the Rust side are stored
483 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
484 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
485 /// `data_is_owned` either set or unset at your discretion.
486 pub struct Transaction {
487 /// The serialized transaction data.
489 /// This is non-const for your convenience, an object passed to Rust is never written to.
491 /// The length of the serialized transaction
493 /// Whether the data pointed to by `data` should be freed or not.
494 pub data_is_owned: bool,
497 fn from_vec(vec: Vec<u8>) -> Self {
498 let datalen = vec.len();
499 let data = Box::into_raw(vec.into_boxed_slice());
501 data: unsafe { (*data).as_mut_ptr() },
506 pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
507 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
508 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
510 pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
511 let vec = ::bitcoin::consensus::encode::serialize(btc);
515 impl Drop for Transaction {
517 if self.data_is_owned && self.datalen != 0 {
518 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
522 impl Clone for Transaction {
523 fn clone(&self) -> Self {
524 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
525 let mut v = Vec::new();
526 v.extend_from_slice(&sl);
531 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
532 pub extern "C" fn Transaction_free(_res: Transaction) { }
535 /// A serialized witness.
537 /// The serialized transaction data.
539 /// This is non-const for your convenience, an object passed to Rust is never written to.
541 /// The length of the serialized transaction
543 /// Whether the data pointed to by `data` should be freed or not.
544 pub data_is_owned: bool,
547 fn from_vec(vec: Vec<u8>) -> Self {
548 let datalen = vec.len();
549 let data = Box::into_raw(vec.into_boxed_slice());
551 data: unsafe { (*data).as_mut_ptr() },
556 pub(crate) fn into_bitcoin(&self) -> BitcoinWitness {
557 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
559 pub(crate) fn from_bitcoin(btc: &BitcoinWitness) -> Self {
560 let vec = ::bitcoin::consensus::encode::serialize(btc);
565 impl Drop for Witness {
567 if self.data_is_owned && self.datalen != 0 {
568 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
572 impl Clone for Witness {
573 fn clone(&self) -> Self {
574 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
575 let mut v = Vec::new();
576 v.extend_from_slice(&sl);
582 /// Creates a new Witness which has the same data as `orig` but with a new buffer.
583 pub extern "C" fn Witness_clone(orig: &Witness) -> Witness { orig.clone() }
586 /// Frees the data pointed to by data
587 pub extern "C" fn Witness_free(_res: Witness) { }
589 pub(crate) fn bitcoin_to_C_outpoint(outpoint: &::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
590 crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: *outpoint.txid.as_ref() }, outpoint.vout.try_into().unwrap())
592 pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
594 ::bitcoin::blockdata::transaction::OutPoint {
595 txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
602 /// An input to a transaction.
604 /// This contains the witness, the scriptSig and the previous outpoint and represents a single
605 /// input to a transaction
607 /// The witness which includes any signatures required to spend a segwit output.
608 pub witness: Witness,
609 /// The script_sig which includes signatures requires to spend a pre-segwit output (or a
610 /// P2SH-wrapped segwit output).
611 pub script_sig: derived::CVec_u8Z,
612 /// The sequence number of the transaction input
614 /// The txid of the transaction being spent.
615 pub previous_txid: ThirtyTwoBytes,
616 /// The output index of the transaction being spent.
617 pub previous_vout: u32,
621 pub(crate) fn from_rust(txin: &::bitcoin::blockdata::transaction::TxIn) -> Self {
623 witness: Witness::from_bitcoin(&txin.witness),
624 script_sig: derived::CVec_u8Z::from(txin.script_sig.clone().into_bytes()),
625 sequence: txin.sequence.0,
626 previous_txid: ThirtyTwoBytes { data: *txin.previous_output.txid.as_ref() },
627 previous_vout: txin.previous_output.vout,
632 /// Convenience function for constructing a new TxIn
633 pub extern "C" fn TxIn_new(witness: Witness, script_sig: derived::CVec_u8Z, sequence: u32, previous_txid: ThirtyTwoBytes, previous_vout: u32) -> TxIn {
634 TxIn { witness, script_sig, sequence, previous_txid, previous_vout }
637 /// Gets the `witness` in the given `TxIn`.
638 pub extern "C" fn TxIn_get_witness(txin: &TxIn) -> Witness {
642 /// Gets the `script_sig` in the given `TxIn`.
643 pub extern "C" fn TxIn_get_script_sig(txin: &TxIn) -> u8slice {
644 u8slice::from_vec(&txin.script_sig)
647 /// Gets the `sequence` in the given `TxIn`.
648 pub extern "C" fn TxIn_get_sequence(txin: &TxIn) -> u32 {
652 /// Gets the previous outpoint txid in the given `TxIn`.
653 pub extern "C" fn TxIn_get_previous_txid(txin: &TxIn) -> ThirtyTwoBytes {
657 /// Gets the previout outpoint index in the given `TxIn`.
658 pub extern "C" fn TxIn_get_previous_vout(txin: &TxIn) -> u32 {
662 /// Frees the witness and script_sig in a TxIn
663 pub extern "C" fn TxIn_free(_res: TxIn) { }
667 /// A transaction output including a scriptPubKey and value.
668 /// This type *does* own its own memory, so must be free'd appropriately.
670 /// The script_pubkey in this output
671 pub script_pubkey: derived::CVec_u8Z,
672 /// The value, in satoshis, of this output
677 pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
678 ::bitcoin::blockdata::transaction::TxOut {
679 script_pubkey: self.script_pubkey.into_rust().into(),
683 pub(crate) fn from_rust(txout: &::bitcoin::blockdata::transaction::TxOut) -> Self {
685 script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.clone().into_bytes()),
692 /// Convenience function for constructing a new TxOut
693 pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
694 TxOut { script_pubkey, value }
697 /// Gets the `script_pubkey` in the given `TxOut`.
698 pub extern "C" fn TxOut_get_script_pubkey(txout: &TxOut) -> u8slice {
699 u8slice::from_vec(&txout.script_pubkey)
702 /// Gets the value in the given `TxOut`.
703 pub extern "C" fn TxOut_get_value(txout: &TxOut) -> u64 {
707 /// Frees the data pointed to by script_pubkey.
708 pub extern "C" fn TxOut_free(_res: TxOut) { }
710 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
711 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
714 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
715 /// own the memory pointed to by data.
717 /// A pointer to the byte buffer
719 /// The number of bytes pointed to by `data`.
723 pub(crate) fn from_slice(s: &[u8]) -> Self {
729 pub(crate) fn to_slice(&self) -> &[u8] {
730 if self.datalen == 0 { return &[]; }
731 unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
733 pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
734 let sl = self.to_slice();
737 pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
738 Self::from_slice(v.as_slice())
741 pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
742 let mut res = Vec::new();
743 r.read_to_end(&mut res).unwrap();
744 derived::CVec_u8Z::from(res)
748 #[derive(Copy, Clone)]
749 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
750 /// look up the corresponding function in rust-lightning's docs.
751 pub struct ThirtyTwoBytes {
752 /// The thirty-two bytes
757 /// A 3-byte byte array.
758 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
761 /// A 4-byte byte array.
762 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
765 /// A 12-byte byte array.
766 pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
769 /// A 16-byte byte array.
770 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
773 /// A 20-byte byte array.
774 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
779 pub struct ThirtyTwoU16s { /** The thirty-two 16-bit integers */ pub data: [u16; 32], }
781 pub(crate) struct VecWriter(pub Vec<u8>);
782 impl lightning::util::ser::Writer for VecWriter {
783 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
784 self.0.extend_from_slice(buf);
788 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
789 let mut out = VecWriter(Vec::new());
790 i.write(&mut out).unwrap();
791 derived::CVec_u8Z::from(out.0)
793 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
794 I::read(&mut s.to_slice())
796 pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
797 I::read(&mut s.to_slice())
799 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
800 I::read(&mut s.to_slice(), args)
804 /// A Rust str object, ie a reference to a UTF8-valid string.
805 /// This is *not* null-terminated so cannot be used directly as a C string!
807 /// A pointer to the string's bytes, in UTF8 encoding
808 pub chars: *const u8,
809 /// The number of bytes (not characters!) pointed to by `chars`
811 /// Whether the data pointed to by `chars` should be freed or not.
812 pub chars_is_owned: bool,
814 impl Into<Str> for &str {
815 fn into(self) -> Str {
816 self.to_owned().into()
819 impl Into<Str> for &mut &str {
820 fn into(self) -> Str {
821 let us: &str = *self;
827 pub(crate) fn into_str(&self) -> &'static str {
828 if self.len == 0 { return ""; }
829 core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
831 pub(crate) fn into_string(mut self) -> String {
832 let bytes = if self.len == 0 {
834 } else if self.chars_is_owned {
836 Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
838 self.chars_is_owned = false;
841 let mut ret = Vec::with_capacity(self.len);
842 ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
845 String::from_utf8(bytes).unwrap()
847 #[cfg(feature = "std")]
848 pub(crate) fn into_pathbuf(mut self) -> std::path::PathBuf {
849 std::path::PathBuf::from(self.into_string())
852 impl Into<Str> for String {
853 fn into(self) -> Str {
854 let s = Box::leak(self.into_boxed_str());
855 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
858 #[cfg(feature = "std")]
859 impl Into<Str> for std::path::PathBuf {
860 fn into(self) -> Str {
861 self.into_os_string().into_string().expect("We expect paths to be UTF-8 valid").into()
865 fn clone(&self) -> Self {
866 String::from(self.into_str()).into()
872 if self.chars_is_owned && self.len != 0 {
873 let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
878 /// Frees the data buffer, if chars_is_owned is set and len > 0.
879 pub extern "C" fn Str_free(_res: Str) { }
881 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
882 // Thus, they must gracefully handle being completely null in _free.
884 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
885 // everywhere in the containers.
888 pub(crate) union CResultPtr<O, E> {
889 pub(crate) result: *mut O,
890 pub(crate) err: *mut E,
893 pub(crate) struct CResultTempl<O, E> {
894 pub(crate) contents: CResultPtr<O, E>,
895 pub(crate) result_ok: bool,
897 impl<O, E> CResultTempl<O, E> {
898 pub(crate) extern "C" fn ok(o: O) -> Self {
900 contents: CResultPtr {
901 result: Box::into_raw(Box::new(o)),
906 pub(crate) extern "C" fn err(e: E) -> Self {
908 contents: CResultPtr {
909 err: Box::into_raw(Box::new(e)),
915 impl<O, E> Drop for CResultTempl<O, E> {
918 if unsafe { !self.contents.result.is_null() } {
919 let _ = unsafe { Box::from_raw(self.contents.result) };
921 } else if unsafe { !self.contents.err.is_null() } {
922 let _ = unsafe { Box::from_raw(self.contents.err) };
927 /// Utility to make it easy to set a pointer to null and get its original value in line.
928 pub(crate) trait TakePointer<T> {
929 fn take_ptr(&mut self) -> T;
931 impl<T> TakePointer<*const T> for *const T {
932 fn take_ptr(&mut self) -> *const T {
934 *self = core::ptr::null();
938 impl<T> TakePointer<*mut T> for *mut T {
939 fn take_ptr(&mut self) -> *mut T {
941 *self = core::ptr::null_mut();
947 pub(crate) mod ObjOps {
948 #[cfg(feature = "no-std")]
949 use alloc::boxed::Box;
952 #[must_use = "returns new dangling pointer"]
953 pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
954 let ptr = Box::into_raw(Box::new(obj));
955 nonnull_ptr_to_inner(ptr)
958 pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
959 if core::mem::size_of::<T>() == 0 {
960 // We map `None::<T>` as `T { inner: null, .. }` which works great for all
961 // non-Zero-Sized-Types `T`.
962 // For ZSTs, we need to differentiate between null implying `None` and null implying
963 // `Some` with no allocation.
964 // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
965 // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
966 // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
967 // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
969 // Note that we add 4095 here as at least the Java client assumes that the low bit on
970 // any heap pointer is 0, which is generally provided by malloc, but which is not true
971 // for ZSTs "allocated" by `Box::new`.
972 debug_assert_eq!(ptr as usize, 1);
973 unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
975 // In order to get better test coverage, also increment non-ZST pointers with
976 // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
977 #[cfg(test_mod_pointers)]
978 unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
979 #[cfg(not(test_mod_pointers))]
980 unsafe { ptr as *mut T }
984 /// Invert nonnull_ptr_to_inner
985 pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
986 if core::mem::size_of::<T>() == 0 {
987 unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
989 #[cfg(test_mod_pointers)]
990 unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
991 #[cfg(not(test_mod_pointers))]
997 #[cfg(test_mod_pointers)]
999 /// This function exists for memory safety testing purposes. It should never be used in production
1001 pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
1002 if ptr as usize == 1 {
1005 unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
1009 pub(crate) struct SmartPtr<T> {
1012 impl<T> SmartPtr<T> {
1013 pub(crate) fn from_obj(o: T) -> Self {
1014 Self { ptr: Box::into_raw(Box::new(o)) }
1016 pub(crate) fn null() -> Self {
1017 Self { ptr: core::ptr::null_mut() }
1020 impl<T> Drop for SmartPtr<T> {
1021 fn drop(&mut self) {
1022 if self.ptr != core::ptr::null_mut() {
1023 let _ = unsafe { Box::from_raw(self.ptr) };
1027 impl<T> core::ops::Deref for SmartPtr<T> {
1028 type Target = *mut T;
1029 fn deref(&self) -> &*mut T {