|
6 | 6 | use core::ops::{self, BitXor};
|
7 | 7 | use core::{fmt, ptr, str};
|
8 | 8 |
|
| 9 | +use secp256k1_sys::secp256k1_ec_pubkey_sort; |
9 | 10 | #[cfg(feature = "serde")]
|
10 | 11 | use serde::ser::SerializeTuple;
|
11 | 12 |
|
@@ -1602,6 +1603,36 @@ impl<'de> serde::Deserialize<'de> for XOnlyPublicKey {
|
1602 | 1603 | }
|
1603 | 1604 | }
|
1604 | 1605 |
|
| 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 | + |
1605 | 1636 | #[cfg(test)]
|
1606 | 1637 | #[allow(unused_imports)]
|
1607 | 1638 | mod test {
|
|
0 commit comments