Merge rust-bitcoin/rust-secp256k1#340: Improve documentation

c73eb2f391 Use 'extra' instead of 'cheap' (Tobin Harding)
c79eb976ca Remove unnecessary explanation (Tobin Harding)
f95e91a6da Use isn't instead of shouldn't (Tobin Harding)
c9e6ca1680 Use rust-bitcoin module doc style (Tobin Harding)
3fa6762437 Add link to referenced commit (Tobin Harding)
f5e68f3ba7 Add ticks around code snippet (Tobin Harding)
d25431c1da Use 3rd person tense for function docs (Tobin Harding)
c3be285c1d Fix size constant docs (Tobin Harding)
5e07e7596b Add period to sentences (Tobin Harding)
269bde042f Remove unnecessary capitalisation (Tobin Harding)

Pull request description:

  In a continued effort to find my feet around here, and inspired by issue #128 I've done a codebase wide audit of the docs (primarily just rustdocs but I glanced at `//` docs as well). Each change is in a separate commit so can be removed if resistance is met. (_"resistance is futile"_).

  I've based the stylistic decisions on [work done](https://github.com/rust-bitcoin/rust-bitcoin/pull/704) in rust-bitcoin.

  I believe the only controversial change is the last (commit: da161c9 Use rust-bitcoin module doc style), please review that one carefully.

ACKs for top commit:
  apoelstra:
    ACK c73eb2f391

Tree-SHA512: 5ea215de3fd23ca2a4f25d8f8d59a85a299044fe495269c43b621291ea50c58856fa8544e36cc109b7bdb1a7a59bcab8711f30113572ddce4509d3b06ff0d3b6
This commit is contained in:
Andrew Poelstra 2022-02-10 15:42:22 +00:00
commit df7520e951
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
6 changed files with 67 additions and 72 deletions

View File

@ -13,34 +13,34 @@
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// //
//! # Constants //! Constants related to the API and the underlying curve.
//! Constants related to the API and the underlying curve //!
/// The size (in bytes) of a message /// The size (in bytes) of a message.
pub const MESSAGE_SIZE: usize = 32; pub const MESSAGE_SIZE: usize = 32;
/// The size (in bytes) of a secret key /// The size (in bytes) of a secret key.
pub const SECRET_KEY_SIZE: usize = 32; pub const SECRET_KEY_SIZE: usize = 32;
/// The size (in bytes) of a serialized public key. /// The size (in bytes) of a serialized public key.
pub const PUBLIC_KEY_SIZE: usize = 33; pub const PUBLIC_KEY_SIZE: usize = 33;
/// The size (in bytes) of an serialized uncompressed public key /// The size (in bytes) of an serialized uncompressed public key.
pub const UNCOMPRESSED_PUBLIC_KEY_SIZE: usize = 65; pub const UNCOMPRESSED_PUBLIC_KEY_SIZE: usize = 65;
/// The maximum size of a signature /// The maximum size of a signature.
pub const MAX_SIGNATURE_SIZE: usize = 72; pub const MAX_SIGNATURE_SIZE: usize = 72;
/// The maximum size of a compact signature /// The maximum size of a compact signature.
pub const COMPACT_SIGNATURE_SIZE: usize = 64; pub const COMPACT_SIGNATURE_SIZE: usize = 64;
/// Size of a Schnorr signature /// The size of a Schnorr signature.
pub const SCHNORRSIG_SIGNATURE_SIZE: usize = 64; pub const SCHNORRSIG_SIGNATURE_SIZE: usize = 64;
/// Size of a Schnorr public key /// The size of a Schnorr public key.
pub const SCHNORRSIG_PUBLIC_KEY_SIZE: usize = 32; pub const SCHNORRSIG_PUBLIC_KEY_SIZE: usize = 32;
/// Size of a key pair /// The size of a key pair.
pub const KEY_PAIR_SIZE: usize = 96; pub const KEY_PAIR_SIZE: usize = 96;
/// The Prime for the secp256k1 field element. /// The Prime for the secp256k1 field element.
@ -51,7 +51,7 @@ pub const FIELD_SIZE: [u8; 32] = [
0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2f 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xfc, 0x2f
]; ];
/// The order of the secp256k1 curve /// The order of the secp256k1 curve.
pub const CURVE_ORDER: [u8; 32] = [ pub const CURVE_ORDER: [u8; 32] = [
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xfe,
@ -59,7 +59,7 @@ pub const CURVE_ORDER: [u8; 32] = [
0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41 0xbf, 0xd2, 0x5e, 0x8c, 0xd0, 0x36, 0x41, 0x41
]; ];
/// The X coordinate of the generator /// The X coordinate of the generator.
pub const GENERATOR_X: [u8; 32] = [ pub const GENERATOR_X: [u8; 32] = [
0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, 0xac, 0x79, 0xbe, 0x66, 0x7e, 0xf9, 0xdc, 0xbb, 0xac,
0x55, 0xa0, 0x62, 0x95, 0xce, 0x87, 0x0b, 0x07, 0x55, 0xa0, 0x62, 0x95, 0xce, 0x87, 0x0b, 0x07,
@ -67,7 +67,7 @@ pub const GENERATOR_X: [u8; 32] = [
0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, 0x17, 0x98 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, 0x17, 0x98
]; ];
/// The Y coordinate of the generator /// The Y coordinate of the generator.
pub const GENERATOR_Y: [u8; 32] = [ pub const GENERATOR_Y: [u8; 32] = [
0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65,
0x5d, 0xa4, 0xfb, 0xfc, 0x0e, 0x11, 0x08, 0xa8, 0x5d, 0xa4, 0xfb, 0xfc, 0x0e, 0x11, 0x08, 0xa8,

View File

@ -11,7 +11,7 @@ pub use self::alloc_only::*;
#[cfg(all(feature = "global-context", feature = "std"))] #[cfg(all(feature = "global-context", feature = "std"))]
#[cfg_attr(docsrs, doc(cfg(all(feature = "global-context", feature = "std"))))] #[cfg_attr(docsrs, doc(cfg(all(feature = "global-context", feature = "std"))))]
/// Module implementing a singleton pattern for a global `Secp256k1` context /// Module implementing a singleton pattern for a global `Secp256k1` context.
pub mod global { pub mod global {
#[cfg(feature = "rand-std")] #[cfg(feature = "rand-std")]
use rand; use rand;
@ -20,7 +20,7 @@ pub mod global {
use std::sync::Once; use std::sync::Once;
use {Secp256k1, All}; use {Secp256k1, All};
/// Proxy struct for global `SECP256K1` context /// Proxy struct for global `SECP256K1` context.
#[derive(Debug, Copy, Clone)] #[derive(Debug, Copy, Clone)]
pub struct GlobalContext { pub struct GlobalContext {
__private: (), __private: (),
@ -60,8 +60,8 @@ pub mod global {
} }
/// A trait for all kinds of Context's that lets you define the exact flags and a function to deallocate memory. /// A trait for all kinds of contexts that lets you define the exact flags and a function to
/// It shouldn't be possible to implement this for types outside this crate. /// deallocate memory. It isn't possible to implement this for types outside this crate.
pub unsafe trait Context : private::Sealed { pub unsafe trait Context : private::Sealed {
/// Flags for the ffi. /// Flags for the ffi.
const FLAGS: c_uint; const FLAGS: c_uint;
@ -97,9 +97,6 @@ pub struct AllPreallocated<'buf> {
mod private { mod private {
use super::*; use super::*;
// A trick to prevent users from implementing a trait.
// on one hand this trait is public, on the other it's in a private module
// so it's not visible to anyone besides it's parent (the context module)
pub trait Sealed {} pub trait Sealed {}
impl<'buf> Sealed for AllPreallocated<'buf> {} impl<'buf> Sealed for AllPreallocated<'buf> {}
@ -289,7 +286,7 @@ unsafe impl<'buf> Context for VerifyOnlyPreallocated<'buf> {
const DESCRIPTION: &'static str = "verification only"; const DESCRIPTION: &'static str = "verification only";
unsafe fn deallocate(_ptr: *mut u8, _size: usize) { unsafe fn deallocate(_ptr: *mut u8, _size: usize) {
// Allocated by the user // Allocated by the user.
} }
} }
@ -298,7 +295,7 @@ unsafe impl<'buf> Context for AllPreallocated<'buf> {
const DESCRIPTION: &'static str = "all capabilities"; const DESCRIPTION: &'static str = "all capabilities";
unsafe fn deallocate(_ptr: *mut u8, _size: usize) { unsafe fn deallocate(_ptr: *mut u8, _size: usize) {
// Allocated by the user // Allocated by the user.
} }
} }
@ -328,7 +325,7 @@ impl<'buf> Secp256k1<AllPreallocated<'buf>> {
pub fn preallocated_new(buf: &'buf mut [AlignedType]) -> Result<Secp256k1<AllPreallocated<'buf>>, Error> { pub fn preallocated_new(buf: &'buf mut [AlignedType]) -> Result<Secp256k1<AllPreallocated<'buf>>, Error> {
Secp256k1::preallocated_gen_new(buf) Secp256k1::preallocated_gen_new(buf)
} }
/// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for a context /// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for a context.
pub fn preallocate_size() -> usize { pub fn preallocate_size() -> usize {
Self::preallocate_size_gen() Self::preallocate_size_gen()
} }
@ -354,12 +351,12 @@ impl<'buf> Secp256k1<AllPreallocated<'buf>> {
} }
impl<'buf> Secp256k1<SignOnlyPreallocated<'buf>> { impl<'buf> Secp256k1<SignOnlyPreallocated<'buf>> {
/// Creates a new Secp256k1 context that can only be used for signing /// Creates a new Secp256k1 context that can only be used for signing.
pub fn preallocated_signing_only(buf: &'buf mut [AlignedType]) -> Result<Secp256k1<SignOnlyPreallocated<'buf>>, Error> { pub fn preallocated_signing_only(buf: &'buf mut [AlignedType]) -> Result<Secp256k1<SignOnlyPreallocated<'buf>>, Error> {
Secp256k1::preallocated_gen_new(buf) Secp256k1::preallocated_gen_new(buf)
} }
/// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for the context /// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for the context.
#[inline] #[inline]
pub fn preallocate_signing_size() -> usize { pub fn preallocate_signing_size() -> usize {
Self::preallocate_size_gen() Self::preallocate_size_gen()
@ -374,7 +371,7 @@ impl<'buf> Secp256k1<SignOnlyPreallocated<'buf>> {
/// * The capabilities (All/SignOnly/VerifyOnly) of the context *must* match the flags passed to libsecp256k1 /// * The capabilities (All/SignOnly/VerifyOnly) of the context *must* match the flags passed to libsecp256k1
/// when generating the context. /// when generating the context.
/// * The user must handle the freeing of the context(using the correct functions) by himself. /// * The user must handle the freeing of the context(using the correct functions) by himself.
/// * This list *is not* exhaustive, and any violation may lead to Undefined Behavior., /// * This list *is not* exhaustive, and any violation may lead to Undefined Behavior.
/// ///
pub unsafe fn from_raw_signining_only(raw_ctx: *mut ffi::Context) -> ManuallyDrop<Secp256k1<SignOnlyPreallocated<'buf>>> { pub unsafe fn from_raw_signining_only(raw_ctx: *mut ffi::Context) -> ManuallyDrop<Secp256k1<SignOnlyPreallocated<'buf>>> {
ManuallyDrop::new(Secp256k1 { ManuallyDrop::new(Secp256k1 {
@ -391,7 +388,7 @@ impl<'buf> Secp256k1<VerifyOnlyPreallocated<'buf>> {
Secp256k1::preallocated_gen_new(buf) Secp256k1::preallocated_gen_new(buf)
} }
/// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for the context /// Uses the ffi `secp256k1_context_preallocated_size` to check the memory size needed for the context.
#[inline] #[inline]
pub fn preallocate_verification_size() -> usize { pub fn preallocate_verification_size() -> usize {
Self::preallocate_size_gen() Self::preallocate_size_gen()
@ -406,7 +403,7 @@ impl<'buf> Secp256k1<VerifyOnlyPreallocated<'buf>> {
/// * The capabilities (All/SignOnly/VerifyOnly) of the context *must* match the flags passed to libsecp256k1 /// * The capabilities (All/SignOnly/VerifyOnly) of the context *must* match the flags passed to libsecp256k1
/// when generating the context. /// when generating the context.
/// * The user must handle the freeing of the context(using the correct functions) by himself. /// * The user must handle the freeing of the context(using the correct functions) by himself.
/// * This list *is not* exhaustive, and any violation may lead to Undefined Behavior., /// * This list *is not* exhaustive, and any violation may lead to Undefined Behavior.
/// ///
pub unsafe fn from_raw_verification_only(raw_ctx: *mut ffi::Context) -> ManuallyDrop<Secp256k1<VerifyOnlyPreallocated<'buf>>> { pub unsafe fn from_raw_verification_only(raw_ctx: *mut ffi::Context) -> ManuallyDrop<Secp256k1<VerifyOnlyPreallocated<'buf>>> {
ManuallyDrop::new(Secp256k1 { ManuallyDrop::new(Secp256k1 {

View File

@ -12,8 +12,7 @@
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// //
//! # ECDH //! Support for shared secret computations.
//! Support for shared secret computations
//! //!
use core::ptr; use core::ptr;
@ -54,7 +53,7 @@ impl_from_array_len!(SharedSecret, 256, (16 20 28 32 48 64 96 128 256));
impl SharedSecret { impl SharedSecret {
/// Create an empty SharedSecret /// Creates an empty `SharedSecret`.
pub(crate) fn empty() -> SharedSecret { pub(crate) fn empty() -> SharedSecret {
SharedSecret { SharedSecret {
data: [0u8; 256], data: [0u8; 256],
@ -62,27 +61,27 @@ impl SharedSecret {
} }
} }
/// Get a pointer to the underlying data with the specified capacity. /// Gets a pointer to the underlying data with the specified capacity.
pub(crate) fn get_data_mut_ptr(&mut self) -> *mut u8 { pub(crate) fn get_data_mut_ptr(&mut self) -> *mut u8 {
self.data.as_mut_ptr() self.data.as_mut_ptr()
} }
/// Get the capacity of the underlying data buffer. /// Gets the capacity of the underlying data buffer.
pub fn capacity(&self) -> usize { pub fn capacity(&self) -> usize {
self.data.len() self.data.len()
} }
/// Get the len of the used data. /// Gets the len of the used data.
pub fn len(&self) -> usize { pub fn len(&self) -> usize {
self.len self.len
} }
/// True if the underlying data buffer is empty. /// Returns true if the underlying data buffer is empty.
pub fn is_empty(&self) -> bool { pub fn is_empty(&self) -> bool {
self.data.is_empty() self.data.is_empty()
} }
/// Set the length of the object. /// Sets the length of the object.
pub(crate) fn set_len(&mut self, len: usize) { pub(crate) fn set_len(&mut self, len: usize) {
debug_assert!(len <= self.data.len()); debug_assert!(len <= self.data.len());
self.len = len; self.len = len;
@ -116,7 +115,7 @@ unsafe extern "C" fn c_callback(output: *mut c_uchar, x: *const c_uchar, y: *con
} }
impl SharedSecret { impl SharedSecret {
/// Creates a new shared secret from a pubkey and secret key /// Creates a new shared secret from a pubkey and secret key.
#[inline] #[inline]
pub fn new(point: &PublicKey, scalar: &SecretKey) -> SharedSecret { pub fn new(point: &PublicKey, scalar: &SecretKey) -> SharedSecret {
let mut ss = SharedSecret::empty(); let mut ss = SharedSecret::empty();
@ -138,7 +137,7 @@ impl SharedSecret {
} }
/// Creates a new shared secret from a pubkey and secret key with applied custom hash function /// Creates a new shared secret from a pubkey and secret key with applied custom hash function.
/// The custom hash function must be in the form of `fn(x: [u8;32], y: [u8;32]) -> SharedSecret` /// The custom hash function must be in the form of `fn(x: [u8;32], y: [u8;32]) -> SharedSecret`
/// `SharedSecret` can be easily created via the `From` impl from arrays. /// `SharedSecret` can be easily created via the `From` impl from arrays.
/// # Examples /// # Examples

View File

@ -13,9 +13,9 @@
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// //
//! # Recovery module
//! Provides a signing function that allows recovering the public key from the //! Provides a signing function that allows recovering the public key from the
//! signature. //! signature.
//!
use core::ptr; use core::ptr;
use key; use key;
@ -25,11 +25,11 @@ use ffi::recovery as ffi;
use super::*; use super::*;
use {Verification, Secp256k1, Signing, Message}; use {Verification, Secp256k1, Signing, Message};
/// A tag used for recovering the public key from a compact signature /// A tag used for recovering the public key from a compact signature.
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct RecoveryId(i32); pub struct RecoveryId(i32);
/// An ECDSA signature with a recovery ID for pubkey recovery /// An ECDSA signature with a recovery ID for pubkey recovery.
#[derive(Copy, Clone, PartialEq, Eq, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub struct RecoverableSignature(ffi::RecoverableSignature); pub struct RecoverableSignature(ffi::RecoverableSignature);
@ -53,8 +53,7 @@ pub fn to_i32(self) -> i32 {
impl RecoverableSignature { impl RecoverableSignature {
#[inline] #[inline]
/// Converts a compact-encoded byte slice to a signature. This /// Converts a compact-encoded byte slice to a signature. This
/// representation is nonstandard and defined by the libsecp256k1 /// representation is nonstandard and defined by the libsecp256k1 library.
/// library.
pub fn from_compact(data: &[u8], recid: RecoveryId) -> Result<RecoverableSignature, Error> { pub fn from_compact(data: &[u8], recid: RecoveryId) -> Result<RecoverableSignature, Error> {
if data.is_empty() {return Err(Error::InvalidSignature);} if data.is_empty() {return Err(Error::InvalidSignature);}
@ -77,20 +76,20 @@ impl RecoverableSignature {
} }
} }
/// Obtains a raw pointer suitable for use with FFI functions /// Obtains a raw pointer suitable for use with FFI functions.
#[inline] #[inline]
pub fn as_ptr(&self) -> *const ffi::RecoverableSignature { pub fn as_ptr(&self) -> *const ffi::RecoverableSignature {
&self.0 &self.0
} }
/// Obtains a raw mutable pointer suitable for use with FFI functions /// Obtains a raw mutable pointer suitable for use with FFI functions.
#[inline] #[inline]
pub fn as_mut_ptr(&mut self) -> *mut ffi::RecoverableSignature { pub fn as_mut_ptr(&mut self) -> *mut ffi::RecoverableSignature {
&mut self.0 &mut self.0
} }
#[inline] #[inline]
/// Serializes the recoverable signature in compact format /// Serializes the recoverable signature in compact format.
pub fn serialize_compact(&self) -> (RecoveryId, [u8; 64]) { pub fn serialize_compact(&self) -> (RecoveryId, [u8; 64]) {
let mut ret = [0u8; 64]; let mut ret = [0u8; 64];
let mut recid = 0i32; let mut recid = 0i32;
@ -107,7 +106,7 @@ impl RecoverableSignature {
} }
/// Converts a recoverable signature to a non-recoverable one (this is needed /// Converts a recoverable signature to a non-recoverable one (this is needed
/// for verification /// for verification).
#[inline] #[inline]
pub fn to_standard(&self) -> Signature { pub fn to_standard(&self) -> Signature {
unsafe { unsafe {
@ -144,7 +143,7 @@ impl CPtr for RecoverableSignature {
} }
} }
/// Creates a new recoverable signature from a FFI one /// Creates a new recoverable signature from a FFI one.
impl From<ffi::RecoverableSignature> for RecoverableSignature { impl From<ffi::RecoverableSignature> for RecoverableSignature {
#[inline] #[inline]
fn from(sig: ffi::RecoverableSignature) -> RecoverableSignature { fn from(sig: ffi::RecoverableSignature) -> RecoverableSignature {
@ -153,7 +152,7 @@ impl From<ffi::RecoverableSignature> for RecoverableSignature {
} }
impl<C: Signing> Secp256k1<C> { impl<C: Signing> Secp256k1<C> {
/// Constructs a signature for `msg` using the secret key `sk` and RFC6979 nonce /// Constructs a signature for `msg` using the secret key `sk` and RFC6979 nonce.
/// Requires a signing-capable context. /// Requires a signing-capable context.
#[deprecated(since = "0.21.0", note = "Use sign_ecdsa_recoverable instead.")] #[deprecated(since = "0.21.0", note = "Use sign_ecdsa_recoverable instead.")]
pub fn sign_recoverable(&self, msg: &Message, sk: &key::SecretKey) -> RecoverableSignature { pub fn sign_recoverable(&self, msg: &Message, sk: &key::SecretKey) -> RecoverableSignature {

View File

@ -62,7 +62,7 @@ impl str::FromStr for SecretKey {
} }
} }
/// The number 1 encoded as a secret key /// The number 1 encoded as a secret key.
pub const ONE_KEY: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0, pub const ONE_KEY: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
@ -355,7 +355,7 @@ impl PublicKey {
unsafe { unsafe {
let mut pk = ffi::PublicKey::new(); 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)

View File

@ -13,7 +13,6 @@
// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. // If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
// //
//! # Secp256k1
//! Rust bindings for Pieter Wuille's secp256k1 library, which is used for //! Rust bindings for Pieter Wuille's secp256k1 library, which is used for
//! fast and accurate manipulation of ECDSA signatures on the secp256k1 //! fast and accurate manipulation of ECDSA signatures on the secp256k1
//! curve. Such signatures are used extensively by the Bitcoin network //! curve. Such signatures are used extensively by the Bitcoin network
@ -221,7 +220,7 @@ pub use context::global::SECP256K1;
use hashes::Hash; use hashes::Hash;
// Backwards compatible changes // Backwards compatible changes
/// Schnorr Sig related methods /// Schnorr Signature related methods.
#[deprecated(since = "0.21.0", note = "Use schnorr instead.")] #[deprecated(since = "0.21.0", note = "Use schnorr instead.")]
pub mod schnorrsig { pub mod schnorrsig {
#[deprecated(since = "0.21.0", note = "Use crate::XOnlyPublicKey instead.")] #[deprecated(since = "0.21.0", note = "Use crate::XOnlyPublicKey instead.")]
@ -271,7 +270,7 @@ impl<T: hashes::sha256t::Tag> ThirtyTwoByteHash for hashes::sha256t::Hash<T> {
} }
} }
/// A (hashed) message input to an ECDSA signature /// A (hashed) message input to an ECDSA signature.
pub struct Message([u8; constants::MESSAGE_SIZE]); pub struct Message([u8; constants::MESSAGE_SIZE]);
impl_array_newtype!(Message, u8, constants::MESSAGE_SIZE); impl_array_newtype!(Message, u8, constants::MESSAGE_SIZE);
impl_pretty_debug!(Message); impl_pretty_debug!(Message);
@ -318,7 +317,7 @@ impl Message {
} }
impl<T: ThirtyTwoByteHash> From<T> for Message { impl<T: ThirtyTwoByteHash> From<T> for Message {
/// Converts a 32-byte hash directly to a message without error paths /// Converts a 32-byte hash directly to a message without error paths.
fn from(t: T) -> Message { fn from(t: T) -> Message {
Message(t.into_32()) Message(t.into_32())
} }
@ -345,21 +344,21 @@ pub enum Error {
/// Signature failed verification /// Signature failed verification
IncorrectSignature, IncorrectSignature,
/// Badly sized message ("messages" are actually fixed-sized digests; see the `MESSAGE_SIZE` /// Badly sized message ("messages" are actually fixed-sized digests; see the `MESSAGE_SIZE`
/// constant) /// constant).
InvalidMessage, InvalidMessage,
/// Bad public key /// Bad public key.
InvalidPublicKey, InvalidPublicKey,
/// Bad signature /// Bad signature.
InvalidSignature, InvalidSignature,
/// Bad secret key /// Bad secret key.
InvalidSecretKey, InvalidSecretKey,
/// Bad recovery id /// Bad recovery id.
InvalidRecoveryId, InvalidRecoveryId,
/// Invalid tweak for add_*_assign or mul_*_assign /// Invalid tweak for `add_*_assign` or `mul_*_assign`.
InvalidTweak, InvalidTweak,
/// Didn't pass enough memory to context creation with preallocated memory /// Didn't pass enough memory to context creation with preallocated memory.
NotEnoughMemory, NotEnoughMemory,
/// Bad set of public keys /// Bad set of public keys.
InvalidPublicKeySum, InvalidPublicKeySum,
/// The only valid parity values are 0 or 1. /// The only valid parity values are 0 or 1.
InvalidParityValue, InvalidParityValue,
@ -382,7 +381,7 @@ impl Error {
} }
} }
// Passthrough Debug to Display, since errors should be user-visible // Passthrough Debug to Display, since errors should be user-visible.
impl fmt::Display for Error { impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
f.write_str(self.as_str()) f.write_str(self.as_str())
@ -394,16 +393,16 @@ impl fmt::Display for Error {
impl std::error::Error for Error {} impl std::error::Error for Error {}
/// The secp256k1 engine, used to execute all signature operations /// The secp256k1 engine, used to execute all signature operations.
pub struct Secp256k1<C: Context> { pub struct Secp256k1<C: Context> {
ctx: *mut ffi::Context, ctx: *mut ffi::Context,
phantom: PhantomData<C>, phantom: PhantomData<C>,
size: usize, size: usize,
} }
// The underlying secp context does not contain any references to memory it does not own // The underlying secp context does not contain any references to memory it does not own.
unsafe impl<C: Context> Send for Secp256k1<C> {} unsafe impl<C: Context> Send for Secp256k1<C> {}
// The API does not permit any mutation of `Secp256k1` objects except through `&mut` references // The API does not permit any mutation of `Secp256k1` objects except through `&mut` references.
unsafe impl<C: Context> Sync for Secp256k1<C> {} unsafe impl<C: Context> Sync for Secp256k1<C> {}
impl<C: Context> PartialEq for Secp256k1<C> { impl<C: Context> PartialEq for Secp256k1<C> {
@ -437,7 +436,7 @@ impl<C: Context> Secp256k1<C> {
&self.ctx &self.ctx
} }
/// Returns the required memory for a preallocated context buffer in a generic manner(sign/verify/all) /// Returns the required memory for a preallocated context buffer in a generic manner(sign/verify/all).
pub fn preallocate_size_gen() -> usize { pub fn preallocate_size_gen() -> usize {
let word_size = mem::size_of::<AlignedType>(); let word_size = mem::size_of::<AlignedType>();
let bytes = unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) }; let bytes = unsafe { ffi::secp256k1_context_preallocated_size(C::FLAGS) };
@ -445,9 +444,10 @@ impl<C: Context> Secp256k1<C> {
(bytes + word_size - 1) / word_size (bytes + word_size - 1) / word_size
} }
/// (Re)randomizes the Secp256k1 context for cheap sidechannel resistance; /// (Re)randomizes the Secp256k1 context for extra sidechannel resistance.
/// see comment in libsecp256k1 commit d2275795f by Gregory Maxwell. Requires ///
/// compilation with "rand" feature. /// Requires compilation with "rand" feature. See comment by Gregory Maxwell in
/// [libsecp256k1](https://github.com/bitcoin-core/secp256k1/commit/d2275795ff22a6f4738869f5528fbbb61738aa48).
#[cfg(any(test, feature = "rand"))] #[cfg(any(test, feature = "rand"))]
#[cfg_attr(docsrs, doc(cfg(feature = "rand")))] #[cfg_attr(docsrs, doc(cfg(feature = "rand")))]
pub fn randomize<R: Rng + ?Sized>(&mut self, rng: &mut R) { pub fn randomize<R: Rng + ?Sized>(&mut self, rng: &mut R) {
@ -456,7 +456,7 @@ impl<C: Context> Secp256k1<C> {
self.seeded_randomize(&seed); self.seeded_randomize(&seed);
} }
/// (Re)randomizes the Secp256k1 context for cheap sidechannel resistance given 32 bytes of /// (Re)randomizes the Secp256k1 context for extra sidechannel resistance given 32 bytes of
/// cryptographically-secure random data; /// cryptographically-secure random data;
/// see comment in libsecp256k1 commit d2275795f by Gregory Maxwell. /// see comment in libsecp256k1 commit d2275795f by Gregory Maxwell.
pub fn seeded_randomize(&mut self, seed: &[u8; 32]) { pub fn seeded_randomize(&mut self, seed: &[u8; 32]) {