Skip to content

Commit

Permalink
Implement lexigraphic ordering for PubKey
Browse files Browse the repository at this point in the history
  • Loading branch information
justinmoon committed Nov 9, 2020
1 parent d31dcf2 commit 1ba7317
Showing 1 changed file with 23 additions and 1 deletion.
24 changes: 23 additions & 1 deletion src/key.rs
Expand Up @@ -64,7 +64,7 @@ pub const ONE_KEY: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 1]);

/// A Secp256k1 public key, used for verification of signatures
#[derive(Copy, Clone, PartialEq, Eq, Debug, PartialOrd, Ord, Hash)]
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
pub struct PublicKey(ffi::PublicKey);

impl fmt::LowerHex for PublicKey {
Expand Down Expand Up @@ -470,6 +470,18 @@ impl<'de> ::serde::Deserialize<'de> for PublicKey {
}
}

impl PartialOrd for PublicKey {
fn partial_cmp(&self, other: &PublicKey) -> Option<::core::cmp::Ordering> {
self.serialize().partial_cmp(&other.serialize())
}
}

impl Ord for PublicKey {
fn cmp(&self, other: &PublicKey) -> ::core::cmp::Ordering {
self.serialize().cmp(&other.serialize())
}
}

#[cfg(test)]
mod test {
use Secp256k1;
Expand Down Expand Up @@ -512,6 +524,16 @@ mod test {
assert!(compressed.is_ok());
}

#[test]
fn pubkey_ordering() {
let pk1 = PublicKey::from_str("03cc0add20974ae5c73dcb1db8c157921403487943ecdc96f1f06bc5b189695590").unwrap();
let pk2 = PublicKey::from_str("0237869a55636998319161ae342085feeacc72397948b77a936c9c23c161645db6").unwrap();
let mut v = vec![pk1, pk2];
v.sort();
let expected = vec![pk2, pk1];
assert_eq!(v, expected);
}

#[test]
fn keypair_slice_round_trip() {
let s = Secp256k1::new();
Expand Down

0 comments on commit 1ba7317

Please sign in to comment.