Skip to content

Commit

Permalink
impl partial ord/ord for PublicKey
Browse files Browse the repository at this point in the history
  • Loading branch information
sanket1729 committed Nov 23, 2020
1 parent 7c05673 commit 0c7c863
Showing 1 changed file with 24 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/util/key.rs
Expand Up @@ -17,7 +17,7 @@
//!

use std::fmt::{self, Write};
use std::{io, ops, error};
use std::{cmp, io, ops, error};
use std::str::FromStr;

use secp256k1::{self, Secp256k1};
Expand Down Expand Up @@ -69,14 +69,36 @@ impl From<secp256k1::Error> for Error {
}

/// A Bitcoin ECDSA public key
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct PublicKey {
/// Whether this public key should be serialized as compressed
pub compressed: bool,
/// The actual ECDSA key
pub key: secp256k1::PublicKey,
}

impl Ord for PublicKey{

// implement lexical partial ord for PublicKey as per BIP 67 if both keys are
// compressed/uncompressed. Since, compressed Pk's start with 0x02 and 0x03
// they are always less than the 0x04 uncompressed keys
fn cmp(&self, other: &PublicKey) -> cmp::Ordering {
match (self.compressed, other.compressed){
(true, false) => cmp::Ordering::Less,
(false, true) => cmp::Ordering::Greater,
(true, true) => self.key.serialize().cmp(&other.key.serialize()),
(false, false) => self.key.serialize_uncompressed().cmp(&other.key.serialize_uncompressed()),
}
}
}

impl PartialOrd for PublicKey{

fn partial_cmp(&self, other: &PublicKey) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}

impl PublicKey {
/// Returns bitcoin 160-bit hash of the public key
pub fn pubkey_hash(&self) -> PubkeyHash {
Expand Down

0 comments on commit 0c7c863

Please sign in to comment.