Skip to content

Commit

Permalink
Add additional Message constructors
Browse files Browse the repository at this point in the history
Currently we provide two ways to construct a `Message` with the aim that
one is type-safe and one is loosey-goosey `From<T: ThirtyTwoByteHash>`
and `from_slice` respectively. We then use `from_slice` in tests and
`from` in code in `rust-bitcoin`.

The trait is causing us a headache every time we have to upgrade because
it means that `hashes` must be the same version here and in `bitcoin`.

At the cost of a little explicit safety add a function

  `Message::from_hash(hash: [u8; 32])`

that constructs a message. Include a dirty big warning about the input
hash being output from a cryptographicly sound hash algorithm.

While we are at it add `Message::insecure` and deprecated `from_slice`.
This makes code that uses the dangerous constructor more obvious. Also
this panics instead of erroring since it is useful mainly for testing.
  • Loading branch information
tcharding committed Aug 9, 2023
1 parent 29e1a0c commit 1aa72cf
Show file tree
Hide file tree
Showing 5 changed files with 70 additions and 60 deletions.
8 changes: 4 additions & 4 deletions examples/sign_verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ fn verify<C: Verification>(
sig: [u8; 64],
pubkey: [u8; 33],
) -> Result<bool, Error> {
let msg = sha256::Hash::hash(msg);
let msg = Message::from_slice(msg.as_ref())?;
let hash = sha256::Hash::hash(msg);
let msg = Message::from_hash(hash.to_byte_array());
let sig = ecdsa::Signature::from_compact(&sig)?;
let pubkey = PublicKey::from_slice(&pubkey)?;

Expand All @@ -23,8 +23,8 @@ fn sign<C: Signing>(
msg: &[u8],
seckey: [u8; 32],
) -> Result<ecdsa::Signature, Error> {
let msg = sha256::Hash::hash(msg);
let msg = Message::from_slice(msg.as_ref())?;
let hash = sha256::Hash::hash(msg);
let msg = Message::from_hash(hash.to_byte_array());
let seckey = SecretKey::from_slice(&seckey)?;
Ok(secp.sign_ecdsa(&msg, &seckey))
}
Expand Down
8 changes: 4 additions & 4 deletions examples/sign_verify_recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ fn recover<C: Verification>(
sig: [u8; 64],
recovery_id: u8,
) -> Result<PublicKey, Error> {
let msg = sha256::Hash::hash(msg);
let msg = Message::from_slice(msg.as_ref())?;
let hash = sha256::Hash::hash(msg);
let msg = Message::from_hash(hash.to_byte_array());
let id = ecdsa::RecoveryId::from_i32(recovery_id as i32)?;
let sig = ecdsa::RecoverableSignature::from_compact(&sig, id)?;

Expand All @@ -23,8 +23,8 @@ fn sign_recovery<C: Signing>(
msg: &[u8],
seckey: [u8; 32],
) -> Result<ecdsa::RecoverableSignature, Error> {
let msg = sha256::Hash::hash(msg);
let msg = Message::from_slice(msg.as_ref())?;
let hash = sha256::Hash::hash(msg);
let msg = Message::from_hash(hash.to_byte_array());
let seckey = SecretKey::from_slice(&seckey)?;
Ok(secp.sign_ecdsa_recoverable(&msg, &seckey))
}
Expand Down
16 changes: 8 additions & 8 deletions src/ecdsa/recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::insecure(&msg);

// Try key generation
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
Expand Down Expand Up @@ -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::insecure(&ONE);

let sig = s.sign_ecdsa_recoverable(&msg, &sk);

Expand All @@ -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::insecure(&ONE);
let noncedata = [42u8; 32];

let sig = s.sign_ecdsa_recoverable_with_noncedata(&msg, &sk, &noncedata);
Expand All @@ -307,15 +307,15 @@ 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::insecure(&msg);

let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());

let sigr = s.sign_ecdsa_recoverable(&msg, &sk);
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::insecure(&msg);
assert_eq!(s.verify_ecdsa(&msg, &sig, &pk), Err(Error::IncorrectSignature));

let recovered_key = s.recover_ecdsa(&msg, &sigr).unwrap();
Expand All @@ -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::insecure(&msg);

let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());

Expand All @@ -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::insecure(&msg);

let noncedata = [42u8; 32];

Expand All @@ -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::insecure(&[0x55; 32]);

// Zero is not a valid sig
let sig = RecoverableSignature::from_compact(&[0; 64], RecoveryId(0)).unwrap();
Expand Down
90 changes: 50 additions & 40 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,23 +218,16 @@ impl_array_newtype!(Message, u8, constants::MESSAGE_SIZE);
impl_pretty_debug!(Message);

impl Message {
/// Creates a [`Message`] from a `hash`.
///
/// **If you just want to sign an arbitrary message use `Message::from_hashed_data` instead.**
///
/// Converts a `MESSAGE_SIZE`-byte slice to a message object. **WARNING:** the slice 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](https://twitter.com/pwuille/status/1063582706288586752).
/// The `hash` 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_slice(data: &[u8]) -> Result<Message, Error> {
match data.len() {
constants::MESSAGE_SIZE => {
let mut ret = [0u8; constants::MESSAGE_SIZE];
ret[..].copy_from_slice(data);
Ok(Message(ret))
}
_ => Err(Error::InvalidMessage),
}
}
pub fn from_hash(hash: [u8; 32]) -> Message { Message(hash) }

/// Constructs a [`Message`] by hashing `data` with hash algorithm `H`.
///
Expand All @@ -258,6 +251,34 @@ impl Message {
pub fn from_hashed_data<H: ThirtyTwoByteHash + hashes::Hash>(data: &[u8]) -> Self {
<H as hashes::Hash>::hash(data).into()
}

/// **If you just want to sign an arbitrary message use `Message::from_hashed_data` instead.**
///
/// Converts a `MESSAGE_SIZE`-byte slice to a message object. **WARNING:** the slice 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](https://twitter.com/pwuille/status/1063582706288586752).
#[inline]
#[deprecated(since = "0.28.0", note = "use insecure instead")]
pub fn from_slice(data: &[u8]) -> Result<Message, Error> {
match data.len() {
constants::MESSAGE_SIZE => Ok(Message::insecure(data)),
_ => Err(Error::InvalidMessage),
}
}

/// Creates a message that signs `data`.
///
/// Intended for use with non-cryptographically secure slices (ie, not the hash of a message).
///
/// # Panics
///
/// Panics if `data` is not 32 bytes long.
pub fn insecure(data: &[u8]) -> Self {
let mut ret = [0u8; constants::MESSAGE_SIZE];
ret[..].copy_from_slice(data);
Message(ret)
}
}

impl<T: ThirtyTwoByteHash> From<T> for Message {
Expand Down Expand Up @@ -540,7 +561,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::insecure(&[2u8; 32]);
// Try signing
assert_eq!(sign.sign_ecdsa(&msg, &sk), full.sign_ecdsa(&msg, &sk));
let sig = full.sign_ecdsa(&msg, &sk);
Expand Down Expand Up @@ -572,7 +593,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::insecure(&[2u8; 32]);
// Try signing
assert_eq!(sign.sign_ecdsa(&msg, &sk), full.sign_ecdsa(&msg, &sk));
let sig = full.sign_ecdsa(&msg, &sk);
Expand Down Expand Up @@ -618,7 +639,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::insecure(&[2u8; 32]);
// Try signing
assert_eq!(sign.sign_ecdsa(&msg, &sk), full.sign_ecdsa(&msg, &sk));
let sig = full.sign_ecdsa(&msg, &sk);
Expand All @@ -636,7 +657,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::insecure(&msg);

// Try key generation
let (sk, pk) = full.generate_keypair(&mut rand::thread_rng());
Expand Down Expand Up @@ -665,7 +686,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::insecure(&msg);

let (sk, _) = s.generate_keypair(&mut rand::thread_rng());
let sig1 = s.sign_ecdsa(&msg, &sk);
Expand Down Expand Up @@ -756,7 +777,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::insecure(&msg);

let (sk, pk) = s.generate_keypair(&mut rand::thread_rng());
let sig = s.sign_ecdsa(&msg, &sk);
Expand Down Expand Up @@ -803,7 +824,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::insecure(&m[..])) {
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);
Expand All @@ -822,14 +843,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::insecure(&msg);

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::insecure(&msg);
assert_eq!(s.verify_ecdsa(&msg, &sig, &pk), Err(Error::IncorrectSignature));
}

Expand All @@ -843,17 +864,6 @@ mod tests {
ecdsa::Signature::from_der(&[0; constants::MAX_SIGNATURE_SIZE]),
Err(Error::InvalidSignature)
);

assert_eq!(
Message::from_slice(&[0; constants::MESSAGE_SIZE - 1]),
Err(Error::InvalidMessage)
);
assert_eq!(
Message::from_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());
}

#[test]
Expand Down Expand Up @@ -892,7 +902,7 @@ mod tests {
fn test_noncedata() {
let secp = Secp256k1::new();
let msg = hex!("887d04bb1cf1b1554f1b268dfe62d13064ca67ae45348d50d1392ce2d13418ac");
let msg = Message::from_slice(&msg).unwrap();
let msg = Message::insecure(&msg);
let noncedata = [42u8; 32];
let sk =
SecretKey::from_str("57f0148f94d13095cfda539d0da0d1541304b678d8b36e243980aab4e1b7cead")
Expand All @@ -919,7 +929,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::insecure(&msg[..]);

// without normalization we expect this will fail
assert_eq!(secp.verify_ecdsa(&msg, &sig, &pk), Err(Error::IncorrectSignature));
Expand All @@ -934,7 +944,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::insecure(&msg);
let sk =
SecretKey::from_str("57f0148f94d13095cfda539d0da0d1541304b678d8b36e243980aab4e1b7cead")
.unwrap();
Expand All @@ -952,7 +962,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::insecure(&msg);
let sk =
SecretKey::from_str("848355d75fe1c354cf05539bb29b2015f1863065bcb6766b44d399ab95c3fa0b")
.unwrap();
Expand All @@ -972,7 +982,7 @@ mod tests {

let s = Secp256k1::new();

let msg = Message::from_slice(&[1; 32]).unwrap();
let msg = Message::insecure(&[1; 32]);
let sk = SecretKey::from_slice(&[2; 32]).unwrap();
let sig = s.sign_ecdsa(&msg, &sk);
static SIG_BYTES: [u8; 71] = [
Expand Down Expand Up @@ -1002,7 +1012,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::insecure(&msg_data);

// Check usage as explicit parameter
let pk = PublicKey::from_secret_key(SECP256K1, &sk);
Expand Down
8 changes: 4 additions & 4 deletions src/schnorr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::insecure(&msg);

let sig = sign(&secp, &msg, &kp, &mut rng);

Expand All @@ -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::insecure(&hex_msg);
let sk = KeyPair::from_seckey_str(
&secp,
"688C77BC2D5AAFF5491CF309D4753B732135470D05B7B2CD21ADD0744FE97BEF",
Expand All @@ -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::insecure(&hex_msg);
let sig = Signature::from_str("6470FD1303DDA4FDA717B9837153C24A6EAB377183FC438F939E0ED2B620E9EE5077C4A8B8DCA28963D772A94F5F0DDF598E1C47C137F91933274C7C3EDADCE8").unwrap();
let pubkey = XOnlyPublicKey::from_str(
"B33CC9EDC096D0A83416964BD3C6247B8FECD256E4EFA7870D2C854BDEB33390",
Expand Down Expand Up @@ -464,7 +464,7 @@ mod tests {

let s = Secp256k1::new();

let msg = Message::from_slice(&[1; 32]).unwrap();
let msg = Message::insecure(&[1; 32]);
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);
Expand Down

0 comments on commit 1aa72cf

Please sign in to comment.