Skip to content

Commit a42b6b2

Browse files
committed
Add function to sort public keys
1 parent ff77611 commit a42b6b2

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/key.rs

+31
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
use core::ops::{self, BitXor};
77
use core::{fmt, ptr, str};
88

9+
use secp256k1_sys::secp256k1_ec_pubkey_sort;
910
#[cfg(feature = "serde")]
1011
use serde::ser::SerializeTuple;
1112

@@ -1602,6 +1603,36 @@ impl<'de> serde::Deserialize<'de> for XOnlyPublicKey {
16021603
}
16031604
}
16041605

1606+
/// Sort public keys using lexicographic (of compressed serialization) order.
1607+
/// Example:
1608+
///
1609+
/// ```rust
1610+
/// # # [cfg(any(test, feature = "rand-std"))] {
1611+
/// # use secp256k1::rand::{thread_rng, RngCore};
1612+
/// # use secp256k1::{Secp256k1, SecretKey, Keypair, PublicKey, pubkey_sort};
1613+
/// # let secp = Secp256k1::new();
1614+
/// # let sk1 = SecretKey::new(&mut thread_rng());
1615+
/// # let pub_key1 = PublicKey::from_secret_key(&secp, &sk1);
1616+
/// # let sk2 = SecretKey::new(&mut thread_rng());
1617+
/// # let pub_key2 = PublicKey::from_secret_key(&secp, &sk2);
1618+
/// #
1619+
/// # let pubkeys = [pub_key1, pub_key2];
1620+
/// # let mut pubkeys_ref: Vec<&PublicKey> = pubkeys.iter().collect();
1621+
/// # let pubkeys_ref = pubkeys_ref.as_mut_slice();
1622+
/// #
1623+
/// # pubkey_sort(&secp, pubkeys_ref);
1624+
/// # }
1625+
/// ```
1626+
pub fn pubkey_sort<C: Verification>(secp: &Secp256k1<C>, pubkeys: &mut [&PublicKey]) {
1627+
let cx = secp.ctx().as_ptr();
1628+
unsafe {
1629+
let mut pubkeys_ref = core::slice::from_raw_parts(pubkeys.as_c_ptr() as *mut *const ffi::PublicKey, pubkeys.len());
1630+
if secp256k1_ec_pubkey_sort(cx, pubkeys_ref.as_mut_c_ptr(), pubkeys_ref.len()) == 0 {
1631+
unreachable!("Invalid public keys for sorting function")
1632+
}
1633+
}
1634+
}
1635+
16051636
#[cfg(test)]
16061637
#[allow(unused_imports)]
16071638
mod test {

src/lib.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ pub use crate::context::{
191191
};
192192
use crate::ffi::types::AlignedType;
193193
use crate::ffi::CPtr;
194-
pub use crate::key::{InvalidParityValue, Keypair, Parity, PublicKey, SecretKey, XOnlyPublicKey};
194+
pub use crate::key::{InvalidParityValue, Keypair, Parity, PublicKey, SecretKey, XOnlyPublicKey, pubkey_sort};
195195
pub use crate::scalar::Scalar;
196196

197197
/// Trait describing something that promises to be a 32-byte uniformly random number.

0 commit comments

Comments
 (0)