Merge rust-bitcoin/rust-secp256k1#644: Improve `Message` constructors

cd40ae7f19 Improve Message constructors (Tobin C. Harding)

Pull request description:

  Observe:

  - The word "hash" can be a verb or a noun, its usage in function names is therefore at times ambiguous.
  - The function name `from_slice` gives no indication as to what the slice input is.

  Improve Message constructors by doing:

  - Add a constructor `Message::from_digest` that takes a 32 byte array as input.
  - Rename `Message::from_slice` to `Message::from_digest_slice` (deprecate `from_slice` and add `from_digest_slice`)
  - Improve the docs while we are at it.

  ### Note

  The original PR conflate 2 separate issues, the `Message` constructor naming clarity issue and the upgrade difficulty issue, PR is now only a solution to the first. The second will be done as a separate PR.

ACKs for top commit:
  apoelstra:
    ACK cd40ae7f19

Tree-SHA512: 4e5aeccf15cca95073f4c3a518b9e1f54f0e33c92c45dfecd1daa31d052022cd28c71bb6df6cff8a6548993e3e22788f11cd2633214ab5a580c753e66d2ea749
This commit is contained in:
Andrew Poelstra 2023-08-10 15:05:34 +00:00
commit 14e82186d1
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
7 changed files with 77 additions and 47 deletions

View File

@ -11,7 +11,7 @@ fn verify<C: Verification>(
pubkey: [u8; 33],
) -> Result<bool, Error> {
let msg = sha256::Hash::hash(msg);
let msg = Message::from_slice(msg.as_ref())?;
let msg = Message::from_digest_slice(msg.as_ref())?;
let sig = ecdsa::Signature::from_compact(&sig)?;
let pubkey = PublicKey::from_slice(&pubkey)?;
@ -24,7 +24,7 @@ fn sign<C: Signing>(
seckey: [u8; 32],
) -> Result<ecdsa::Signature, Error> {
let msg = sha256::Hash::hash(msg);
let msg = Message::from_slice(msg.as_ref())?;
let msg = Message::from_digest_slice(msg.as_ref())?;
let seckey = SecretKey::from_slice(&seckey)?;
Ok(secp.sign_ecdsa(&msg, &seckey))
}

View File

@ -11,7 +11,7 @@ fn recover<C: Verification>(
recovery_id: u8,
) -> Result<PublicKey, Error> {
let msg = sha256::Hash::hash(msg);
let msg = Message::from_slice(msg.as_ref())?;
let msg = Message::from_digest_slice(msg.as_ref())?;
let id = ecdsa::RecoveryId::from_i32(recovery_id as i32)?;
let sig = ecdsa::RecoverableSignature::from_compact(&sig, id)?;
@ -24,7 +24,7 @@ fn sign_recovery<C: Signing>(
seckey: [u8; 32],
) -> Result<ecdsa::RecoverableSignature, Error> {
let msg = sha256::Hash::hash(msg);
let msg = Message::from_slice(msg.as_ref())?;
let msg = Message::from_digest_slice(msg.as_ref())?;
let seckey = SecretKey::from_slice(&seckey)?;
Ok(secp.sign_ecdsa_recoverable(&msg, &seckey))
}

View File

@ -91,7 +91,7 @@ fn start(_argc: isize, _argv: *const *const u8) -> isize {
secp.randomize(&mut FakeRng);
let secret_key = SecretKey::new(&mut FakeRng);
let public_key = PublicKey::from_secret_key(&secp, &secret_key);
let message = Message::from_slice(&[0xab; 32]).expect("32 bytes");
let message = Message::from_digest_slice(&[0xab; 32]).expect("32 bytes");
let sig = secp.sign_ecdsa(&message, &secret_key);
assert!(secp.verify_ecdsa(&message, &sig, &public_key).is_ok());
@ -118,7 +118,7 @@ fn start(_argc: isize, _argv: *const *const u8) -> isize {
{
let secp_alloc = Secp256k1::new();
let public_key = PublicKey::from_secret_key(&secp_alloc, &secret_key);
let message = Message::from_slice(&[0xab; 32]).expect("32 bytes");
let message = Message::from_digest_slice(&[0xab; 32]).expect("32 bytes");
let sig = secp_alloc.sign_ecdsa(&message, &secret_key);
assert!(secp_alloc.verify_ecdsa(&message, &sig, &public_key).is_ok());

View File

@ -371,11 +371,11 @@ impl<C: Verification> Secp256k1<C> {
/// # let secp = Secp256k1::new();
/// # let (secret_key, public_key) = secp.generate_keypair(&mut rand::thread_rng());
/// #
/// let message = Message::from_slice(&[0xab; 32]).expect("32 bytes");
/// let message = Message::from_digest_slice(&[0xab; 32]).expect("32 bytes");
/// let sig = secp.sign_ecdsa(&message, &secret_key);
/// assert_eq!(secp.verify_ecdsa(&message, &sig, &public_key), Ok(()));
///
/// let message = Message::from_slice(&[0xcd; 32]).expect("32 bytes");
/// let message = Message::from_digest_slice(&[0xcd; 32]).expect("32 bytes");
/// assert_eq!(secp.verify_ecdsa(&message, &sig, &public_key), Err(Error::IncorrectSignature));
/// # }
/// ```

View File

@ -226,7 +226,7 @@ mod tests {
let full = Secp256k1::new();
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
// Try key generation
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
@ -258,7 +258,7 @@ mod tests {
s.randomize(&mut rand::thread_rng());
let sk = SecretKey::from_slice(&ONE).unwrap();
let msg = Message::from_slice(&ONE).unwrap();
let msg = Message::from_digest_slice(&ONE).unwrap();
let sig = s.sign_ecdsa_recoverable(&msg, &sk);
@ -283,7 +283,7 @@ mod tests {
s.randomize(&mut rand::thread_rng());
let sk = SecretKey::from_slice(&ONE).unwrap();
let msg = Message::from_slice(&ONE).unwrap();
let msg = Message::from_digest_slice(&ONE).unwrap();
let noncedata = [42u8; 32];
let sig = s.sign_ecdsa_recoverable_with_noncedata(&msg, &sk, &noncedata);
@ -307,7 +307,7 @@ mod tests {
s.randomize(&mut rand::thread_rng());
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
@ -315,7 +315,7 @@ mod tests {
let sig = sigr.to_standard();
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
assert_eq!(s.verify_ecdsa(&msg, &sig, &pk), Err(Error::IncorrectSignature));
let recovered_key = s.recover_ecdsa(&msg, &sigr).unwrap();
@ -329,7 +329,7 @@ mod tests {
s.randomize(&mut rand::thread_rng());
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
@ -345,7 +345,7 @@ mod tests {
s.randomize(&mut rand::thread_rng());
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let noncedata = [42u8; 32];
@ -362,7 +362,7 @@ mod tests {
let mut s = Secp256k1::new();
s.randomize(&mut rand::thread_rng());
let msg = Message::from_slice(&[0x55; 32]).unwrap();
let msg = Message::from_digest_slice(&[0x55; 32]).unwrap();
// Zero is not a valid sig
let sig = RecoverableSignature::from_compact(&[0; 64], RecoveryId(0)).unwrap();
@ -433,7 +433,7 @@ mod benches {
pub fn bench_recover(bh: &mut Bencher) {
let s = Secp256k1::new();
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, _) = s.generate_keypair(&mut rand::thread_rng());
let sig = s.sign_ecdsa_recoverable(&msg, &sk);

View File

@ -70,7 +70,7 @@
//! let public_key = PublicKey::from_secret_key(&secp, &secret_key);
//! // This is unsafe unless the supplied byte slice is the output of a cryptographic hash function.
//! // See the above example for how to use this library together with `bitcoin-hashes-std`.
//! let message = Message::from_slice(&[0xab; 32]).expect("32 bytes");
//! let message = Message::from_digest_slice(&[0xab; 32]).expect("32 bytes");
//!
//! let sig = secp.sign_ecdsa(&message, &secret_key);
//! assert!(secp.verify_ecdsa(&message, &sig, &public_key).is_ok());
@ -93,7 +93,7 @@
//! 0x3a, 0x17, 0x10, 0xc9, 0x62, 0x67, 0x90, 0x63,
//! ]).expect("public keys must be 33 or 65 bytes, serialized according to SEC 2");
//!
//! let message = Message::from_slice(&[
//! let message = Message::from_digest_slice(&[
//! 0xaa, 0xdf, 0x7d, 0xe7, 0x82, 0x03, 0x4f, 0xbe,
//! 0x3d, 0x3d, 0xb2, 0xcb, 0x13, 0xc0, 0xcd, 0x91,
//! 0xbf, 0x41, 0xcb, 0x08, 0xfa, 0xc7, 0xbd, 0x61,
@ -225,11 +225,41 @@ impl Message {
/// the result of signing isn't a
/// [secure signature](https://twitter.com/pwuille/status/1063582706288586752).
#[inline]
pub fn from_slice(data: &[u8]) -> Result<Message, Error> {
match data.len() {
#[deprecated(since = "0.28.0", note = "use from_digest_slice instead")]
pub fn from_slice(digest: &[u8]) -> Result<Message, Error> {
Message::from_digest_slice(digest)
}
/// Creates a [`Message`] from a `digest`.
///
/// **If you just want to sign an arbitrary message use `Message::from_hashed_data` instead.**
///
/// The `digest` array has to be a cryptographically secure hash of the actual message that's
/// going to be signed. Otherwise the result of signing isn't a [secure signature].
///
/// [secure signature]: https://twitter.com/pwuille/status/1063582706288586752
#[inline]
pub fn from_digest(digest: [u8; 32]) -> Message { Message(digest) }
/// Creates a [`Message`] from a 32 byte slice `digest`.
///
/// **If you just want to sign an arbitrary message use `Message::from_hashed_data` instead.**
///
/// The slice has to be 32 bytes long and be a cryptographically secure hash of the actual
/// message that's going to be signed. Otherwise the result of signing isn't a [secure
/// signature].
///
/// # Errors
///
/// If `digest` is not exactly 32 bytes long.
///
/// [secure signature]: https://twitter.com/pwuille/status/1063582706288586752
#[inline]
pub fn from_digest_slice(digest: &[u8]) -> Result<Message, Error> {
match digest.len() {
constants::MESSAGE_SIZE => {
let mut ret = [0u8; constants::MESSAGE_SIZE];
ret[..].copy_from_slice(data);
ret[..].copy_from_slice(digest);
Ok(Message(ret))
}
_ => Err(Error::InvalidMessage),
@ -540,7 +570,7 @@ mod tests {
Secp256k1 { ctx: ctx_vrfy, phantom: PhantomData };
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
let msg = Message::from_slice(&[2u8; 32]).unwrap();
let msg = Message::from_digest_slice(&[2u8; 32]).unwrap();
// Try signing
assert_eq!(sign.sign_ecdsa(&msg, &sk), full.sign_ecdsa(&msg, &sk));
let sig = full.sign_ecdsa(&msg, &sk);
@ -572,7 +602,7 @@ mod tests {
let mut vrfy = unsafe { Secp256k1::from_raw_verification_only(ctx_vrfy.ctx) };
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
let msg = Message::from_slice(&[2u8; 32]).unwrap();
let msg = Message::from_digest_slice(&[2u8; 32]).unwrap();
// Try signing
assert_eq!(sign.sign_ecdsa(&msg, &sk), full.sign_ecdsa(&msg, &sk));
let sig = full.sign_ecdsa(&msg, &sk);
@ -618,7 +648,7 @@ mod tests {
// println!("{:?}", buf_ful[5]); // Can't even read the data thanks to the borrow checker.
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
let msg = Message::from_slice(&[2u8; 32]).unwrap();
let msg = Message::from_digest_slice(&[2u8; 32]).unwrap();
// Try signing
assert_eq!(sign.sign_ecdsa(&msg, &sk), full.sign_ecdsa(&msg, &sk));
let sig = full.sign_ecdsa(&msg, &sk);
@ -636,7 +666,7 @@ mod tests {
let full = Secp256k1::new();
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
// Try key generation
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
@ -665,7 +695,7 @@ mod tests {
for _ in 0..100 {
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, _) = s.generate_keypair(&mut rand::thread_rng());
let sig1 = s.sign_ecdsa(&msg, &sk);
@ -756,7 +786,7 @@ mod tests {
let noncedata = [42u8; 32];
for _ in 0..100 {
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
let sig = s.sign_ecdsa(&msg, &sk);
@ -803,7 +833,7 @@ mod tests {
wild_msgs[1][0] -= 1;
for key in wild_keys.iter().map(|k| SecretKey::from_slice(&k[..]).unwrap()) {
for msg in wild_msgs.iter().map(|m| Message::from_slice(&m[..]).unwrap()) {
for msg in wild_msgs.iter().map(|m| Message::from_digest_slice(&m[..]).unwrap()) {
let sig = s.sign_ecdsa(&msg, &key);
let low_r_sig = s.sign_ecdsa_low_r(&msg, &key);
let grind_r_sig = s.sign_ecdsa_grind_r(&msg, &key, 1);
@ -822,14 +852,14 @@ mod tests {
s.randomize(&mut rand::thread_rng());
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
let sig = s.sign_ecdsa(&msg, &sk);
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
assert_eq!(s.verify_ecdsa(&msg, &sig, &pk), Err(Error::IncorrectSignature));
}
@ -845,15 +875,15 @@ mod tests {
);
assert_eq!(
Message::from_slice(&[0; constants::MESSAGE_SIZE - 1]),
Message::from_digest_slice(&[0; constants::MESSAGE_SIZE - 1]),
Err(Error::InvalidMessage)
);
assert_eq!(
Message::from_slice(&[0; constants::MESSAGE_SIZE + 1]),
Message::from_digest_slice(&[0; constants::MESSAGE_SIZE + 1]),
Err(Error::InvalidMessage)
);
assert!(Message::from_slice(&[0; constants::MESSAGE_SIZE]).is_ok());
assert!(Message::from_slice(&[1; constants::MESSAGE_SIZE]).is_ok());
assert!(Message::from_digest_slice(&[0; constants::MESSAGE_SIZE]).is_ok());
assert!(Message::from_digest_slice(&[1; constants::MESSAGE_SIZE]).is_ok());
}
#[test]
@ -892,7 +922,7 @@ mod tests {
fn test_noncedata() {
let secp = Secp256k1::new();
let msg = hex!("887d04bb1cf1b1554f1b268dfe62d13064ca67ae45348d50d1392ce2d13418ac");
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let noncedata = [42u8; 32];
let sk =
SecretKey::from_str("57f0148f94d13095cfda539d0da0d1541304b678d8b36e243980aab4e1b7cead")
@ -919,7 +949,7 @@ mod tests {
let secp = Secp256k1::new();
let mut sig = ecdsa::Signature::from_der(&sig[..]).unwrap();
let pk = PublicKey::from_slice(&pk[..]).unwrap();
let msg = Message::from_slice(&msg[..]).unwrap();
let msg = Message::from_digest_slice(&msg[..]).unwrap();
// without normalization we expect this will fail
assert_eq!(secp.verify_ecdsa(&msg, &sig, &pk), Err(Error::IncorrectSignature));
@ -934,7 +964,7 @@ mod tests {
fn test_low_r() {
let secp = Secp256k1::new();
let msg = hex!("887d04bb1cf1b1554f1b268dfe62d13064ca67ae45348d50d1392ce2d13418ac");
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let sk =
SecretKey::from_str("57f0148f94d13095cfda539d0da0d1541304b678d8b36e243980aab4e1b7cead")
.unwrap();
@ -952,7 +982,7 @@ mod tests {
fn test_grind_r() {
let secp = Secp256k1::new();
let msg = hex!("ef2d5b9a7c61865a95941d0f04285420560df7e9d76890ac1b8867b12ce43167");
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let sk =
SecretKey::from_str("848355d75fe1c354cf05539bb29b2015f1863065bcb6766b44d399ab95c3fa0b")
.unwrap();
@ -972,7 +1002,7 @@ mod tests {
let s = Secp256k1::new();
let msg = Message::from_slice(&[1; 32]).unwrap();
let msg = Message::from_digest_slice(&[1; 32]).unwrap();
let sk = SecretKey::from_slice(&[2; 32]).unwrap();
let sig = s.sign_ecdsa(&msg, &sk);
static SIG_BYTES: [u8; 71] = [
@ -1002,7 +1032,7 @@ mod tests {
let sk_data = hex!("e6dd32f8761625f105c39a39f19370b3521d845a12456d60ce44debd0a362641");
let sk = SecretKey::from_slice(&sk_data).unwrap();
let msg_data = hex!("a4965ca63b7d8562736ceec36dfa5a11bf426eb65be8ea3f7a49ae363032da0d");
let msg = Message::from_slice(&msg_data).unwrap();
let msg = Message::from_digest_slice(&msg_data).unwrap();
// Check usage as explicit parameter
let pk = PublicKey::from_secret_key(SECP256K1, &sk);
@ -1054,7 +1084,7 @@ mod benches {
pub fn bench_sign_ecdsa(bh: &mut Bencher) {
let s = Secp256k1::new();
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, _) = s.generate_keypair(&mut rand::thread_rng());
bh.iter(|| {
@ -1067,7 +1097,7 @@ mod benches {
pub fn bench_verify_ecdsa(bh: &mut Bencher) {
let s = Secp256k1::new();
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
let sig = s.sign_ecdsa(&msg, &sk);

View File

@ -248,7 +248,7 @@ mod tests {
for _ in 0..100 {
let msg = crate::random_32_bytes(&mut rand::thread_rng());
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::from_digest_slice(&msg).unwrap();
let sig = sign(&secp, &msg, &kp, &mut rng);
@ -263,7 +263,7 @@ mod tests {
let secp = Secp256k1::new();
let hex_msg = hex_32!("E48441762FB75010B2AA31A512B62B4148AA3FB08EB0765D76B252559064A614");
let msg = Message::from_slice(&hex_msg).unwrap();
let msg = Message::from_digest_slice(&hex_msg).unwrap();
let sk = KeyPair::from_seckey_str(
&secp,
"688C77BC2D5AAFF5491CF309D4753B732135470D05B7B2CD21ADD0744FE97BEF",
@ -285,7 +285,7 @@ mod tests {
let secp = Secp256k1::new();
let hex_msg = hex_32!("E48441762FB75010B2AA31A512B62B4148AA3FB08EB0765D76B252559064A614");
let msg = Message::from_slice(&hex_msg).unwrap();
let msg = Message::from_digest_slice(&hex_msg).unwrap();
let sig = Signature::from_str("6470FD1303DDA4FDA717B9837153C24A6EAB377183FC438F939E0ED2B620E9EE5077C4A8B8DCA28963D772A94F5F0DDF598E1C47C137F91933274C7C3EDADCE8").unwrap();
let pubkey = XOnlyPublicKey::from_str(
"B33CC9EDC096D0A83416964BD3C6247B8FECD256E4EFA7870D2C854BDEB33390",
@ -464,7 +464,7 @@ mod tests {
let s = Secp256k1::new();
let msg = Message::from_slice(&[1; 32]).unwrap();
let msg = Message::from_digest_slice(&[1; 32]).unwrap();
let keypair = KeyPair::from_seckey_slice(&s, &[2; 32]).unwrap();
let aux = [3u8; 32];
let sig = s.sign_schnorr_with_aux_rand(&msg, &keypair, &aux);