1pub mod address;
4pub mod ecdsa;
5pub mod encrypt;
6pub mod hash;
7pub mod pow;
8pub mod vdf;
9pub mod vrf;
10
11use crate::error::{ChaincraftError, CryptoError, Result};
12use async_trait::async_trait;
13use ed25519_dalek::{Signer, Verifier};
14use k256::ecdsa::signature::Verifier as K256Verifier;
15use serde::{Deserialize, Serialize};
16use thiserror::Error;
17
18#[async_trait]
20pub trait KeylessCryptoPrimitive: Send + Sync {
21 type Input;
22 type Output;
23 type Challenge;
24 type Proof;
25
26 async fn compute(&self, input: Self::Input) -> Result<Self::Output>;
27 async fn create_proof(&self, challenge: Self::Challenge) -> Result<Self::Proof>;
28 async fn verify_proof(&self, challenge: Self::Challenge, proof: Self::Proof) -> Result<bool>;
29}
30
31#[async_trait]
33pub trait KeyedCryptoPrimitive: Send + Sync {
34 type PrivateKey;
35 type PublicKey;
36 type Input;
37 type Output;
38 type Message;
39 type Signature;
40
41 async fn generate_keypair(&self) -> Result<(Self::PrivateKey, Self::PublicKey)>;
42 async fn compute(&self, key: &Self::PrivateKey, input: Self::Input) -> Result<Self::Output>;
43 async fn verify(
44 &self,
45 key: &Self::PublicKey,
46 input: Self::Input,
47 output: &Self::Output,
48 ) -> Result<bool>;
49 async fn sign(
50 &self,
51 private_key: &Self::PrivateKey,
52 message: &Self::Message,
53 ) -> Result<Self::Signature>;
54}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub enum PublicKey {
59 Ed25519(ed25519_dalek::VerifyingKey),
60 Secp256k1(k256::PublicKey),
61}
62
63impl Serialize for PublicKey {
64 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
65 where
66 S: serde::Serializer,
67 {
68 match self {
69 PublicKey::Ed25519(key) => serializer.serialize_str(&hex::encode(key.as_bytes())),
70 PublicKey::Secp256k1(key) => {
71 serializer.serialize_str(&hex::encode(key.to_sec1_bytes()))
72 },
73 }
74 }
75}
76
77impl<'de> Deserialize<'de> for PublicKey {
78 fn deserialize<D>(deserializer: D) -> std::result::Result<PublicKey, D::Error>
79 where
80 D: serde::Deserializer<'de>,
81 {
82 let s = String::deserialize(deserializer)?;
83 let bytes = hex::decode(&s).map_err(serde::de::Error::custom)?;
84
85 if bytes.len() == 32 {
86 let key = ed25519_dalek::VerifyingKey::from_bytes(&bytes.try_into().unwrap())
88 .map_err(serde::de::Error::custom)?;
89 Ok(PublicKey::Ed25519(key))
90 } else if bytes.len() == 33 {
91 let key = k256::PublicKey::from_sec1_bytes(&bytes).map_err(serde::de::Error::custom)?;
93 Ok(PublicKey::Secp256k1(key))
94 } else {
95 Err(serde::de::Error::custom("Invalid public key length"))
96 }
97 }
98}
99
100impl PublicKey {
101 pub fn as_bytes(&self) -> Vec<u8> {
103 match self {
104 PublicKey::Ed25519(key) => key.as_bytes().to_vec(),
105 PublicKey::Secp256k1(key) => key.to_sec1_bytes().to_vec(),
106 }
107 }
108
109 pub fn to_hex(&self) -> String {
111 hex::encode(self.as_bytes())
112 }
113
114 pub fn from_hex(hex_str: &str, key_type: KeyType) -> Result<Self> {
116 let bytes = hex::decode(hex_str).map_err(|_| {
117 ChaincraftError::Crypto(crate::error::CryptoError::InvalidPublicKey {
118 reason: "Invalid hex encoding".to_string(),
119 })
120 })?;
121
122 match key_type {
123 KeyType::Ed25519 => {
124 let key_bytes: [u8; 32] = bytes.try_into().map_err(|_| {
125 ChaincraftError::Crypto(crate::error::CryptoError::InvalidPublicKey {
126 reason: "Invalid key length for Ed25519".to_string(),
127 })
128 })?;
129 let key = ed25519_dalek::VerifyingKey::from_bytes(&key_bytes).map_err(|_| {
130 ChaincraftError::Crypto(crate::error::CryptoError::InvalidPublicKey {
131 reason: "Invalid Ed25519 key".to_string(),
132 })
133 })?;
134 Ok(PublicKey::Ed25519(key))
135 },
136 KeyType::Secp256k1 => {
137 let key = k256::PublicKey::from_sec1_bytes(&bytes).map_err(|_| {
138 ChaincraftError::Crypto(crate::error::CryptoError::InvalidPublicKey {
139 reason: "Invalid Secp256k1 key".to_string(),
140 })
141 })?;
142 Ok(PublicKey::Secp256k1(key))
143 },
144 }
145 }
146
147 pub fn algorithm(&self) -> &'static str {
148 match self {
149 PublicKey::Ed25519(_) => "Ed25519",
150 PublicKey::Secp256k1(_) => "Secp256k1",
151 }
152 }
153
154 pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<bool> {
155 match (self, signature) {
156 (PublicKey::Ed25519(pk), Signature::Ed25519(sig)) => {
157 Ok(pk.verify(message, sig).is_ok())
158 },
159 (PublicKey::Secp256k1(pk), Signature::Secp256k1(sig)) => {
160 let verifying_key = k256::ecdsa::VerifyingKey::from(pk);
161 Ok(verifying_key.verify(message, sig).is_ok())
162 },
163 _ => Err(ChaincraftError::Crypto(CryptoError::InvalidSignature)),
164 }
165 }
166}
167
168#[derive(Debug, Clone)]
170pub enum PrivateKey {
171 Ed25519(ed25519_dalek::SigningKey),
172 Secp256k1(k256::SecretKey),
173}
174
175impl Serialize for PrivateKey {
176 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
177 where
178 S: serde::Serializer,
179 {
180 match self {
181 PrivateKey::Ed25519(key) => serializer.serialize_str(&hex::encode(key.as_bytes())),
182 PrivateKey::Secp256k1(key) => serializer.serialize_str(&hex::encode(key.to_bytes())),
183 }
184 }
185}
186
187impl<'de> Deserialize<'de> for PrivateKey {
188 fn deserialize<D>(deserializer: D) -> std::result::Result<PrivateKey, D::Error>
189 where
190 D: serde::Deserializer<'de>,
191 {
192 let s = String::deserialize(deserializer)?;
193 let bytes = hex::decode(&s).map_err(serde::de::Error::custom)?;
194
195 if bytes.len() == 32 {
196 let bytes_array: [u8; 32] = bytes
198 .clone()
199 .try_into()
200 .map_err(|_| serde::de::Error::custom("Invalid byte length conversion"))?;
201 let key = ed25519_dalek::SigningKey::from_bytes(&bytes_array);
202 Ok(PrivateKey::Ed25519(key))
203 } else {
204 Err(serde::de::Error::custom("Invalid private key length"))
205 }
206 }
207}
208
209impl PrivateKey {
210 pub fn public_key(&self) -> PublicKey {
212 match self {
213 PrivateKey::Ed25519(key) => PublicKey::Ed25519(key.verifying_key()),
214 PrivateKey::Secp256k1(key) => PublicKey::Secp256k1(key.public_key()),
215 }
216 }
217
218 pub fn to_hex(&self) -> String {
220 match self {
221 PrivateKey::Ed25519(key) => hex::encode(key.as_bytes()),
222 PrivateKey::Secp256k1(key) => hex::encode(key.to_bytes()),
223 }
224 }
225
226 pub fn from_hex(hex_str: &str, key_type: KeyType) -> Result<Self> {
228 let bytes = hex::decode(hex_str).map_err(|_| {
229 ChaincraftError::Crypto(CryptoError::InvalidPrivateKey {
230 reason: "Invalid hex encoding".to_string(),
231 })
232 })?;
233
234 match key_type {
235 KeyType::Ed25519 => {
236 let key_bytes: [u8; 32] = bytes.try_into().map_err(|_| {
237 ChaincraftError::Crypto(CryptoError::InvalidPrivateKey {
238 reason: "Invalid key length for Ed25519".to_string(),
239 })
240 })?;
241 let key = ed25519_dalek::SigningKey::from_bytes(&key_bytes);
242 Ok(PrivateKey::Ed25519(key))
243 },
244 KeyType::Secp256k1 => {
245 let key = k256::SecretKey::from_slice(&bytes).map_err(|_| {
246 ChaincraftError::Crypto(CryptoError::InvalidPrivateKey {
247 reason: "Invalid Secp256k1 key".to_string(),
248 })
249 })?;
250 Ok(PrivateKey::Secp256k1(key))
251 },
252 }
253 }
254
255 pub fn algorithm(&self) -> &'static str {
256 match self {
257 PrivateKey::Ed25519(_) => "Ed25519",
258 PrivateKey::Secp256k1(_) => "Secp256k1",
259 }
260 }
261
262 pub fn sign(&self, message: &[u8]) -> Result<Signature> {
263 match self {
264 PrivateKey::Ed25519(key) => {
265 let signature = key.sign(message);
266 Ok(Signature::Ed25519(signature))
267 },
268 PrivateKey::Secp256k1(key) => {
269 use k256::ecdsa::SigningKey;
270 let signing_key = SigningKey::from(key);
271 use k256::ecdsa::signature::Signer;
272 let signature = signing_key.sign(message);
273 Ok(Signature::Secp256k1(signature))
274 },
275 }
276 }
277}
278
279#[derive(Debug, Clone, PartialEq, Eq)]
281pub enum Signature {
282 Ed25519(ed25519_dalek::Signature),
283 Secp256k1(k256::ecdsa::Signature),
284}
285
286impl Serialize for Signature {
287 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
288 where
289 S: serde::Serializer,
290 {
291 match self {
292 Signature::Ed25519(sig) => serializer.serialize_str(&hex::encode(sig.to_bytes())),
293 Signature::Secp256k1(sig) => serializer.serialize_str(&hex::encode(sig.to_bytes())),
294 }
295 }
296}
297
298impl<'de> Deserialize<'de> for Signature {
299 fn deserialize<D>(deserializer: D) -> std::result::Result<Signature, D::Error>
300 where
301 D: serde::Deserializer<'de>,
302 {
303 let s = String::deserialize(deserializer)?;
304 let bytes = hex::decode(&s).map_err(serde::de::Error::custom)?;
305
306 if bytes.len() == 64 {
307 let bytes_array: [u8; 64] = bytes
309 .clone()
310 .try_into()
311 .map_err(|_| serde::de::Error::custom("Invalid byte length conversion"))?;
312 let sig = ed25519_dalek::Signature::from_bytes(&bytes_array);
313 Ok(Signature::Ed25519(sig))
314 } else if bytes.len() == 65 || bytes.len() == 71 {
315 match k256::ecdsa::Signature::from_der(&bytes)
317 .or_else(|_| k256::ecdsa::Signature::from_slice(&bytes))
318 {
319 Ok(sig) => Ok(Signature::Secp256k1(sig)),
320 Err(_) => Err(serde::de::Error::custom("Invalid Secp256k1 signature")),
321 }
322 } else {
323 Err(serde::de::Error::custom("Invalid signature length"))
324 }
325 }
326}
327
328impl Signature {
329 pub fn to_bytes(&self) -> Vec<u8> {
331 match self {
332 Signature::Ed25519(sig) => sig.to_bytes().to_vec(),
333 Signature::Secp256k1(sig) => sig.to_bytes().to_vec(),
334 }
335 }
336
337 pub fn to_hex(&self) -> String {
339 hex::encode(self.to_bytes())
340 }
341
342 pub fn from_hex(hex_str: &str, sig_type: KeyType) -> Result<Self> {
344 let bytes = hex::decode(hex_str)
345 .map_err(|_| ChaincraftError::Crypto(crate::error::CryptoError::InvalidSignature))?;
346
347 match sig_type {
348 KeyType::Ed25519 => {
349 let sig_bytes: [u8; 64] = bytes.try_into().map_err(|_| {
350 ChaincraftError::Crypto(crate::error::CryptoError::InvalidSignature)
351 })?;
352 let sig = ed25519_dalek::Signature::from_bytes(&sig_bytes);
353 Ok(Signature::Ed25519(sig))
354 },
355 KeyType::Secp256k1 => {
356 let sig = k256::ecdsa::Signature::from_slice(&bytes).map_err(|_| {
357 ChaincraftError::Crypto(crate::error::CryptoError::InvalidSignature)
358 })?;
359 Ok(Signature::Secp256k1(sig))
360 },
361 }
362 }
363
364 pub fn algorithm(&self) -> &'static str {
365 match self {
366 Signature::Ed25519(_) => "Ed25519",
367 Signature::Secp256k1(_) => "Secp256k1",
368 }
369 }
370}
371
372#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
374pub enum KeyType {
375 Ed25519,
376 Secp256k1,
377}
378
379impl KeyType {
380 pub fn as_str(&self) -> &'static str {
382 match self {
383 KeyType::Ed25519 => "ed25519",
384 KeyType::Secp256k1 => "secp256k1",
385 }
386 }
387}
388
389impl std::str::FromStr for KeyType {
390 type Err = ();
391
392 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
393 match s.to_lowercase().as_str() {
394 "ed25519" => Ok(KeyType::Ed25519),
395 "secp256k1" => Ok(KeyType::Secp256k1),
396 _ => Err(()),
397 }
398 }
399}
400
401pub mod utils {
403 use super::*;
404 use rand::rngs::OsRng;
405
406 pub fn generate_keypair(key_type: KeyType) -> Result<(PrivateKey, PublicKey)> {
408 let mut rng = OsRng;
409
410 match key_type {
411 KeyType::Ed25519 => {
412 let private_key = ed25519_dalek::SigningKey::generate(&mut rng);
413 let public_key = private_key.verifying_key();
414 Ok((PrivateKey::Ed25519(private_key), PublicKey::Ed25519(public_key)))
415 },
416 KeyType::Secp256k1 => {
417 let private_key = k256::SecretKey::random(&mut rng);
418 let public_key = private_key.public_key();
419 Ok((PrivateKey::Secp256k1(private_key), PublicKey::Secp256k1(public_key)))
420 },
421 }
422 }
423
424 pub fn sign_message(private_key: &PrivateKey, message: &[u8]) -> Result<Signature> {
426 match private_key {
427 PrivateKey::Ed25519(key) => {
428 let signature = key.sign(message);
429 Ok(Signature::Ed25519(signature))
430 },
431 PrivateKey::Secp256k1(key) => {
432 use k256::ecdsa::{signature::Signer, SigningKey};
433 let signing_key = SigningKey::from(key);
434 let signature = signing_key.sign(message);
435 Ok(Signature::Secp256k1(signature))
436 },
437 }
438 }
439
440 pub fn verify_signature(
442 public_key: &PublicKey,
443 message: &[u8],
444 signature: &Signature,
445 ) -> Result<bool> {
446 match (public_key, signature) {
447 (PublicKey::Ed25519(pk), Signature::Ed25519(sig)) => {
448 use ed25519_dalek::Verifier;
449 Ok(pk.verify(message, sig).is_ok())
450 },
451 (PublicKey::Secp256k1(pk), Signature::Secp256k1(sig)) => {
452 use k256::ecdsa::{signature::Verifier, VerifyingKey};
453 let verifying_key = VerifyingKey::from(pk);
454 Ok(verifying_key.verify(message, sig).is_ok())
455 },
456 _ => Err(ChaincraftError::Crypto(CryptoError::InvalidSignature)),
457 }
458 }
459}
460
461pub mod ed25519_utils {
463 use crate::error::{ChaincraftError, CryptoError, Result};
464 use ed25519_dalek::Signature as Ed25519Signature;
465
466 pub fn create_signature(bytes: &[u8; 64]) -> Result<Ed25519Signature> {
468 Ok(Ed25519Signature::from_bytes(bytes))
470 }
471}
472
473pub use address::Address;
475pub use ecdsa::EcdsaSignature;
476pub use hash::*;
477pub use pow::ProofOfWork;
478pub use vdf::VerifiableDelayFunction;
479pub use vrf::{ECDSAVRF, VerifiableRandomFunction};
480pub use encrypt::SymmetricEncryption;
481
482#[cfg(test)]
483mod tests {
484 use super::*;
485 use crate::error::{ChaincraftError, CryptoError, Result};
486
487 #[test]
488 fn test_key_generation() -> Result<()> {
489 Ok(())
491 }
492}