Skip to content

Commit 72918bf

Browse files
committed
Merge #506: Manually implement PartialEq, Eq, and Hash for PublicKey
5ccf0c8 Manually implement PartialEq, Eq, and Hash for PublicKey (Tobin C. Harding) Pull request description: `PartialEq` and `Eq` should agree with `PartialOrd` and `Ord` but we are deriving `PartialEq`/`Eq` and doing a custom implementation of `PartialOrd` and `Ord` (that calls down to ffi functions). If two keys are equal their hashes should be equal so, we should add a custom implementation of `Hash` also. In order to guarantee the digest will be the same across library versions first serialize the key before hashing it. Add custom implementation of `PartialEq`, `Eq`, and `Hash` when not fuzzing. Please note, this is for the main `PublicKey` type, the patch does not effect the `ffi::PublicKey`, nor do we call methods on the `ffi::PublicKey`. EDIT: Please note the comment below by apoelstra about the possible performance hit introduced by this PR. ACKs for top commit: apoelstra: ACK 5ccf0c8 Tree-SHA512: 1464308238411d259bb0493dc1eca775ec235036eef10b91f70ef17816174f452d5911ecae3b40434b71f9866be1db54d69e8ed9475a4f2801c07a800aead2b2
2 parents 497654e + 5ccf0c8 commit 72918bf

File tree

1 file changed

+20
-2
lines changed

1 file changed

+20
-2
lines changed

src/key.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,8 +100,8 @@ pub const ONE_KEY: SecretKey = SecretKey(constants::ONE);
100100
/// ```
101101
/// [`bincode`]: https://docs.rs/bincode
102102
/// [`cbor`]: https://docs.rs/cbor
103-
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
104-
#[cfg_attr(fuzzing, derive(PartialOrd, Ord))]
103+
#[derive(Copy, Clone, Debug)]
104+
#[cfg_attr(fuzzing, derive(PartialOrd, Ord, PartialEq, Eq, Hash))]
105105
#[repr(transparent)]
106106
pub struct PublicKey(ffi::PublicKey);
107107

@@ -814,6 +814,24 @@ impl Ord for PublicKey {
814814
}
815815
}
816816

817+
#[cfg(not(fuzzing))]
818+
impl PartialEq for PublicKey {
819+
fn eq(&self, other: &Self) -> bool {
820+
self.cmp(other) == core::cmp::Ordering::Equal
821+
}
822+
}
823+
824+
#[cfg(not(fuzzing))]
825+
impl Eq for PublicKey {}
826+
827+
#[cfg(not(fuzzing))]
828+
impl core::hash::Hash for PublicKey {
829+
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
830+
let ser = self.serialize();
831+
ser.hash(state);
832+
}
833+
}
834+
817835
/// Opaque data structure that holds a keypair consisting of a secret and a public key.
818836
///
819837
/// # Serde support

0 commit comments

Comments
 (0)