1use crate::types::JsonSignSessionKeyResponseV1;
2use blsful::{Bls12381G2Impl, PublicKey, Signature, SignatureSchemes, TimeCryptCiphertext};
3use eyre::Result;
4
5pub fn combine(
6 signature_shares: &[JsonSignSessionKeyResponseV1],
7) -> Result<Signature<Bls12381G2Impl>> {
8 combine_iter(signature_shares.iter())
9}
10
11pub fn combine_iter<I, T>(signature_shares: I) -> Result<Signature<Bls12381G2Impl>>
12where
13 I: Iterator<Item = T>,
14 T: core::borrow::Borrow<JsonSignSessionKeyResponseV1>,
15{
16 let shares = signature_shares
17 .map(|s| s.borrow().signature_share)
18 .collect::<Vec<_>>();
19 let sig = Signature::from_shares(&shares)?;
20 Ok(sig)
21}
22
23pub fn verify(
24 public_key: &[u8],
25 message: &[u8],
26 signature: &Signature<Bls12381G2Impl>,
27) -> Result<()> {
28 let pk = PublicKey::try_from(public_key)?;
29 signature.verify(&pk, message)?;
30 Ok(())
31}
32
33pub fn encrypt(encryption_key: &[u8], message: &[u8], identity: &[u8]) -> Result<Vec<u8>> {
34 let ek = PublicKey::<Bls12381G2Impl>::try_from(encryption_key)?;
35 let ciphertext =
36 ek.encrypt_time_lock(SignatureSchemes::ProofOfPossession, message, identity)?;
37 let ciphertext = serde_bare::to_vec(&ciphertext)?;
38 Ok(ciphertext)
39}
40
41pub fn decrypt(ciphertext: &[u8], decryption_key: &[u8]) -> Result<Vec<u8>> {
42 let dk = Signature::<Bls12381G2Impl>::try_from(decryption_key)?;
43 let ciphertext: TimeCryptCiphertext<Bls12381G2Impl> = serde_bare::from_slice(ciphertext)?;
44 let message =
45 Option::<Vec<u8>>::from(ciphertext.decrypt(&dk)).ok_or(eyre::eyre!("Unable to decrypt"))?;
46 Ok(message)
47}