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