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::key::TweakedPublicKey as BitcoinTweakedPublicKey;
11 use bitcoin::key::XOnlyPublicKey;
12 use bitcoin::hashes::Hash;
13 use bitcoin::secp256k1::PublicKey as SecpPublicKey;
14 use bitcoin::secp256k1::SecretKey as SecpSecretKey;
15 use bitcoin::secp256k1::ecdsa::Signature as ECDSASecpSignature;
16 use bitcoin::secp256k1::schnorr::Signature as SchnorrSecpSignature;
17 use bitcoin::secp256k1::Error as SecpError;
18 use bitcoin::secp256k1::ecdsa::RecoveryId;
19 use bitcoin::secp256k1::ecdsa::RecoverableSignature as SecpRecoverableSignature;
20 use bitcoin::secp256k1::Scalar as SecpScalar;
23 use core::convert::TryInto; // Bindings need at least rustc 1.34
24 use alloc::borrow::ToOwned;
25 use core::ffi::c_void;
27 #[cfg(feature = "std")]
28 pub(crate) use std::io::{self, Cursor, Read};
29 #[cfg(feature = "no-std")]
30 pub(crate) use core2::io::{self, Cursor, Read};
31 #[cfg(feature = "no-std")]
32 use alloc::{boxed::Box, vec::Vec, string::String};
34 use core::convert::TryFrom;
37 /// A dummy struct of which an instance must never exist.
38 /// This corresponds to the Rust type `Infallible`, or, in unstable rust, `!`
39 pub struct NotConstructable {
40 _priv_thing: core::convert::Infallible,
42 impl From<core::convert::Infallible> for NotConstructable {
43 fn from(_: core::convert::Infallible) -> Self { unreachable!(); }
46 /// Integer in the range `0..32`
47 #[derive(PartialEq, Eq, Copy, Clone)]
48 #[allow(non_camel_case_types)]
52 impl From<bech32::u5> for U5 {
53 fn from(o: bech32::u5) -> Self { Self(o.to_u8()) }
55 impl Into<bech32::u5> for U5 {
56 fn into(self) -> bech32::u5 { bech32::u5::try_from_u8(self.0).expect("u5 objects must be in the range 0..32") }
59 /// Unsigned, 128-bit integer.
61 /// Because LLVM implements an incorrect ABI for 128-bit integers, a wrapper type is defined here.
62 /// See https://github.com/rust-lang/rust/issues/54341 for more details.
63 #[derive(PartialEq, Eq, Copy, Clone)]
64 #[allow(non_camel_case_types)]
67 /// The 128-bit integer, as 16 little-endian bytes
68 pub le_bytes: [u8; 16],
72 /// Gets the 128-bit integer, as 16 little-endian bytes
73 pub extern "C" fn U128_le_bytes(val: U128) -> SixteenBytes { SixteenBytes { data: val.le_bytes } }
75 /// Constructs a new U128 from 16 little-endian bytes
76 pub extern "C" fn U128_new(le_bytes: SixteenBytes) -> U128 { U128 { le_bytes: le_bytes.data } }
78 impl From<u128> for U128 {
79 fn from(o: u128) -> Self { Self { le_bytes: o.to_le_bytes() } }
81 impl From<&mut u128> for U128 {
82 fn from(o: &mut u128) -> U128 { Self::from(*o) }
84 impl Into<u128> for U128 {
85 fn into(self) -> u128 { u128::from_le_bytes(self.le_bytes) }
88 /// Integer in the range `0..=16`
89 #[derive(PartialEq, Eq, Copy, Clone)]
91 pub struct WitnessVersion(u8);
93 impl From<address::WitnessVersion> for WitnessVersion {
94 fn from(o: address::WitnessVersion) -> Self { Self(o.to_num()) }
96 impl Into<address::WitnessVersion> for WitnessVersion {
97 fn into(self) -> address::WitnessVersion {
98 address::WitnessVersion::try_from(self.0).expect("WitnessVersion objects must be in the range 0..=16")
102 /// A segregated witness version byte and script bytes
105 pub struct WitnessProgram {
106 version: WitnessVersion,
107 program: derived::CVec_u8Z,
109 impl WitnessProgram {
110 pub(crate) fn from_bitcoin(o: BitcoinWitnessProgram) -> Self {
112 version: o.version().into(),
113 program: o.program().as_bytes().to_vec().into(),
116 pub(crate) fn into_bitcoin(mut self) -> BitcoinWitnessProgram {
117 BitcoinWitnessProgram::new(
119 self.program.into_rust(),
120 ).expect("Program length was previously checked")
125 /// Constructs a new WitnessProgram given a version and program bytes.
127 /// The program MUST be at least 2 bytes and no longer than 40 bytes long.
128 /// Further, if the version is 0, the program MUST be either exactly 20 or exactly 32 bytes long.
129 pub extern "C" fn WitnessProgram_new(version: WitnessVersion, program: derived::CVec_u8Z) -> WitnessProgram {
130 assert!(program.datalen >= 2, "WitnessProgram program lengths must be at least 2 bytes long");
131 assert!(program.datalen <= 40, "WitnessProgram program lengths must be no longer than 40 bytes");
133 assert!(program.datalen == 20 || program.datalen == 32, "WitnessProgram program length must be 20 or 32 for version-0 programs");
135 WitnessProgram { version, program }
138 /// Gets the `WitnessVersion` of the given `WitnessProgram`
139 pub extern "C" fn WitnessProgram_get_version(prog: &WitnessProgram) -> WitnessVersion {
143 /// Gets the witness program bytes of the given `WitnessProgram`
144 pub extern "C" fn WitnessProgram_get_program(prog: &WitnessProgram) -> u8slice {
145 u8slice::from_vec(&prog.program)
148 /// Creates a new WitnessProgram which has the same data as `orig`
149 pub extern "C" fn WitnessProgram_clone(orig: &WitnessProgram) -> WitnessProgram { orig.clone() }
151 /// Releases any memory held by the given `WitnessProgram` (which is currently none)
152 pub extern "C" fn WitnessProgram_free(o: WitnessProgram) { }
156 /// Represents a valid secp256k1 public key serialized in "compressed form" as a 33 byte array.
157 pub struct PublicKey {
158 /// The bytes of the public key
159 pub compressed_form: [u8; 33],
162 pub(crate) fn from_rust(pk: &SecpPublicKey) -> Self {
164 compressed_form: pk.serialize(),
167 pub(crate) fn into_rust(&self) -> SecpPublicKey {
168 SecpPublicKey::from_slice(&self.compressed_form).unwrap()
170 pub(crate) fn is_null(&self) -> bool { self.compressed_form[..] == [0; 33][..] }
171 pub(crate) fn null() -> Self { Self { compressed_form: [0; 33] } }
176 /// Represents a tweaked X-only public key as required for BIP 340 (Taproot).
177 pub struct TweakedPublicKey {
178 /// The bytes of the public key X coordinate
179 pub x_coordinate: [u8; 32],
181 impl TweakedPublicKey {
182 pub(crate) fn from_rust(pk: &BitcoinTweakedPublicKey) -> Self {
184 x_coordinate: pk.serialize(),
187 pub(crate) fn into_rust(&self) -> BitcoinTweakedPublicKey {
188 let xonly_key = XOnlyPublicKey::from_slice(&self.x_coordinate).unwrap();
189 BitcoinTweakedPublicKey::dangerous_assume_tweaked(xonly_key)
195 /// Represents a valid secp256k1 secret key serialized as a 32 byte array.
196 pub struct SecretKey {
197 /// The bytes of the secret key
201 // from_rust isn't implemented for a ref since we just return byte array refs directly
202 pub(crate) fn from_rust(sk: SecpSecretKey) -> Self {
203 let mut bytes = [0; 32];
204 bytes.copy_from_slice(&sk[..]);
207 pub(crate) fn into_rust(&self) -> SecpSecretKey {
208 SecpSecretKey::from_slice(&self.bytes).unwrap()
214 /// Represents a secp256k1 ECDSA signature serialized as two 32-byte numbers
215 pub struct ECDSASignature {
216 /// The bytes of the signature in "compact" form
217 pub compact_form: [u8; 64],
219 impl ECDSASignature {
220 pub(crate) fn from_rust(pk: &ECDSASecpSignature) -> Self {
222 compact_form: pk.serialize_compact(),
225 pub(crate) fn into_rust(&self) -> ECDSASecpSignature {
226 ECDSASecpSignature::from_compact(&self.compact_form).unwrap()
232 /// Represents a secp256k1 Schnorr signature serialized as two 32-byte numbers
233 pub struct SchnorrSignature {
234 /// The bytes of the signature as two 32-byte numbers
235 pub compact_form: [u8; 64],
237 impl SchnorrSignature {
238 pub(crate) fn from_rust(pk: &SchnorrSecpSignature) -> Self {
240 compact_form: pk.as_ref().clone(),
243 pub(crate) fn into_rust(&self) -> SchnorrSecpSignature {
244 SchnorrSecpSignature::from_slice(&self.compact_form).unwrap()
250 /// Represents a secp256k1 signature serialized as two 32-byte numbers as well as a tag which
251 /// allows recovering the exact public key which created the signature given the message.
252 pub struct RecoverableSignature {
253 /// The bytes of the signature in "compact" form plus a "Recovery ID" which allows for
255 pub serialized_form: [u8; 68],
257 impl RecoverableSignature {
258 pub(crate) fn from_rust(pk: &SecpRecoverableSignature) -> Self {
259 let (id, compact_form) = pk.serialize_compact();
260 let mut serialized_form = [0; 68];
261 serialized_form[0..64].copy_from_slice(&compact_form[..]);
262 serialized_form[64..].copy_from_slice(&id.to_i32().to_le_bytes());
263 Self { serialized_form }
265 pub(crate) fn into_rust(&self) -> SecpRecoverableSignature {
267 id.copy_from_slice(&self.serialized_form[64..]);
268 SecpRecoverableSignature::from_compact(&self.serialized_form[0..64],
269 RecoveryId::from_i32(i32::from_le_bytes(id)).expect("Invalid Recovery ID"))
276 /// Represents a scalar value between zero and the secp256k1 curve order, in big endian.
277 pub struct BigEndianScalar {
278 /// The bytes of the scalar value.
279 pub big_endian_bytes: [u8; 32],
281 impl BigEndianScalar {
282 pub(crate) fn from_rust(scalar: &SecpScalar) -> Self {
283 Self { big_endian_bytes: scalar.to_be_bytes() }
285 pub(crate) fn into_rust(&self) -> SecpScalar {
286 SecpScalar::from_be_bytes(self.big_endian_bytes).expect("Scalar greater than the curve order")
291 /// Convenience function for constructing a new BigEndianScalar
292 pub extern "C" fn BigEndianScalar_new(big_endian_bytes: ThirtyTwoBytes) -> BigEndianScalar {
293 BigEndianScalar { big_endian_bytes: big_endian_bytes.data }
297 #[derive(Copy, Clone)]
298 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
299 pub enum Secp256k1Error {
300 /// Signature failed verification
302 /// Badly sized message ("messages" are actually fixed-sized digests; see the MESSAGE_SIZE constant)
310 /// Bad shared secret.
314 /// Invalid tweak for add_assign or mul_assign
316 /// Didn't pass enough memory to context creation with preallocated memory
318 /// Bad set of public keys.
320 /// The only valid parity values are 0 or 1.
323 impl Secp256k1Error {
324 pub(crate) fn from_rust(err: SecpError) -> Self {
326 SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
327 SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
328 SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
329 SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
330 SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
331 SecpError::InvalidSharedSecret => Secp256k1Error::InvalidSharedSecret,
332 SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
333 SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
334 SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
335 SecpError::InvalidPublicKeySum => Secp256k1Error::InvalidPublicKeySum,
336 SecpError::InvalidParityValue(_) => Secp256k1Error::InvalidParityValue,
339 pub(crate) fn into_rust(self) -> SecpError {
340 let invalid_parity = secp256k1::Parity::from_i32(42).unwrap_err();
342 Secp256k1Error::IncorrectSignature => SecpError::IncorrectSignature,
343 Secp256k1Error::InvalidMessage => SecpError::InvalidMessage,
344 Secp256k1Error::InvalidPublicKey => SecpError::InvalidPublicKey,
345 Secp256k1Error::InvalidSignature => SecpError::InvalidSignature,
346 Secp256k1Error::InvalidSecretKey => SecpError::InvalidSecretKey,
347 Secp256k1Error::InvalidSharedSecret => SecpError::InvalidSharedSecret,
348 Secp256k1Error::InvalidRecoveryId => SecpError::InvalidRecoveryId,
349 Secp256k1Error::InvalidTweak => SecpError::InvalidTweak,
350 Secp256k1Error::NotEnoughMemory => SecpError::NotEnoughMemory,
351 Secp256k1Error::InvalidPublicKeySum => SecpError::InvalidPublicKeySum,
352 Secp256k1Error::InvalidParityValue => SecpError::InvalidParityValue(invalid_parity),
358 #[derive(Copy, Clone)]
359 /// Represents an error returned from the bech32 library during validation of some bech32 data
360 pub enum Bech32Error {
361 /// String does not contain the separator character
363 /// The checksum does not match the rest of the data
365 /// The data or human-readable part is too long or too short
367 /// Some part of the string contains an invalid character
369 /// Some part of the data has an invalid value
371 /// The bit conversion failed due to a padding issue
373 /// The whole string must be of one case
377 pub(crate) fn from_rust(err: bech32::Error) -> Self {
379 bech32::Error::MissingSeparator => Self::MissingSeparator,
380 bech32::Error::InvalidChecksum => Self::InvalidChecksum,
381 bech32::Error::InvalidLength => Self::InvalidLength,
382 bech32::Error::InvalidChar(c) => Self::InvalidChar(c as u32),
383 bech32::Error::InvalidData(d) => Self::InvalidData(d),
384 bech32::Error::InvalidPadding => Self::InvalidPadding,
385 bech32::Error::MixedCase => Self::MixedCase,
388 pub(crate) fn into_rust(self) -> bech32::Error {
390 Self::MissingSeparator => bech32::Error::MissingSeparator,
391 Self::InvalidChecksum => bech32::Error::InvalidChecksum,
392 Self::InvalidLength => bech32::Error::InvalidLength,
393 Self::InvalidChar(c) => bech32::Error::InvalidChar(core::char::from_u32(c).expect("Invalid UTF-8 character in Bech32Error::InvalidChar")),
394 Self::InvalidData(d) => bech32::Error::InvalidData(d),
395 Self::InvalidPadding => bech32::Error::InvalidPadding,
396 Self::MixedCase => bech32::Error::MixedCase,
401 /// Creates a new Bech32Error which has the same data as `orig`
402 pub extern "C" fn Bech32Error_clone(orig: &Bech32Error) -> Bech32Error { orig.clone() }
404 /// Releases any memory held by the given `Bech32Error` (which is currently none)
405 pub extern "C" fn Bech32Error_free(o: Bech32Error) { }
408 #[derive(Clone, Copy, PartialEq)]
409 /// Sub-errors which don't have specific information in them use this type.
411 /// Zero-Sized_types aren't consistent across Rust/C/C++, so we add some size here
416 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
417 #[derive(Clone, Copy, PartialEq)]
418 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
440 pub(crate) fn from_rust_kind(err: io::ErrorKind) -> Self {
442 io::ErrorKind::NotFound => IOError::NotFound,
443 io::ErrorKind::PermissionDenied => IOError::PermissionDenied,
444 io::ErrorKind::ConnectionRefused => IOError::ConnectionRefused,
445 io::ErrorKind::ConnectionReset => IOError::ConnectionReset,
446 io::ErrorKind::ConnectionAborted => IOError::ConnectionAborted,
447 io::ErrorKind::NotConnected => IOError::NotConnected,
448 io::ErrorKind::AddrInUse => IOError::AddrInUse,
449 io::ErrorKind::AddrNotAvailable => IOError::AddrNotAvailable,
450 io::ErrorKind::BrokenPipe => IOError::BrokenPipe,
451 io::ErrorKind::AlreadyExists => IOError::AlreadyExists,
452 io::ErrorKind::WouldBlock => IOError::WouldBlock,
453 io::ErrorKind::InvalidInput => IOError::InvalidInput,
454 io::ErrorKind::InvalidData => IOError::InvalidData,
455 io::ErrorKind::TimedOut => IOError::TimedOut,
456 io::ErrorKind::WriteZero => IOError::WriteZero,
457 io::ErrorKind::Interrupted => IOError::Interrupted,
458 io::ErrorKind::Other => IOError::Other,
459 io::ErrorKind::UnexpectedEof => IOError::UnexpectedEof,
463 pub(crate) fn from_rust(err: io::Error) -> Self {
464 Self::from_rust_kind(err.kind())
466 pub(crate) fn to_rust_kind(&self) -> io::ErrorKind {
468 IOError::NotFound => io::ErrorKind::NotFound,
469 IOError::PermissionDenied => io::ErrorKind::PermissionDenied,
470 IOError::ConnectionRefused => io::ErrorKind::ConnectionRefused,
471 IOError::ConnectionReset => io::ErrorKind::ConnectionReset,
472 IOError::ConnectionAborted => io::ErrorKind::ConnectionAborted,
473 IOError::NotConnected => io::ErrorKind::NotConnected,
474 IOError::AddrInUse => io::ErrorKind::AddrInUse,
475 IOError::AddrNotAvailable => io::ErrorKind::AddrNotAvailable,
476 IOError::BrokenPipe => io::ErrorKind::BrokenPipe,
477 IOError::AlreadyExists => io::ErrorKind::AlreadyExists,
478 IOError::WouldBlock => io::ErrorKind::WouldBlock,
479 IOError::InvalidInput => io::ErrorKind::InvalidInput,
480 IOError::InvalidData => io::ErrorKind::InvalidData,
481 IOError::TimedOut => io::ErrorKind::TimedOut,
482 IOError::WriteZero => io::ErrorKind::WriteZero,
483 IOError::Interrupted => io::ErrorKind::Interrupted,
484 IOError::Other => io::ErrorKind::Other,
485 IOError::UnexpectedEof => io::ErrorKind::UnexpectedEof,
488 pub(crate) fn to_rust(&self) -> io::Error {
489 io::Error::new(self.to_rust_kind(), "")
494 /// A serialized transaction, in (pointer, length) form.
496 /// This type optionally owns its own memory, and thus the semantics around access change based on
497 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
498 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
499 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
500 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
501 /// you would be invalid.
503 /// Note that, while it may change in the future, because transactions on the Rust side are stored
504 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
505 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
506 /// `data_is_owned` either set or unset at your discretion.
507 pub struct Transaction {
508 /// The serialized transaction data.
510 /// This is non-const for your convenience, an object passed to Rust is never written to.
512 /// The length of the serialized transaction
514 /// Whether the data pointed to by `data` should be freed or not.
515 pub data_is_owned: bool,
518 fn from_vec(vec: Vec<u8>) -> Self {
519 let datalen = vec.len();
520 let data = Box::into_raw(vec.into_boxed_slice());
522 data: unsafe { (*data).as_mut_ptr() },
527 pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
528 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
529 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
531 pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
532 let vec = ::bitcoin::consensus::encode::serialize(btc);
536 impl Drop for Transaction {
538 if self.data_is_owned && self.datalen != 0 {
539 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
543 impl Clone for Transaction {
544 fn clone(&self) -> Self {
545 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
546 let mut v = Vec::new();
547 v.extend_from_slice(&sl);
552 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
553 pub extern "C" fn Transaction_free(_res: Transaction) { }
556 /// A serialized witness.
558 /// The serialized transaction data.
560 /// This is non-const for your convenience, an object passed to Rust is never written to.
562 /// The length of the serialized transaction
564 /// Whether the data pointed to by `data` should be freed or not.
565 pub data_is_owned: bool,
568 fn from_vec(vec: Vec<u8>) -> Self {
569 let datalen = vec.len();
570 let data = Box::into_raw(vec.into_boxed_slice());
572 data: unsafe { (*data).as_mut_ptr() },
577 pub(crate) fn into_bitcoin(&self) -> BitcoinWitness {
578 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
580 pub(crate) fn from_bitcoin(btc: &BitcoinWitness) -> Self {
581 let vec = ::bitcoin::consensus::encode::serialize(btc);
586 impl Drop for Witness {
588 if self.data_is_owned && self.datalen != 0 {
589 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
593 impl Clone for Witness {
594 fn clone(&self) -> Self {
595 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
596 let mut v = Vec::new();
597 v.extend_from_slice(&sl);
603 /// Creates a new Witness which has the same data as `orig` but with a new buffer.
604 pub extern "C" fn Witness_clone(orig: &Witness) -> Witness { orig.clone() }
607 /// Frees the data pointed to by data
608 pub extern "C" fn Witness_free(_res: Witness) { }
610 pub(crate) fn bitcoin_to_C_outpoint(outpoint: &::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
611 crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: *outpoint.txid.as_ref() }, outpoint.vout.try_into().unwrap())
613 pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
615 ::bitcoin::blockdata::transaction::OutPoint {
616 txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
623 /// An input to a transaction.
625 /// This contains the witness, the scriptSig and the previous outpoint and represents a single
626 /// input to a transaction
628 /// The witness which includes any signatures required to spend a segwit output.
629 pub witness: Witness,
630 /// The script_sig which includes signatures requires to spend a pre-segwit output (or a
631 /// P2SH-wrapped segwit output).
632 pub script_sig: derived::CVec_u8Z,
633 /// The sequence number of the transaction input
635 /// The txid of the transaction being spent.
636 pub previous_txid: ThirtyTwoBytes,
637 /// The output index of the transaction being spent.
638 pub previous_vout: u32,
642 pub(crate) fn from_rust(txin: &::bitcoin::blockdata::transaction::TxIn) -> Self {
644 witness: Witness::from_bitcoin(&txin.witness),
645 script_sig: derived::CVec_u8Z::from(txin.script_sig.clone().into_bytes()),
646 sequence: txin.sequence.0,
647 previous_txid: ThirtyTwoBytes { data: *txin.previous_output.txid.as_ref() },
648 previous_vout: txin.previous_output.vout,
653 /// Convenience function for constructing a new TxIn
654 pub extern "C" fn TxIn_new(witness: Witness, script_sig: derived::CVec_u8Z, sequence: u32, previous_txid: ThirtyTwoBytes, previous_vout: u32) -> TxIn {
655 TxIn { witness, script_sig, sequence, previous_txid, previous_vout }
658 /// Gets the `witness` in the given `TxIn`.
659 pub extern "C" fn TxIn_get_witness(txin: &TxIn) -> Witness {
663 /// Gets the `script_sig` in the given `TxIn`.
664 pub extern "C" fn TxIn_get_script_sig(txin: &TxIn) -> u8slice {
665 u8slice::from_vec(&txin.script_sig)
668 /// Gets the `sequence` in the given `TxIn`.
669 pub extern "C" fn TxIn_get_sequence(txin: &TxIn) -> u32 {
673 /// Gets the previous outpoint txid in the given `TxIn`.
674 pub extern "C" fn TxIn_get_previous_txid(txin: &TxIn) -> ThirtyTwoBytes {
678 /// Gets the previout outpoint index in the given `TxIn`.
679 pub extern "C" fn TxIn_get_previous_vout(txin: &TxIn) -> u32 {
683 /// Frees the witness and script_sig in a TxIn
684 pub extern "C" fn TxIn_free(_res: TxIn) { }
688 /// A transaction output including a scriptPubKey and value.
689 /// This type *does* own its own memory, so must be free'd appropriately.
691 /// The script_pubkey in this output
692 pub script_pubkey: derived::CVec_u8Z,
693 /// The value, in satoshis, of this output
698 pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
699 ::bitcoin::blockdata::transaction::TxOut {
700 script_pubkey: self.script_pubkey.into_rust().into(),
704 pub(crate) fn from_rust(txout: &::bitcoin::blockdata::transaction::TxOut) -> Self {
706 script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.clone().into_bytes()),
713 /// Convenience function for constructing a new TxOut
714 pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
715 TxOut { script_pubkey, value }
718 /// Gets the `script_pubkey` in the given `TxOut`.
719 pub extern "C" fn TxOut_get_script_pubkey(txout: &TxOut) -> u8slice {
720 u8slice::from_vec(&txout.script_pubkey)
723 /// Gets the value in the given `TxOut`.
724 pub extern "C" fn TxOut_get_value(txout: &TxOut) -> u64 {
728 /// Frees the data pointed to by script_pubkey.
729 pub extern "C" fn TxOut_free(_res: TxOut) { }
731 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
732 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
735 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
736 /// own the memory pointed to by data.
738 /// A pointer to the byte buffer
740 /// The number of bytes pointed to by `data`.
744 pub(crate) fn from_slice(s: &[u8]) -> Self {
750 pub(crate) fn to_slice(&self) -> &[u8] {
751 if self.datalen == 0 { return &[]; }
752 unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
754 pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
755 let sl = self.to_slice();
758 pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
759 Self::from_slice(v.as_slice())
762 pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
763 let mut res = Vec::new();
764 r.read_to_end(&mut res).unwrap();
765 derived::CVec_u8Z::from(res)
769 #[derive(Copy, Clone)]
770 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
771 /// look up the corresponding function in rust-lightning's docs.
772 pub struct ThirtyTwoBytes {
773 /// The thirty-two bytes
779 /// A 3-byte byte array.
780 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
783 /// A 4-byte byte array.
784 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
787 /// A 12-byte byte array.
788 pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
791 /// A 16-byte byte array.
792 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
795 /// A 20-byte byte array.
796 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
801 pub struct ThirtyTwoU16s { /** The thirty-two 16-bit integers */ pub data: [u16; 32], }
803 pub(crate) struct VecWriter(pub Vec<u8>);
804 impl lightning::util::ser::Writer for VecWriter {
805 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
806 self.0.extend_from_slice(buf);
810 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
811 let mut out = VecWriter(Vec::new());
812 i.write(&mut out).unwrap();
813 derived::CVec_u8Z::from(out.0)
815 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
816 I::read(&mut s.to_slice())
818 pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
819 I::read(&mut s.to_slice())
821 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
822 I::read(&mut s.to_slice(), args)
826 /// A Rust str object, ie a reference to a UTF8-valid string.
827 /// This is *not* null-terminated so cannot be used directly as a C string!
829 /// A pointer to the string's bytes, in UTF8 encoding
830 pub chars: *const u8,
831 /// The number of bytes (not characters!) pointed to by `chars`
833 /// Whether the data pointed to by `chars` should be freed or not.
834 pub chars_is_owned: bool,
836 impl Into<Str> for &str {
837 fn into(self) -> Str {
838 self.to_owned().into()
841 impl Into<Str> for &mut &str {
842 fn into(self) -> Str {
843 let us: &str = *self;
849 pub(crate) fn into_str(&self) -> &'static str {
850 if self.len == 0 { return ""; }
851 core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
853 pub(crate) fn into_string(mut self) -> String {
854 let bytes = if self.len == 0 {
856 } else if self.chars_is_owned {
858 Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
860 self.chars_is_owned = false;
863 let mut ret = Vec::with_capacity(self.len);
864 ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
867 String::from_utf8(bytes).unwrap()
869 #[cfg(feature = "std")]
870 pub(crate) fn into_pathbuf(mut self) -> std::path::PathBuf {
871 std::path::PathBuf::from(self.into_string())
874 impl Into<Str> for String {
875 fn into(self) -> Str {
876 let s = Box::leak(self.into_boxed_str());
877 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
880 #[cfg(feature = "std")]
881 impl Into<Str> for std::path::PathBuf {
882 fn into(self) -> Str {
883 self.into_os_string().into_string().expect("We expect paths to be UTF-8 valid").into()
887 fn clone(&self) -> Self {
888 String::from(self.into_str()).into()
894 if self.chars_is_owned && self.len != 0 {
895 let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
900 /// Frees the data buffer, if chars_is_owned is set and len > 0.
901 pub extern "C" fn Str_free(_res: Str) { }
903 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
904 // Thus, they must gracefully handle being completely null in _free.
906 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
907 // everywhere in the containers.
910 pub(crate) union CResultPtr<O, E> {
911 pub(crate) result: *mut O,
912 pub(crate) err: *mut E,
915 pub(crate) struct CResultTempl<O, E> {
916 pub(crate) contents: CResultPtr<O, E>,
917 pub(crate) result_ok: bool,
919 impl<O, E> CResultTempl<O, E> {
920 pub(crate) extern "C" fn ok(o: O) -> Self {
922 contents: CResultPtr {
923 result: Box::into_raw(Box::new(o)),
928 pub(crate) extern "C" fn err(e: E) -> Self {
930 contents: CResultPtr {
931 err: Box::into_raw(Box::new(e)),
937 impl<O, E> Drop for CResultTempl<O, E> {
940 if unsafe { !self.contents.result.is_null() } {
941 let _ = unsafe { Box::from_raw(self.contents.result) };
943 } else if unsafe { !self.contents.err.is_null() } {
944 let _ = unsafe { Box::from_raw(self.contents.err) };
949 /// Utility to make it easy to set a pointer to null and get its original value in line.
950 pub(crate) trait TakePointer<T> {
951 fn take_ptr(&mut self) -> T;
953 impl<T> TakePointer<*const T> for *const T {
954 fn take_ptr(&mut self) -> *const T {
956 *self = core::ptr::null();
960 impl<T> TakePointer<*mut T> for *mut T {
961 fn take_ptr(&mut self) -> *mut T {
963 *self = core::ptr::null_mut();
969 pub(crate) mod ObjOps {
970 #[cfg(feature = "no-std")]
971 use alloc::boxed::Box;
974 #[must_use = "returns new dangling pointer"]
975 pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
976 let ptr = Box::into_raw(Box::new(obj));
977 nonnull_ptr_to_inner(ptr)
980 pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
981 if core::mem::size_of::<T>() == 0 {
982 // We map `None::<T>` as `T { inner: null, .. }` which works great for all
983 // non-Zero-Sized-Types `T`.
984 // For ZSTs, we need to differentiate between null implying `None` and null implying
985 // `Some` with no allocation.
986 // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
987 // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
988 // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
989 // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
991 // Note that we add 4095 here as at least the Java client assumes that the low bit on
992 // any heap pointer is 0, which is generally provided by malloc, but which is not true
993 // for ZSTs "allocated" by `Box::new`.
994 debug_assert_eq!(ptr as usize, 1);
995 unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
997 // In order to get better test coverage, also increment non-ZST pointers with
998 // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
999 #[cfg(test_mod_pointers)]
1000 unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
1001 #[cfg(not(test_mod_pointers))]
1002 unsafe { ptr as *mut T }
1006 /// Invert nonnull_ptr_to_inner
1007 pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
1008 if core::mem::size_of::<T>() == 0 {
1009 unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
1011 #[cfg(test_mod_pointers)]
1012 unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
1013 #[cfg(not(test_mod_pointers))]
1019 #[cfg(test_mod_pointers)]
1021 /// This function exists for memory safety testing purposes. It should never be used in production
1023 pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
1024 if ptr as usize == 1 {
1027 unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
1031 pub(crate) struct SmartPtr<T> {
1034 impl<T> SmartPtr<T> {
1035 pub(crate) fn from_obj(o: T) -> Self {
1036 Self { ptr: Box::into_raw(Box::new(o)) }
1038 pub(crate) fn null() -> Self {
1039 Self { ptr: core::ptr::null_mut() }
1042 impl<T> Drop for SmartPtr<T> {
1043 fn drop(&mut self) {
1044 if self.ptr != core::ptr::null_mut() {
1045 let _ = unsafe { Box::from_raw(self.ptr) };
1049 impl<T> core::ops::Deref for SmartPtr<T> {
1050 type Target = *mut T;
1051 fn deref(&self) -> &*mut T {