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 }
296 /// Creates a new BigEndianScalar which has the same data as `orig`
297 pub extern "C" fn BigEndianScalar_clone(orig: &BigEndianScalar) -> BigEndianScalar { orig.clone() }
300 #[derive(Copy, Clone)]
301 /// Represents an error returned from libsecp256k1 during validation of some secp256k1 data
302 pub enum Secp256k1Error {
303 /// Signature failed verification
305 /// Badly sized message ("messages" are actually fixed-sized digests; see the MESSAGE_SIZE constant)
313 /// Bad shared secret.
317 /// Invalid tweak for add_assign or mul_assign
319 /// Didn't pass enough memory to context creation with preallocated memory
321 /// Bad set of public keys.
323 /// The only valid parity values are 0 or 1.
326 impl Secp256k1Error {
327 pub(crate) fn from_rust(err: SecpError) -> Self {
329 SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
330 SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
331 SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
332 SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
333 SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
334 SecpError::InvalidSharedSecret => Secp256k1Error::InvalidSharedSecret,
335 SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
336 SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
337 SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
338 SecpError::InvalidPublicKeySum => Secp256k1Error::InvalidPublicKeySum,
339 SecpError::InvalidParityValue(_) => Secp256k1Error::InvalidParityValue,
342 pub(crate) fn into_rust(self) -> SecpError {
343 let invalid_parity = secp256k1::Parity::from_i32(42).unwrap_err();
345 Secp256k1Error::IncorrectSignature => SecpError::IncorrectSignature,
346 Secp256k1Error::InvalidMessage => SecpError::InvalidMessage,
347 Secp256k1Error::InvalidPublicKey => SecpError::InvalidPublicKey,
348 Secp256k1Error::InvalidSignature => SecpError::InvalidSignature,
349 Secp256k1Error::InvalidSecretKey => SecpError::InvalidSecretKey,
350 Secp256k1Error::InvalidSharedSecret => SecpError::InvalidSharedSecret,
351 Secp256k1Error::InvalidRecoveryId => SecpError::InvalidRecoveryId,
352 Secp256k1Error::InvalidTweak => SecpError::InvalidTweak,
353 Secp256k1Error::NotEnoughMemory => SecpError::NotEnoughMemory,
354 Secp256k1Error::InvalidPublicKeySum => SecpError::InvalidPublicKeySum,
355 Secp256k1Error::InvalidParityValue => SecpError::InvalidParityValue(invalid_parity),
361 #[derive(Copy, Clone)]
362 /// Represents an error returned from the bech32 library during validation of some bech32 data
363 pub enum Bech32Error {
364 /// String does not contain the separator character
366 /// The checksum does not match the rest of the data
368 /// The data or human-readable part is too long or too short
370 /// Some part of the string contains an invalid character
372 /// Some part of the data has an invalid value
374 /// The bit conversion failed due to a padding issue
376 /// The whole string must be of one case
380 pub(crate) fn from_rust(err: bech32::Error) -> Self {
382 bech32::Error::MissingSeparator => Self::MissingSeparator,
383 bech32::Error::InvalidChecksum => Self::InvalidChecksum,
384 bech32::Error::InvalidLength => Self::InvalidLength,
385 bech32::Error::InvalidChar(c) => Self::InvalidChar(c as u32),
386 bech32::Error::InvalidData(d) => Self::InvalidData(d),
387 bech32::Error::InvalidPadding => Self::InvalidPadding,
388 bech32::Error::MixedCase => Self::MixedCase,
391 pub(crate) fn into_rust(self) -> bech32::Error {
393 Self::MissingSeparator => bech32::Error::MissingSeparator,
394 Self::InvalidChecksum => bech32::Error::InvalidChecksum,
395 Self::InvalidLength => bech32::Error::InvalidLength,
396 Self::InvalidChar(c) => bech32::Error::InvalidChar(core::char::from_u32(c).expect("Invalid UTF-8 character in Bech32Error::InvalidChar")),
397 Self::InvalidData(d) => bech32::Error::InvalidData(d),
398 Self::InvalidPadding => bech32::Error::InvalidPadding,
399 Self::MixedCase => bech32::Error::MixedCase,
404 /// Creates a new Bech32Error which has the same data as `orig`
405 pub extern "C" fn Bech32Error_clone(orig: &Bech32Error) -> Bech32Error { orig.clone() }
407 /// Releases any memory held by the given `Bech32Error` (which is currently none)
408 pub extern "C" fn Bech32Error_free(o: Bech32Error) { }
411 #[derive(Clone, Copy, PartialEq)]
412 /// Sub-errors which don't have specific information in them use this type.
414 /// Zero-Sized_types aren't consistent across Rust/C/C++, so we add some size here
419 #[allow(missing_docs)] // If there's no docs upstream, that's good enough for us
420 #[derive(Clone, Copy, PartialEq)]
421 /// Represents an IO Error. Note that some information is lost in the conversion from Rust.
443 pub(crate) fn from_rust_kind(err: io::ErrorKind) -> Self {
445 io::ErrorKind::NotFound => IOError::NotFound,
446 io::ErrorKind::PermissionDenied => IOError::PermissionDenied,
447 io::ErrorKind::ConnectionRefused => IOError::ConnectionRefused,
448 io::ErrorKind::ConnectionReset => IOError::ConnectionReset,
449 io::ErrorKind::ConnectionAborted => IOError::ConnectionAborted,
450 io::ErrorKind::NotConnected => IOError::NotConnected,
451 io::ErrorKind::AddrInUse => IOError::AddrInUse,
452 io::ErrorKind::AddrNotAvailable => IOError::AddrNotAvailable,
453 io::ErrorKind::BrokenPipe => IOError::BrokenPipe,
454 io::ErrorKind::AlreadyExists => IOError::AlreadyExists,
455 io::ErrorKind::WouldBlock => IOError::WouldBlock,
456 io::ErrorKind::InvalidInput => IOError::InvalidInput,
457 io::ErrorKind::InvalidData => IOError::InvalidData,
458 io::ErrorKind::TimedOut => IOError::TimedOut,
459 io::ErrorKind::WriteZero => IOError::WriteZero,
460 io::ErrorKind::Interrupted => IOError::Interrupted,
461 io::ErrorKind::Other => IOError::Other,
462 io::ErrorKind::UnexpectedEof => IOError::UnexpectedEof,
466 pub(crate) fn from_rust(err: io::Error) -> Self {
467 Self::from_rust_kind(err.kind())
469 pub(crate) fn to_rust_kind(&self) -> io::ErrorKind {
471 IOError::NotFound => io::ErrorKind::NotFound,
472 IOError::PermissionDenied => io::ErrorKind::PermissionDenied,
473 IOError::ConnectionRefused => io::ErrorKind::ConnectionRefused,
474 IOError::ConnectionReset => io::ErrorKind::ConnectionReset,
475 IOError::ConnectionAborted => io::ErrorKind::ConnectionAborted,
476 IOError::NotConnected => io::ErrorKind::NotConnected,
477 IOError::AddrInUse => io::ErrorKind::AddrInUse,
478 IOError::AddrNotAvailable => io::ErrorKind::AddrNotAvailable,
479 IOError::BrokenPipe => io::ErrorKind::BrokenPipe,
480 IOError::AlreadyExists => io::ErrorKind::AlreadyExists,
481 IOError::WouldBlock => io::ErrorKind::WouldBlock,
482 IOError::InvalidInput => io::ErrorKind::InvalidInput,
483 IOError::InvalidData => io::ErrorKind::InvalidData,
484 IOError::TimedOut => io::ErrorKind::TimedOut,
485 IOError::WriteZero => io::ErrorKind::WriteZero,
486 IOError::Interrupted => io::ErrorKind::Interrupted,
487 IOError::Other => io::ErrorKind::Other,
488 IOError::UnexpectedEof => io::ErrorKind::UnexpectedEof,
491 pub(crate) fn to_rust(&self) -> io::Error {
492 io::Error::new(self.to_rust_kind(), "")
497 /// A serialized transaction, in (pointer, length) form.
499 /// This type optionally owns its own memory, and thus the semantics around access change based on
500 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
501 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
502 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
503 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
504 /// you would be invalid.
506 /// Note that, while it may change in the future, because transactions on the Rust side are stored
507 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
508 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
509 /// `data_is_owned` either set or unset at your discretion.
510 pub struct Transaction {
511 /// The serialized transaction data.
513 /// This is non-const for your convenience, an object passed to Rust is never written to.
515 /// The length of the serialized transaction
517 /// Whether the data pointed to by `data` should be freed or not.
518 pub data_is_owned: bool,
521 fn from_vec(vec: Vec<u8>) -> Self {
522 let datalen = vec.len();
523 let data = Box::into_raw(vec.into_boxed_slice());
525 data: unsafe { (*data).as_mut_ptr() },
530 pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
531 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
532 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
534 pub(crate) fn from_bitcoin(btc: &BitcoinTransaction) -> Self {
535 let vec = ::bitcoin::consensus::encode::serialize(btc);
539 impl Drop for Transaction {
541 if self.data_is_owned && self.datalen != 0 {
542 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
546 impl Clone for Transaction {
547 fn clone(&self) -> Self {
548 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
549 let mut v = Vec::new();
550 v.extend_from_slice(&sl);
555 /// Frees the data buffer, if data_is_owned is set and datalen > 0.
556 pub extern "C" fn Transaction_free(_res: Transaction) { }
559 /// A serialized witness.
561 /// The serialized transaction data.
563 /// This is non-const for your convenience, an object passed to Rust is never written to.
565 /// The length of the serialized transaction
567 /// Whether the data pointed to by `data` should be freed or not.
568 pub data_is_owned: bool,
571 fn from_vec(vec: Vec<u8>) -> Self {
572 let datalen = vec.len();
573 let data = Box::into_raw(vec.into_boxed_slice());
575 data: unsafe { (*data).as_mut_ptr() },
580 pub(crate) fn into_bitcoin(&self) -> BitcoinWitness {
581 ::bitcoin::consensus::encode::deserialize(unsafe { core::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
583 pub(crate) fn from_bitcoin(btc: &BitcoinWitness) -> Self {
584 let vec = ::bitcoin::consensus::encode::serialize(btc);
589 impl Drop for Witness {
591 if self.data_is_owned && self.datalen != 0 {
592 let _ = derived::CVec_u8Z { data: self.data as *mut u8, datalen: self.datalen };
596 impl Clone for Witness {
597 fn clone(&self) -> Self {
598 let sl = unsafe { core::slice::from_raw_parts(self.data, self.datalen) };
599 let mut v = Vec::new();
600 v.extend_from_slice(&sl);
606 /// Creates a new Witness which has the same data as `orig` but with a new buffer.
607 pub extern "C" fn Witness_clone(orig: &Witness) -> Witness { orig.clone() }
610 /// Frees the data pointed to by data
611 pub extern "C" fn Witness_free(_res: Witness) { }
613 pub(crate) fn bitcoin_to_C_outpoint(outpoint: &::bitcoin::blockdata::transaction::OutPoint) -> crate::lightning::chain::transaction::OutPoint {
614 crate::lightning::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: *outpoint.txid.as_ref() }, outpoint.vout.try_into().unwrap())
616 pub(crate) fn C_to_bitcoin_outpoint(outpoint: crate::lightning::chain::transaction::OutPoint) -> ::bitcoin::blockdata::transaction::OutPoint {
618 ::bitcoin::blockdata::transaction::OutPoint {
619 txid: (*outpoint.inner).txid, vout: (*outpoint.inner).index as u32
626 /// An input to a transaction.
628 /// This contains the witness, the scriptSig and the previous outpoint and represents a single
629 /// input to a transaction
631 /// The witness which includes any signatures required to spend a segwit output.
632 pub witness: Witness,
633 /// The script_sig which includes signatures requires to spend a pre-segwit output (or a
634 /// P2SH-wrapped segwit output).
635 pub script_sig: derived::CVec_u8Z,
636 /// The sequence number of the transaction input
638 /// The txid of the transaction being spent.
639 pub previous_txid: ThirtyTwoBytes,
640 /// The output index of the transaction being spent.
641 pub previous_vout: u32,
645 pub(crate) fn from_rust(txin: &::bitcoin::blockdata::transaction::TxIn) -> Self {
647 witness: Witness::from_bitcoin(&txin.witness),
648 script_sig: derived::CVec_u8Z::from(txin.script_sig.clone().into_bytes()),
649 sequence: txin.sequence.0,
650 previous_txid: ThirtyTwoBytes { data: *txin.previous_output.txid.as_ref() },
651 previous_vout: txin.previous_output.vout,
656 /// Convenience function for constructing a new TxIn
657 pub extern "C" fn TxIn_new(witness: Witness, script_sig: derived::CVec_u8Z, sequence: u32, previous_txid: ThirtyTwoBytes, previous_vout: u32) -> TxIn {
658 TxIn { witness, script_sig, sequence, previous_txid, previous_vout }
661 /// Gets the `witness` in the given `TxIn`.
662 pub extern "C" fn TxIn_get_witness(txin: &TxIn) -> Witness {
666 /// Gets the `script_sig` in the given `TxIn`.
667 pub extern "C" fn TxIn_get_script_sig(txin: &TxIn) -> u8slice {
668 u8slice::from_vec(&txin.script_sig)
671 /// Gets the `sequence` in the given `TxIn`.
672 pub extern "C" fn TxIn_get_sequence(txin: &TxIn) -> u32 {
676 /// Gets the previous outpoint txid in the given `TxIn`.
677 pub extern "C" fn TxIn_get_previous_txid(txin: &TxIn) -> ThirtyTwoBytes {
681 /// Gets the previout outpoint index in the given `TxIn`.
682 pub extern "C" fn TxIn_get_previous_vout(txin: &TxIn) -> u32 {
686 /// Frees the witness and script_sig in a TxIn
687 pub extern "C" fn TxIn_free(_res: TxIn) { }
691 /// A transaction output including a scriptPubKey and value.
692 /// This type *does* own its own memory, so must be free'd appropriately.
694 /// The script_pubkey in this output
695 pub script_pubkey: derived::CVec_u8Z,
696 /// The value, in satoshis, of this output
701 pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
702 ::bitcoin::blockdata::transaction::TxOut {
703 script_pubkey: self.script_pubkey.into_rust().into(),
707 pub(crate) fn from_rust(txout: &::bitcoin::blockdata::transaction::TxOut) -> Self {
709 script_pubkey: derived::CVec_u8Z::from(txout.script_pubkey.clone().into_bytes()),
716 /// Convenience function for constructing a new TxOut
717 pub extern "C" fn TxOut_new(script_pubkey: derived::CVec_u8Z, value: u64) -> TxOut {
718 TxOut { script_pubkey, value }
721 /// Gets the `script_pubkey` in the given `TxOut`.
722 pub extern "C" fn TxOut_get_script_pubkey(txout: &TxOut) -> u8slice {
723 u8slice::from_vec(&txout.script_pubkey)
726 /// Gets the value in the given `TxOut`.
727 pub extern "C" fn TxOut_get_value(txout: &TxOut) -> u64 {
731 /// Frees the data pointed to by script_pubkey.
732 pub extern "C" fn TxOut_free(_res: TxOut) { }
734 /// Creates a new TxOut which has the same data as `orig` but with a new script buffer.
735 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
738 /// A "slice" referencing some byte array. This is simply a length-tagged pointer which does not
739 /// own the memory pointed to by data.
741 /// A pointer to the byte buffer
743 /// The number of bytes pointed to by `data`.
747 pub(crate) fn from_slice(s: &[u8]) -> Self {
753 pub(crate) fn to_slice(&self) -> &[u8] {
754 if self.datalen == 0 { return &[]; }
755 unsafe { core::slice::from_raw_parts(self.data, self.datalen) }
757 pub(crate) fn to_reader<'a>(&'a self) -> Cursor<&'a [u8]> {
758 let sl = self.to_slice();
761 pub(crate) fn from_vec(v: &derived::CVec_u8Z) -> u8slice {
762 Self::from_slice(v.as_slice())
765 pub(crate) fn reader_to_vec<R: Read>(r: &mut R) -> derived::CVec_u8Z {
766 let mut res = Vec::new();
767 r.read_to_end(&mut res).unwrap();
768 derived::CVec_u8Z::from(res)
772 #[derive(Copy, Clone)]
773 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
774 /// look up the corresponding function in rust-lightning's docs.
775 pub struct ThirtyTwoBytes {
776 /// The thirty-two bytes
782 /// A 3-byte byte array.
783 pub struct ThreeBytes { /** The three bytes */ pub data: [u8; 3], }
786 /// A 4-byte byte array.
787 pub struct FourBytes { /** The four bytes */ pub data: [u8; 4], }
790 /// A 12-byte byte array.
791 pub struct TwelveBytes { /** The twelve bytes */ pub data: [u8; 12], }
794 /// A 16-byte byte array.
795 pub struct SixteenBytes { /** The sixteen bytes */ pub data: [u8; 16], }
798 /// A 20-byte byte array.
799 pub struct TwentyBytes { /** The twenty bytes */ pub data: [u8; 20], }
804 pub struct ThirtyTwoU16s { /** The thirty-two 16-bit integers */ pub data: [u16; 32], }
806 pub(crate) struct VecWriter(pub Vec<u8>);
807 impl lightning::util::ser::Writer for VecWriter {
808 fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
809 self.0.extend_from_slice(buf);
813 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
814 let mut out = VecWriter(Vec::new());
815 i.write(&mut out).unwrap();
816 derived::CVec_u8Z::from(out.0)
818 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
819 I::read(&mut s.to_slice())
821 pub(crate) fn maybe_deserialize_obj<I: lightning::util::ser::MaybeReadable>(s: u8slice) -> Result<Option<I>, lightning::ln::msgs::DecodeError> {
822 I::read(&mut s.to_slice())
824 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
825 I::read(&mut s.to_slice(), args)
829 /// A Rust str object, ie a reference to a UTF8-valid string.
830 /// This is *not* null-terminated so cannot be used directly as a C string!
832 /// A pointer to the string's bytes, in UTF8 encoding
833 pub chars: *const u8,
834 /// The number of bytes (not characters!) pointed to by `chars`
836 /// Whether the data pointed to by `chars` should be freed or not.
837 pub chars_is_owned: bool,
839 impl Into<Str> for &str {
840 fn into(self) -> Str {
841 self.to_owned().into()
844 impl Into<Str> for &mut &str {
845 fn into(self) -> Str {
846 let us: &str = *self;
852 pub(crate) fn into_str(&self) -> &'static str {
853 if self.len == 0 { return ""; }
854 core::str::from_utf8(unsafe { core::slice::from_raw_parts(self.chars, self.len) }).unwrap()
856 pub(crate) fn into_string(mut self) -> String {
857 let bytes = if self.len == 0 {
859 } else if self.chars_is_owned {
861 Box::from_raw(core::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
863 self.chars_is_owned = false;
866 let mut ret = Vec::with_capacity(self.len);
867 ret.extend_from_slice(unsafe { core::slice::from_raw_parts(self.chars, self.len) });
870 String::from_utf8(bytes).unwrap()
872 #[cfg(feature = "std")]
873 pub(crate) fn into_pathbuf(mut self) -> std::path::PathBuf {
874 std::path::PathBuf::from(self.into_string())
877 impl Into<Str> for String {
878 fn into(self) -> Str {
879 let s = Box::leak(self.into_boxed_str());
880 Str { chars: s.as_ptr(), len: s.len(), chars_is_owned: true }
883 #[cfg(feature = "std")]
884 impl Into<Str> for std::path::PathBuf {
885 fn into(self) -> Str {
886 self.into_os_string().into_string().expect("We expect paths to be UTF-8 valid").into()
890 fn clone(&self) -> Self {
891 String::from(self.into_str()).into()
897 if self.chars_is_owned && self.len != 0 {
898 let _ = derived::CVec_u8Z { data: self.chars as *mut u8, datalen: self.len };
903 /// Frees the data buffer, if chars_is_owned is set and len > 0.
904 pub extern "C" fn Str_free(_res: Str) { }
906 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
907 // Thus, they must gracefully handle being completely null in _free.
909 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
910 // everywhere in the containers.
913 pub(crate) union CResultPtr<O, E> {
914 pub(crate) result: *mut O,
915 pub(crate) err: *mut E,
918 pub(crate) struct CResultTempl<O, E> {
919 pub(crate) contents: CResultPtr<O, E>,
920 pub(crate) result_ok: bool,
922 impl<O, E> CResultTempl<O, E> {
923 pub(crate) extern "C" fn ok(o: O) -> Self {
925 contents: CResultPtr {
926 result: Box::into_raw(Box::new(o)),
931 pub(crate) extern "C" fn err(e: E) -> Self {
933 contents: CResultPtr {
934 err: Box::into_raw(Box::new(e)),
940 impl<O, E> Drop for CResultTempl<O, E> {
943 if unsafe { !self.contents.result.is_null() } {
944 let _ = unsafe { Box::from_raw(self.contents.result) };
946 } else if unsafe { !self.contents.err.is_null() } {
947 let _ = unsafe { Box::from_raw(self.contents.err) };
952 /// Utility to make it easy to set a pointer to null and get its original value in line.
953 pub(crate) trait TakePointer<T> {
954 fn take_ptr(&mut self) -> T;
956 impl<T> TakePointer<*const T> for *const T {
957 fn take_ptr(&mut self) -> *const T {
959 *self = core::ptr::null();
963 impl<T> TakePointer<*mut T> for *mut T {
964 fn take_ptr(&mut self) -> *mut T {
966 *self = core::ptr::null_mut();
972 pub(crate) mod ObjOps {
973 #[cfg(feature = "no-std")]
974 use alloc::boxed::Box;
977 #[must_use = "returns new dangling pointer"]
978 pub(crate) fn heap_alloc<T>(obj: T) -> *mut T {
979 let ptr = Box::into_raw(Box::new(obj));
980 nonnull_ptr_to_inner(ptr)
983 pub(crate) fn nonnull_ptr_to_inner<T>(ptr: *const T) -> *mut T {
984 if core::mem::size_of::<T>() == 0 {
985 // We map `None::<T>` as `T { inner: null, .. }` which works great for all
986 // non-Zero-Sized-Types `T`.
987 // For ZSTs, we need to differentiate between null implying `None` and null implying
988 // `Some` with no allocation.
989 // Thus, for ZSTs, we add one (usually) page here, which should always be aligned.
990 // Note that this relies on undefined behavior! A pointer to NULL may be valid, but a
991 // pointer to NULL + 4096 is almost certainly not. That said, Rust's existing use of
992 // `(*mut T)1` for the pointer we're adding to is also not defined, so we should be
994 // Note that we add 4095 here as at least the Java client assumes that the low bit on
995 // any heap pointer is 0, which is generally provided by malloc, but which is not true
996 // for ZSTs "allocated" by `Box::new`.
997 debug_assert_eq!(ptr as usize, 1);
998 unsafe { (ptr as *mut T).cast::<u8>().add(4096 - 1).cast::<T>() }
1000 // In order to get better test coverage, also increment non-ZST pointers with
1001 // --cfg=test_mod_pointers, which is set in genbindings.sh for debug builds.
1002 #[cfg(test_mod_pointers)]
1003 unsafe { (ptr as *mut T).cast::<u8>().add(4096).cast::<T>() }
1004 #[cfg(not(test_mod_pointers))]
1005 unsafe { ptr as *mut T }
1009 /// Invert nonnull_ptr_to_inner
1010 pub(crate) fn untweak_ptr<T>(ptr: *mut T) -> *mut T {
1011 if core::mem::size_of::<T>() == 0 {
1012 unsafe { ptr.cast::<u8>().sub(4096 - 1).cast::<T>() }
1014 #[cfg(test_mod_pointers)]
1015 unsafe { ptr.cast::<u8>().sub(4096).cast::<T>() }
1016 #[cfg(not(test_mod_pointers))]
1022 #[cfg(test_mod_pointers)]
1024 /// This function exists for memory safety testing purposes. It should never be used in production
1026 pub extern "C" fn __unmangle_inner_ptr(ptr: *const c_void) -> *const c_void {
1027 if ptr as usize == 1 {
1030 unsafe { ptr.cast::<u8>().sub(4096).cast::<c_void>() }
1034 pub(crate) struct SmartPtr<T> {
1037 impl<T> SmartPtr<T> {
1038 pub(crate) fn from_obj(o: T) -> Self {
1039 Self { ptr: Box::into_raw(Box::new(o)) }
1041 pub(crate) fn null() -> Self {
1042 Self { ptr: core::ptr::null_mut() }
1045 impl<T> Drop for SmartPtr<T> {
1046 fn drop(&mut self) {
1047 if self.ptr != core::ptr::null_mut() {
1048 let _ = unsafe { Box::from_raw(self.ptr) };
1052 impl<T> core::ops::Deref for SmartPtr<T> {
1053 type Target = *mut T;
1054 fn deref(&self) -> &*mut T {