make `ffi::Type::new` functions all unsafe, expand documentation

This commit is contained in:
Andrew Poelstra 2020-11-27 17:49:11 +00:00
parent be9a78f39e
commit 12b0abbcf8
5 changed files with 120 additions and 55 deletions

View File

@ -106,13 +106,32 @@ impl_array_newtype!(PublicKey, c_uchar, 64);
impl_raw_debug!(PublicKey); impl_raw_debug!(PublicKey);
impl PublicKey { impl PublicKey {
/// Create a new (zeroed) public key usable for the FFI interface /// Creates an "uninitialized" FFI public key which is zeroed out
pub fn new() -> PublicKey { PublicKey([0; 64]) } ///
} /// If you pass this to any FFI functions, except as an out-pointer,
/// the result is likely to be an assertation failure and process
/// termination.
pub unsafe fn new() -> Self {
Self::from_array_unchecked([0; 64])
}
impl Default for PublicKey { /// Create a new public key usable for the FFI interface from raw bytes
fn default() -> Self { ///
PublicKey::new() /// Does not check the validity of the underlying representation. If it is
/// invalid the result may be assertation failures (and process aborts) from
/// the underlying library. You should not use this method except with data
/// that you obtained from the FFI interface of the same version of this
/// library.
pub unsafe fn from_array_unchecked(data: [c_uchar; 64]) -> Self {
PublicKey(data)
}
/// Returns the underlying FFI opaque representation of the public key
///
/// You should not use this unless you really know what you are doing. It is
/// essentially only useful for extending the FFI interface itself.
pub fn underlying_bytes(self) -> [c_uchar; 64] {
self.0
} }
} }
@ -129,13 +148,32 @@ impl_array_newtype!(Signature, c_uchar, 64);
impl_raw_debug!(Signature); impl_raw_debug!(Signature);
impl Signature { impl Signature {
/// Create a new (zeroed) signature usable for the FFI interface /// Creates an "uninitialized" FFI signature which is zeroed out
pub fn new() -> Signature { Signature([0; 64]) } ///
} /// If you pass this to any FFI functions, except as an out-pointer,
/// the result is likely to be an assertation failure and process
/// termination.
pub unsafe fn new() -> Self {
Self::from_array_unchecked([0; 64])
}
impl Default for Signature { /// Create a new signature usable for the FFI interface from raw bytes
fn default() -> Self { ///
Signature::new() /// Does not check the validity of the underlying representation. If it is
/// invalid the result may be assertation failures (and process aborts) from
/// the underlying library. You should not use this method except with data
/// that you obtained from the FFI interface of the same version of this
/// library.
pub unsafe fn from_array_unchecked(data: [c_uchar; 64]) -> Self {
Signature(data)
}
/// Returns the underlying FFI opaque representation of the signature
///
/// You should not use this unless you really know what you are doing. It is
/// essentially only useful for extending the FFI interface itself.
pub fn underlying_bytes(self) -> [c_uchar; 64] {
self.0
} }
} }
@ -145,11 +183,33 @@ impl_array_newtype!(XOnlyPublicKey, c_uchar, 64);
impl_raw_debug!(XOnlyPublicKey); impl_raw_debug!(XOnlyPublicKey);
impl XOnlyPublicKey { impl XOnlyPublicKey {
/// Create a new (zeroed) x-only public key usable for the FFI interface /// Creates an "uninitialized" FFI x-only public key which is zeroed out
pub fn new() -> XOnlyPublicKey { XOnlyPublicKey([0; 64]) } ///
pub fn from_array(data: [c_uchar; 64]) -> XOnlyPublicKey { /// If you pass this to any FFI functions, except as an out-pointer,
/// the result is likely to be an assertation failure and process
/// termination.
pub unsafe fn new() -> Self {
Self::from_array_unchecked([0; 64])
}
/// Create a new x-only public key usable for the FFI interface from raw bytes
///
/// Does not check the validity of the underlying representation. If it is
/// invalid the result may be assertation failures (and process aborts) from
/// the underlying library. You should not use this method except with data
/// that you obtained from the FFI interface of the same version of this
/// library.
pub unsafe fn from_array_unchecked(data: [c_uchar; 64]) -> Self {
XOnlyPublicKey(data) XOnlyPublicKey(data)
} }
/// Returns the underlying FFI opaque representation of the x-only public key
///
/// You should not use this unless you really know what you are doing. It is
/// essentially only useful for extending the FFI interface itself.
pub fn underlying_bytes(self) -> [c_uchar; 64] {
self.0
}
} }
impl hash::Hash for XOnlyPublicKey { impl hash::Hash for XOnlyPublicKey {
@ -158,23 +218,39 @@ impl hash::Hash for XOnlyPublicKey {
} }
} }
impl Default for XOnlyPublicKey {
fn default() -> Self {
XOnlyPublicKey::new()
}
}
#[repr(C)] #[repr(C)]
pub struct KeyPair([c_uchar; 96]); pub struct KeyPair([c_uchar; 96]);
impl_array_newtype!(KeyPair, c_uchar, 96); impl_array_newtype!(KeyPair, c_uchar, 96);
impl_raw_debug!(KeyPair); impl_raw_debug!(KeyPair);
impl KeyPair { impl KeyPair {
/// Create a new (zeroed) key pair usable for the FFI interface /// Creates an "uninitialized" FFI keypair which is zeroed out
pub fn new() -> KeyPair { KeyPair([0; 96]) } ///
pub fn from_array(data: [c_uchar; 96]) -> KeyPair { /// If you pass this to any FFI functions, except as an out-pointer,
/// the result is likely to be an assertation failure and process
/// termination.
pub unsafe fn new() -> Self {
Self::from_array_unchecked([0; 96])
}
/// Create a new keypair usable for the FFI interface from raw bytes
///
/// Does not check the validity of the underlying representation. If it is
/// invalid the result may be assertation failures (and process aborts) from
/// the underlying library. You should not use this method except with data
/// that you obtained from the FFI interface of the same version of this
/// library.
pub unsafe fn from_array_unchecked(data: [c_uchar; 96]) -> Self {
KeyPair(data) KeyPair(data)
} }
/// Returns the underlying FFI opaque representation of the x-only public key
///
/// You should not use this unless you really know what you are doing. It is
/// essentially only useful for extending the FFI interface itself.
pub fn underlying_bytes(self) -> [c_uchar; 96] {
self.0
}
} }
impl hash::Hash for KeyPair { impl hash::Hash for KeyPair {
@ -183,12 +259,6 @@ impl hash::Hash for KeyPair {
} }
} }
impl Default for KeyPair {
fn default() -> Self {
KeyPair::new()
}
}
#[cfg(not(feature = "fuzztarget"))] #[cfg(not(feature = "fuzztarget"))]
extern "C" { extern "C" {
/// Default ECDH hash function /// Default ECDH hash function

View File

@ -233,14 +233,14 @@ impl PublicKey {
pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>, pub fn from_secret_key<C: Signing>(secp: &Secp256k1<C>,
sk: &SecretKey) sk: &SecretKey)
-> PublicKey { -> PublicKey {
let mut pk = ffi::PublicKey::new();
unsafe { unsafe {
let mut pk = ffi::PublicKey::new();
// We can assume the return value because it's not possible to construct // We can assume the return value because it's not possible to construct
// an invalid `SecretKey` without transmute trickery or something // an invalid `SecretKey` without transmute trickery or something
let res = ffi::secp256k1_ec_pubkey_create(secp.ctx, &mut pk, sk.as_c_ptr()); let res = ffi::secp256k1_ec_pubkey_create(secp.ctx, &mut pk, sk.as_c_ptr());
debug_assert_eq!(res, 1); debug_assert_eq!(res, 1);
PublicKey(pk)
} }
PublicKey(pk)
} }
/// Creates a public key directly from a slice /// Creates a public key directly from a slice
@ -248,8 +248,8 @@ impl PublicKey {
pub fn from_slice(data: &[u8]) -> Result<PublicKey, Error> { pub fn from_slice(data: &[u8]) -> Result<PublicKey, Error> {
if data.is_empty() {return Err(Error::InvalidPublicKey);} if data.is_empty() {return Err(Error::InvalidPublicKey);}
let mut pk = ffi::PublicKey::new();
unsafe { unsafe {
let mut pk = ffi::PublicKey::new();
if ffi::secp256k1_ec_pubkey_parse( if ffi::secp256k1_ec_pubkey_parse(
ffi::secp256k1_context_no_precomp, ffi::secp256k1_context_no_precomp,
&mut pk, &mut pk,

View File

@ -269,9 +269,8 @@ impl Signature {
pub fn from_der(data: &[u8]) -> Result<Signature, Error> { pub fn from_der(data: &[u8]) -> Result<Signature, Error> {
if data.is_empty() {return Err(Error::InvalidSignature);} if data.is_empty() {return Err(Error::InvalidSignature);}
let mut ret = ffi::Signature::new();
unsafe { unsafe {
let mut ret = ffi::Signature::new();
if ffi::secp256k1_ecdsa_signature_parse_der( if ffi::secp256k1_ecdsa_signature_parse_der(
ffi::secp256k1_context_no_precomp, ffi::secp256k1_context_no_precomp,
&mut ret, &mut ret,
@ -288,12 +287,12 @@ impl Signature {
/// Converts a 64-byte compact-encoded byte slice to a signature /// Converts a 64-byte compact-encoded byte slice to a signature
pub fn from_compact(data: &[u8]) -> Result<Signature, Error> { pub fn from_compact(data: &[u8]) -> Result<Signature, Error> {
let mut ret = ffi::Signature::new();
if data.len() != 64 { if data.len() != 64 {
return Err(Error::InvalidSignature) return Err(Error::InvalidSignature)
} }
unsafe { unsafe {
let mut ret = ffi::Signature::new();
if ffi::secp256k1_ecdsa_signature_parse_compact( if ffi::secp256k1_ecdsa_signature_parse_compact(
ffi::secp256k1_context_no_precomp, ffi::secp256k1_context_no_precomp,
&mut ret, &mut ret,
@ -661,16 +660,15 @@ impl<C: Signing> Secp256k1<C> {
pub fn sign(&self, msg: &Message, sk: &key::SecretKey) pub fn sign(&self, msg: &Message, sk: &key::SecretKey)
-> Signature { -> Signature {
let mut ret = ffi::Signature::new();
unsafe { unsafe {
let mut ret = ffi::Signature::new();
// We can assume the return value because it's not possible to construct // We can assume the return value because it's not possible to construct
// an invalid signature from a valid `Message` and `SecretKey` // an invalid signature from a valid `Message` and `SecretKey`
assert_eq!(ffi::secp256k1_ecdsa_sign(self.ctx, &mut ret, msg.as_c_ptr(), assert_eq!(ffi::secp256k1_ecdsa_sign(self.ctx, &mut ret, msg.as_c_ptr(),
sk.as_c_ptr(), ffi::secp256k1_nonce_function_rfc6979, sk.as_c_ptr(), ffi::secp256k1_nonce_function_rfc6979,
ptr::null()), 1); ptr::null()), 1);
Signature::from(ret)
} }
Signature::from(ret)
} }
/// Generates a random keypair. Convenience function for `key::SecretKey::new` /// Generates a random keypair. Convenience function for `key::SecretKey::new`

View File

@ -112,16 +112,16 @@ impl RecoverableSignature {
/// for verification /// for verification
#[inline] #[inline]
pub fn to_standard(&self) -> Signature { pub fn to_standard(&self) -> Signature {
let mut ret = super_ffi::Signature::new();
unsafe { unsafe {
let mut ret = super_ffi::Signature::new();
let err = ffi::secp256k1_ecdsa_recoverable_signature_convert( let err = ffi::secp256k1_ecdsa_recoverable_signature_convert(
super_ffi::secp256k1_context_no_precomp, super_ffi::secp256k1_context_no_precomp,
&mut ret, &mut ret,
self.as_c_ptr(), self.as_c_ptr(),
); );
assert!(err == 1); assert!(err == 1);
Signature(ret)
} }
Signature(ret)
} }
} }
@ -178,15 +178,14 @@ impl<C: Verification> Secp256k1<C> {
pub fn recover(&self, msg: &Message, sig: &RecoverableSignature) pub fn recover(&self, msg: &Message, sig: &RecoverableSignature)
-> Result<key::PublicKey, Error> { -> Result<key::PublicKey, Error> {
let mut pk = super_ffi::PublicKey::new();
unsafe { unsafe {
let mut pk = super_ffi::PublicKey::new();
if ffi::secp256k1_ecdsa_recover(self.ctx, &mut pk, if ffi::secp256k1_ecdsa_recover(self.ctx, &mut pk,
sig.as_c_ptr(), msg.as_c_ptr()) != 1 { sig.as_c_ptr(), msg.as_c_ptr()) != 1 {
return Err(Error::InvalidSignature); return Err(Error::InvalidSignature);
} }
}; Ok(key::PublicKey::from(pk))
Ok(key::PublicKey::from(pk)) }
} }
} }

View File

@ -123,8 +123,8 @@ impl KeyPair {
return Err(InvalidPublicKey); return Err(InvalidPublicKey);
} }
let mut kp = ffi::KeyPair::new();
unsafe { unsafe {
let mut kp = ffi::KeyPair::new();
if ffi::secp256k1_keypair_create(secp.ctx, &mut kp, data.as_c_ptr()) == 1 { if ffi::secp256k1_keypair_create(secp.ctx, &mut kp, data.as_c_ptr()) == 1 {
Ok(KeyPair(kp)) Ok(KeyPair(kp))
} else { } else {
@ -155,13 +155,13 @@ impl KeyPair {
ret ret
}; };
let mut data = random_32_bytes(); let mut data = random_32_bytes();
let mut keypair = ffi::KeyPair::new();
unsafe { unsafe {
let mut keypair = ffi::KeyPair::new();
while ffi::secp256k1_keypair_create(secp.ctx, &mut keypair, data.as_c_ptr()) == 0 { while ffi::secp256k1_keypair_create(secp.ctx, &mut keypair, data.as_c_ptr()) == 0 {
data = random_32_bytes(); data = random_32_bytes();
} }
KeyPair(keypair)
} }
KeyPair(keypair)
} }
/// Tweak a keypair by adding the given tweak to the secret key and updating the /// Tweak a keypair by adding the given tweak to the secret key and updating the
@ -210,9 +210,9 @@ impl PublicKey {
/// Creates a new Schnorr public key from a Schnorr key pair /// Creates a new Schnorr public key from a Schnorr key pair
#[inline] #[inline]
pub fn from_keypair<C: Signing>(secp: &Secp256k1<C>, keypair: &KeyPair) -> PublicKey { pub fn from_keypair<C: Signing>(secp: &Secp256k1<C>, keypair: &KeyPair) -> PublicKey {
let mut xonly_pk = ffi::XOnlyPublicKey::new();
let mut pk_parity = 0; let mut pk_parity = 0;
unsafe { unsafe {
let mut xonly_pk = ffi::XOnlyPublicKey::new();
let ret = ffi::secp256k1_keypair_xonly_pub( let ret = ffi::secp256k1_keypair_xonly_pub(
secp.ctx, secp.ctx,
&mut xonly_pk, &mut xonly_pk,
@ -220,8 +220,8 @@ impl PublicKey {
keypair.as_ptr(), keypair.as_ptr(),
); );
debug_assert_eq!(ret, 1); debug_assert_eq!(ret, 1);
PublicKey(xonly_pk)
} }
PublicKey(xonly_pk)
} }
/// Creates a Schnorr public key directly from a slice /// Creates a Schnorr public key directly from a slice
@ -231,8 +231,8 @@ impl PublicKey {
return Err(InvalidPublicKey); return Err(InvalidPublicKey);
} }
let mut pk = ffi::XOnlyPublicKey::new();
unsafe { unsafe {
let mut pk = ffi::XOnlyPublicKey::new();
if ffi::secp256k1_xonly_pubkey_parse( if ffi::secp256k1_xonly_pubkey_parse(
ffi::secp256k1_context_no_precomp, ffi::secp256k1_context_no_precomp,
&mut pk, &mut pk,
@ -326,9 +326,8 @@ impl From<ffi::XOnlyPublicKey> for PublicKey {
impl From<::key::PublicKey> for PublicKey { impl From<::key::PublicKey> for PublicKey {
fn from(src: ::key::PublicKey) -> PublicKey { fn from(src: ::key::PublicKey) -> PublicKey {
let mut pk = ffi::XOnlyPublicKey::new();
unsafe { unsafe {
let mut pk = ffi::XOnlyPublicKey::new();
assert_eq!( assert_eq!(
1, 1,
ffi::secp256k1_xonly_pubkey_from_pubkey( ffi::secp256k1_xonly_pubkey_from_pubkey(
@ -338,9 +337,8 @@ impl From<::key::PublicKey> for PublicKey {
src.as_c_ptr(), src.as_c_ptr(),
) )
); );
PublicKey(pk)
} }
PublicKey(pk)
} }
} }