1use thiserror::Error;
2use borsh::{BorshSerialize, BorshDeserialize};
3use std::collections::HashMap;
4use crate::types::{SecretKey, SecretDigest, Signature, Ciphertext};
5use race_api;
6#[cfg(feature = "serde")]
7use serde::{Serialize, Deserialize};
8
9#[derive(Debug, PartialEq, Eq, Clone, BorshSerialize, BorshDeserialize)]
10#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
11pub struct NodePublicKeyRaw {
12 pub rsa: String,
13 pub ec: String,
14}
15
16pub type EncryptorResult<T> = std::result::Result<T, EncryptorError>;
17
18#[derive(Error, Debug, PartialEq, Eq)]
19pub enum EncryptorError {
20 #[error("Key gen failed")]
21 KeyGenFailed,
22
23 #[error("Encode failed")]
24 EncodeFailed,
25
26 #[error("Decode failed")]
27 DecodeFailed,
28
29 #[error("Rsa encrypt failed")]
30 RsaEncryptFailed(String),
31
32 #[error("Rsa decrypt failed")]
33 RsaDecryptFailed(String),
34
35 #[error("Sign failed: {0}")]
36 SignFailed(String),
37
38 #[error("Invalid result: {0}")]
39 InvalidResult(String),
40
41 #[error("Verify failed: {0}")]
42 VerifyFailed(String),
43
44 #[error("Aes encrypt failed")]
45 AesEncryptFailed,
46
47 #[error("Aes decrypt failed")]
48 AesDecryptFailed,
49
50 #[error("Public key not found")]
51 PublicKeyNotfound,
52
53 #[error("Failed to import public key")]
54 ImportPublicKeyError,
55
56 #[error("Failed to export public key")]
57 ExportPublicKeyError,
58
59 #[error("Failed to import private key")]
60 ImportPrivateKeyError,
61
62 #[error("Failed to export private key")]
63 ExportPrivateKeyError,
64
65 #[error("Invalid nonce")]
66 InvalidNonce,
67
68 #[error("Add public key error")]
69 AddPublicKeyError,
70
71 #[error("Read public key error")]
72 ReadPublicKeyError,
73
74 #[error("Missing secrets")]
75 MissingSecret,
76
77 #[error("Invalid signature length: {0}")]
78 InvalidSignatureLength(usize),
79}
80
81impl From<EncryptorError> for race_api::error::Error {
82 fn from(e: EncryptorError) -> Self {
83 race_api::error::Error::CryptoError(e.to_string())
84 }
85}
86
87pub trait EncryptorT: std::fmt::Debug + Send + Sync {
88 fn add_public_key(&self, addr: String, raw: &NodePublicKeyRaw) -> EncryptorResult<()>;
89
90 fn export_public_key(&self, addr: Option<&str>) -> EncryptorResult<NodePublicKeyRaw>;
91
92 fn gen_secret(&self) -> SecretKey;
93
94 fn encrypt(&self, addr: Option<&str>, text: &[u8]) -> EncryptorResult<Vec<u8>>;
95
96 fn decrypt(&self, text: &[u8]) -> EncryptorResult<Vec<u8>>;
97
98 fn apply(&self, secret: &SecretKey, buf: &mut [u8]);
99
100 fn apply_multi(&self, secret: Vec<SecretKey>, buf: &mut [u8]);
101
102 fn sign_raw(&self, message: &[u8]) -> EncryptorResult<Vec<u8>>;
103
104 fn verify_raw(
105 &self,
106 addr: Option<&str>,
107 message: &[u8],
108 signature: &[u8],
109 ) -> EncryptorResult<()>;
110
111 fn sign(&self, message: &[u8], signer: String) -> EncryptorResult<Signature>;
112
113 fn verify(&self, message: &[u8], signature: &Signature) -> EncryptorResult<()>;
114
115 fn shuffle(&self, items: &mut Vec<Ciphertext>);
116
117 fn digest(&self, text: &[u8]) -> SecretDigest;
118
119 fn decrypt_with_secrets(
120 &self,
121 ciphertext_map: HashMap<usize, Ciphertext>,
122 mut secret_map: HashMap<usize, Vec<SecretKey>>,
123 valid_options: &[String],
124 ) -> EncryptorResult<HashMap<usize, String>> {
125 let mut ret = HashMap::new();
126 for (i, mut buf) in ciphertext_map.into_iter() {
127 if let Some(secrets) = secret_map.remove(&i) {
128 self.apply_multi(secrets, &mut buf);
129 let value = String::from_utf8(buf).or(Err(EncryptorError::DecodeFailed))?;
130 if !valid_options.contains(&value) {
131 return Err(EncryptorError::InvalidResult(value))?;
132 }
133 ret.insert(i, value);
134 } else {
135 return Err(EncryptorError::MissingSecret);
136 }
137 }
138 Ok(ret)
139 }
140}
141
142#[cfg(test)]
143pub mod tests {
144 use crate::types::{Ciphertext, SecretDigest, SecretKey, Signature};
145
146 use super::{EncryptorResult, EncryptorT, NodePublicKeyRaw};
147
148 #[derive(Debug, Default)]
149 pub struct DummyEncryptor {}
150
151 #[allow(unused)]
152 impl EncryptorT for DummyEncryptor {
153 fn add_public_key(&self, addr: String, raw: &NodePublicKeyRaw) -> EncryptorResult<()> {
154 Ok(())
155 }
156
157 fn export_public_key(&self, addr: Option<&str>) -> EncryptorResult<NodePublicKeyRaw> {
158 Ok(NodePublicKeyRaw {
159 rsa: "".into(),
160 ec: "".into(),
161 })
162 }
163
164 fn gen_secret(&self) -> SecretKey {
165 vec![0, 0, 0, 0]
166 }
167
168 fn encrypt(&self, addr: Option<&str>, text: &[u8]) -> EncryptorResult<Vec<u8>> {
169 Ok(vec![0, 0, 0, 0])
170 }
171
172 fn decrypt(&self, text: &[u8]) -> EncryptorResult<Vec<u8>> {
173 Ok(vec![0, 0, 0, 0])
174 }
175
176 fn apply(&self, secret: &SecretKey, buf: &mut [u8]) {}
177
178 fn apply_multi(&self, secret: Vec<SecretKey>, buf: &mut [u8]) {}
179
180 fn sign_raw(&self, message: &[u8]) -> EncryptorResult<Vec<u8>> {
181 Ok(vec![0, 0, 0, 0])
182 }
183
184 fn verify_raw(
185 &self,
186 addr: Option<&str>,
187 message: &[u8],
188 signature: &[u8],
189 ) -> EncryptorResult<()> {
190 Ok(())
191 }
192
193 fn sign(&self, message: &[u8], signer: String) -> EncryptorResult<Signature> {
194 Ok(Signature {
195 signer,
196 timestamp: 0,
197 signature: "".into(),
198 })
199 }
200
201 fn verify(&self, message: &[u8], signature: &Signature) -> EncryptorResult<()> {
202 Ok(())
203 }
204
205 fn shuffle(&self, items: &mut Vec<Ciphertext>) {}
206
207 fn digest(&self, text: &[u8]) -> SecretDigest {
208 vec![0, 1, 2, 3]
209 }
210 }
211}