Skip to content

Commit 21a0482

Browse files
committed
Add combine_keys function to PublicKey
1 parent 4ae0e7e commit 21a0482

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

src/key.rs

+35-2
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ pub const ONE_KEY: SecretKey = SecretKey([0, 0, 0, 0, 0, 0, 0, 0,
6565

6666
/// A Secp256k1 public key, used for verification of signatures
6767
#[derive(Copy, Clone, PartialEq, Eq, Debug, Hash)]
68+
#[repr(transparent)]
6869
pub struct PublicKey(ffi::PublicKey);
6970

7071
impl fmt::LowerHex for PublicKey {
@@ -364,14 +365,23 @@ impl PublicKey {
364365
/// the result would be the point at infinity, i.e. we are adding this point
365366
/// to its own negation
366367
pub fn combine(&self, other: &PublicKey) -> Result<PublicKey, Error> {
368+
PublicKey::combine_keys(&[self, other])
369+
}
370+
371+
/// Adds the keys in the provided slice together, returning the sum. Returns
372+
/// an error if the result would be the point at infinity, i.e. we are adding
373+
/// a point to its own negation
374+
#[cfg(all(feature = "std"))]
375+
pub fn combine_keys(keys: &[&PublicKey]) -> Result<PublicKey, Error> {
367376
unsafe {
368377
let mut ret = ffi::PublicKey::new();
369-
let ptrs = [self.as_c_ptr(), other.as_c_ptr()];
378+
let ptrs : &[*const ffi::PublicKey] =
379+
std::mem::transmute::<&[&PublicKey], &[*const ffi::PublicKey]>(keys);
370380
if ffi::secp256k1_ec_pubkey_combine(
371381
ffi::secp256k1_context_no_precomp,
372382
&mut ret,
373383
ptrs.as_c_ptr(),
374-
2
384+
keys.len() as i32
375385
) == 1
376386
{
377387
Ok(PublicKey(ret))
@@ -794,6 +804,29 @@ mod test {
794804
assert_eq!(sum1.unwrap(), exp_sum);
795805
}
796806

807+
#[test]
808+
fn pubkey_combine_keys() {
809+
let compressed1 = PublicKey::from_slice(
810+
&hex!("0241cc121c419921942add6db6482fb36243faf83317c866d2a28d8c6d7089f7ba"),
811+
).unwrap();
812+
let compressed2 = PublicKey::from_slice(
813+
&hex!("02e6642fd69bd211f93f7f1f36ca51a26a5290eb2dd1b0d8279a87bb0d480c8443"),
814+
).unwrap();
815+
let compressed3 = PublicKey::from_slice(
816+
&hex!("03e74897d8644eb3e5b391ca2ab257aec2080f4d1a95cad57e454e47f021168eb0")
817+
).unwrap();
818+
let exp_sum = PublicKey::from_slice(
819+
&hex!("0252d73a47f66cf341e5651542f0348f452b7c793af62a6d8bff75ade703a451ad"),
820+
).unwrap();
821+
822+
let sum1 = PublicKey::combine_keys(&[&compressed1, &compressed2, &compressed3]);
823+
assert!(sum1.is_ok());
824+
let sum2 = PublicKey::combine_keys(&[&compressed1, &compressed2, &compressed3]);
825+
assert!(sum2.is_ok());
826+
assert_eq!(sum1, sum2);
827+
assert_eq!(sum1.unwrap(), exp_sum);
828+
}
829+
797830
#[test]
798831
fn pubkey_equal() {
799832
let pk1 = PublicKey::from_slice(

0 commit comments

Comments
 (0)