3 use bitcoin::Script as BitcoinScript;
4 use bitcoin::Transaction as BitcoinTransaction;
5 use bitcoin::hashes::Hash;
6 use bitcoin::secp256k1::key::PublicKey as SecpPublicKey;
7 use bitcoin::secp256k1::key::SecretKey as SecpSecretKey;
8 use bitcoin::secp256k1::Signature as SecpSignature;
9 use bitcoin::secp256k1::Error as SecpError;
11 use std::convert::TryInto; // Bindings need at least rustc 1.34
15 pub struct PublicKey {
16 pub compressed_form: [u8; 33],
19 pub(crate) fn from_rust(pk: &SecpPublicKey) -> Self {
21 compressed_form: pk.serialize(),
24 pub(crate) fn into_rust(&self) -> SecpPublicKey {
25 SecpPublicKey::from_slice(&self.compressed_form).unwrap()
27 pub(crate) fn is_null(&self) -> bool { self.compressed_form[..] == [0; 33][..] }
28 pub(crate) fn null() -> Self { Self { compressed_form: [0; 33] } }
32 pub struct SecretKey {
36 // from_rust isn't implemented for a ref since we just return byte array refs directly
37 pub(crate) fn from_rust(sk: SecpSecretKey) -> Self {
38 let mut bytes = [0; 32];
39 bytes.copy_from_slice(&sk[..]);
42 pub(crate) fn into_rust(&self) -> SecpSecretKey {
43 SecpSecretKey::from_slice(&self.bytes).unwrap()
49 pub struct Signature {
50 pub compact_form: [u8; 64],
53 pub(crate) fn from_rust(pk: &SecpSignature) -> Self {
55 compact_form: pk.serialize_compact(),
58 pub(crate) fn into_rust(&self) -> SecpSignature {
59 SecpSignature::from_compact(&self.compact_form).unwrap()
61 // The following are used for Option<Signature> which we support, but don't use anymore
62 #[allow(unused)] pub(crate) fn is_null(&self) -> bool { self.compact_form[..] == [0; 64][..] }
63 #[allow(unused)] pub(crate) fn null() -> Self { Self { compact_form: [0; 64] } }
67 pub enum Secp256k1Error {
79 pub(crate) fn from_rust(err: SecpError) -> Self {
81 SecpError::IncorrectSignature => Secp256k1Error::IncorrectSignature,
82 SecpError::InvalidMessage => Secp256k1Error::InvalidMessage,
83 SecpError::InvalidPublicKey => Secp256k1Error::InvalidPublicKey,
84 SecpError::InvalidSignature => Secp256k1Error::InvalidSignature,
85 SecpError::InvalidSecretKey => Secp256k1Error::InvalidSecretKey,
86 SecpError::InvalidRecoveryId => Secp256k1Error::InvalidRecoveryId,
87 SecpError::InvalidTweak => Secp256k1Error::InvalidTweak,
88 SecpError::NotEnoughMemory => Secp256k1Error::NotEnoughMemory,
94 /// A serialized transaction, in (pointer, length) form.
96 /// This type optionally owns its own memory, and thus the semantics around access change based on
97 /// the `data_is_owned` flag. If `data_is_owned` is set, you must call `Transaction_free` to free
98 /// the underlying buffer before the object goes out of scope. If `data_is_owned` is not set, any
99 /// access to the buffer after the scope in which the object was provided to you is invalid. eg,
100 /// access after you return from the call in which a `!data_is_owned` `Transaction` is provided to
101 /// you would be invalid.
103 /// Note that, while it may change in the future, because transactions on the Rust side are stored
104 /// in a deserialized form, all `Transaction`s generated on the Rust side will have `data_is_owned`
105 /// set. Similarly, while it may change in the future, all `Transaction`s you pass to Rust may have
106 /// `data_is_owned` either set or unset at your discretion.
107 pub struct Transaction {
108 /// This is non-const for your convenience, an object passed to Rust is never written to.
111 pub data_is_owned: bool,
114 pub(crate) fn into_bitcoin(&self) -> BitcoinTransaction {
115 if self.datalen == 0 { panic!("0-length buffer can never represent a valid Transaction"); }
116 ::bitcoin::consensus::encode::deserialize(unsafe { std::slice::from_raw_parts(self.data, self.datalen) }).unwrap()
118 pub(crate) fn from_vec(v: Vec<u8>) -> Self {
119 let datalen = v.len();
120 let data = Box::into_raw(v.into_boxed_slice());
122 data: unsafe { (*data).as_mut_ptr() },
128 impl Drop for Transaction {
130 if self.data_is_owned && self.datalen != 0 {
131 let _ = CVecTempl { data: self.data as *mut u8, datalen: self.datalen };
136 pub extern "C" fn Transaction_free(_res: Transaction) { }
138 pub(crate) fn bitcoin_to_C_outpoint(outpoint: ::bitcoin::blockdata::transaction::OutPoint) -> crate::chain::transaction::OutPoint {
139 crate::chain::transaction::OutPoint_new(ThirtyTwoBytes { data: outpoint.txid.into_inner() }, outpoint.vout.try_into().unwrap())
144 /// A transaction output including a scriptPubKey and value.
145 /// This type *does* own its own memory, so must be free'd appropriately.
147 pub script_pubkey: derived::CVec_u8Z,
152 pub(crate) fn into_rust(mut self) -> ::bitcoin::blockdata::transaction::TxOut {
153 ::bitcoin::blockdata::transaction::TxOut {
154 script_pubkey: self.script_pubkey.into_rust().into(),
158 pub(crate) fn from_rust(txout: ::bitcoin::blockdata::transaction::TxOut) -> Self {
160 script_pubkey: CVecTempl::from(txout.script_pubkey.into_bytes()),
166 pub extern "C" fn TxOut_free(_res: TxOut) { }
168 pub extern "C" fn TxOut_clone(orig: &TxOut) -> TxOut { orig.clone() }
176 pub(crate) fn from_slice(s: &[u8]) -> Self {
182 pub(crate) fn to_slice(&self) -> &[u8] {
183 if self.datalen == 0 { return &[]; }
184 unsafe { std::slice::from_raw_parts(self.data, self.datalen) }
189 #[derive(Copy, Clone)]
190 /// Arbitrary 32 bytes, which could represent one of a few different things. You probably want to
191 /// look up the corresponding function in rust-lightning's docs.
192 pub struct ThirtyTwoBytes {
195 impl ThirtyTwoBytes {
196 pub(crate) fn null() -> Self {
197 Self { data: [0; 32] }
202 pub struct ThreeBytes { pub data: [u8; 3], }
205 pub struct FourBytes { pub data: [u8; 4], }
208 pub struct TenBytes { pub data: [u8; 10], }
211 pub struct SixteenBytes { pub data: [u8; 16], }
213 pub(crate) struct VecWriter(pub Vec<u8>);
214 impl lightning::util::ser::Writer for VecWriter {
215 fn write_all(&mut self, buf: &[u8]) -> Result<(), ::std::io::Error> {
216 self.0.extend_from_slice(buf);
219 fn size_hint(&mut self, size: usize) {
220 self.0.reserve_exact(size);
223 pub(crate) fn serialize_obj<I: lightning::util::ser::Writeable>(i: &I) -> derived::CVec_u8Z {
224 let mut out = VecWriter(Vec::new());
225 i.write(&mut out).unwrap();
226 CVecTempl::from(out.0)
228 pub(crate) fn deserialize_obj<I: lightning::util::ser::Readable>(s: u8slice) -> Result<I, lightning::ln::msgs::DecodeError> {
229 I::read(&mut s.to_slice())
231 pub(crate) fn deserialize_obj_arg<A, I: lightning::util::ser::ReadableArgs<A>>(s: u8slice, args: A) -> Result<I, lightning::ln::msgs::DecodeError> {
232 I::read(&mut s.to_slice(), args)
236 #[derive(Copy, Clone)]
237 /// A Rust str object, ie a reference to a UTF8-valid string.
238 /// This is *not* null-terminated so cannot be used directly as a C string!
240 pub chars: *const u8,
243 impl Into<Str> for &'static str {
244 fn into(self) -> Str {
245 Str { chars: self.as_ptr(), len: self.len() }
248 impl Into<&'static str> for Str {
249 fn into(self) -> &'static str {
250 if self.len == 0 { return ""; }
251 std::str::from_utf8(unsafe { std::slice::from_raw_parts(self.chars, self.len) }).unwrap()
255 // Note that the C++ headers memset(0) all the Templ types to avoid deallocation!
256 // Thus, they must gracefully handle being completely null in _free.
258 // TODO: Integer/bool primitives should avoid the pointer indirection for underlying types
259 // everywhere in the containers.
262 pub(crate) union CResultPtr<O, E> {
263 pub(crate) result: *mut O,
264 pub(crate) err: *mut E,
267 pub(crate) struct CResultTempl<O, E> {
268 pub(crate) contents: CResultPtr<O, E>,
269 pub(crate) result_ok: bool,
271 impl<O, E> CResultTempl<O, E> {
272 pub(crate) extern "C" fn ok(o: O) -> Self {
274 contents: CResultPtr {
275 result: Box::into_raw(Box::new(o)),
280 pub(crate) extern "C" fn err(e: E) -> Self {
282 contents: CResultPtr {
283 err: Box::into_raw(Box::new(e)),
289 impl<O, E> Drop for CResultTempl<O, E> {
292 if unsafe { !self.contents.result.is_null() } {
293 unsafe { Box::from_raw(self.contents.result) };
295 } else if unsafe { !self.contents.err.is_null() } {
296 unsafe { Box::from_raw(self.contents.err) };
302 pub struct CVecTempl<T> {
306 impl<T> CVecTempl<T> {
307 pub(crate) fn into_rust(&mut self) -> Vec<T> {
308 if self.datalen == 0 { return Vec::new(); }
309 let ret = unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) }.into();
310 self.data = std::ptr::null_mut();
314 pub(crate) fn as_slice(&self) -> &[T] {
315 unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) }
318 impl<T> From<Vec<T>> for CVecTempl<T> {
319 fn from(v: Vec<T>) -> Self {
320 let datalen = v.len();
321 let data = Box::into_raw(v.into_boxed_slice());
322 CVecTempl { datalen, data: unsafe { (*data).as_mut_ptr() } }
325 pub extern "C" fn CVecTempl_free<T>(_res: CVecTempl<T>) { }
326 impl<T> Drop for CVecTempl<T> {
328 if self.datalen == 0 { return; }
329 unsafe { Box::from_raw(std::slice::from_raw_parts_mut(self.data, self.datalen)) };
332 impl<T: Clone> Clone for CVecTempl<T> {
333 fn clone(&self) -> Self {
334 let mut res = Vec::new();
335 if self.datalen == 0 { return Self::from(res); }
336 res.extend_from_slice(unsafe { std::slice::from_raw_parts_mut(self.data, self.datalen) });
342 pub struct C2TupleTempl<A, B> {
346 impl<A, B> From<(A, B)> for C2TupleTempl<A, B> {
347 fn from(tup: (A, B)) -> Self {
354 impl<A, B> C2TupleTempl<A, B> {
355 pub(crate) fn to_rust(mut self) -> (A, B) {
359 pub extern "C" fn C2TupleTempl_free<A, B>(_res: C2TupleTempl<A, B>) { }
360 impl <A: Clone, B: Clone> Clone for C2TupleTempl<A, B> {
361 fn clone(&self) -> Self {
370 pub struct C3TupleTempl<A, B, C> {
375 impl<A, B, C> From<(A, B, C)> for C3TupleTempl<A, B, C> {
376 fn from(tup: (A, B, C)) -> Self {
384 impl<A, B, C> C3TupleTempl<A, B, C> {
385 pub(crate) fn to_rust(mut self) -> (A, B, C) {
386 (self.a, self.b, self.c)
389 pub extern "C" fn C3TupleTempl_free<A, B, C>(_res: C3TupleTempl<A, B, C>) { }
391 /// Utility to make it easy to set a pointer to null and get its original value in line.
392 pub(crate) trait TakePointer<T> {
393 fn take_ptr(&mut self) -> T;
395 impl<T> TakePointer<*const T> for *const T {
396 fn take_ptr(&mut self) -> *const T {
398 *self = std::ptr::null();
402 impl<T> TakePointer<*mut T> for *mut T {
403 fn take_ptr(&mut self) -> *mut T {
405 *self = std::ptr::null_mut();