1use crate::{Array, BatchScheme, Error, Scheme};
2use commonware_utils::{hex, union_unique, SizedSerialize};
3use ed25519_consensus::{self, VerificationKey};
4use rand::{CryptoRng, Rng, RngCore};
5use std::borrow::Cow;
6use std::fmt::{Debug, Display};
7use std::hash::{Hash, Hasher};
8use std::ops::Deref;
9
10const PRIVATE_KEY_LENGTH: usize = 32;
11const PUBLIC_KEY_LENGTH: usize = 32;
12const SIGNATURE_LENGTH: usize = 64;
13
14#[derive(Clone)]
16pub struct Ed25519 {
17 signer: ed25519_consensus::SigningKey,
18 verifier: ed25519_consensus::VerificationKey,
19}
20
21impl Scheme for Ed25519 {
22 type PrivateKey = PrivateKey;
23 type PublicKey = PublicKey;
24 type Signature = Signature;
25
26 fn new<R: CryptoRng + Rng>(r: &mut R) -> Self {
27 let signer = ed25519_consensus::SigningKey::new(r);
28 let verifier = signer.verification_key();
29 Self { signer, verifier }
30 }
31
32 fn from(private_key: PrivateKey) -> Option<Self> {
33 let signer = private_key.key;
34 let verifier = signer.verification_key();
35 Some(Self { signer, verifier })
36 }
37
38 fn private_key(&self) -> PrivateKey {
39 PrivateKey::from(self.signer.clone())
40 }
41
42 fn public_key(&self) -> PublicKey {
43 PublicKey::from(self.verifier)
44 }
45
46 fn sign(&mut self, namespace: Option<&[u8]>, message: &[u8]) -> Signature {
47 let sig = match namespace {
48 Some(namespace) => self.signer.sign(&union_unique(namespace, message)),
49 None => self.signer.sign(message),
50 };
51 Signature::from(sig)
52 }
53
54 fn verify(
55 namespace: Option<&[u8]>,
56 message: &[u8],
57 public_key: &Self::PublicKey,
58 signature: &Self::Signature,
59 ) -> bool {
60 match namespace {
61 Some(namespace) => {
62 let payload = union_unique(namespace, message);
63 public_key
64 .key
65 .verify(&signature.signature, &payload)
66 .is_ok()
67 }
68 None => public_key.key.verify(&signature.signature, message).is_ok(),
69 }
70 }
71}
72
73pub struct Ed25519Batch {
75 verifier: ed25519_consensus::batch::Verifier,
76}
77
78impl BatchScheme for Ed25519Batch {
79 type PublicKey = PublicKey;
80 type Signature = Signature;
81
82 fn new() -> Self {
83 Ed25519Batch {
84 verifier: ed25519_consensus::batch::Verifier::new(),
85 }
86 }
87
88 fn add(
89 &mut self,
90 namespace: Option<&[u8]>,
91 message: &[u8],
92 public_key: &Self::PublicKey,
93 signature: &Self::Signature,
94 ) -> bool {
95 let payload = match namespace {
96 Some(namespace) => Cow::Owned(union_unique(namespace, message)),
97 None => Cow::Borrowed(message),
98 };
99 let item = ed25519_consensus::batch::Item::from((
100 public_key.key.into(),
101 signature.signature,
102 &payload,
103 ));
104 self.verifier.queue(item);
105 true
106 }
107
108 fn verify<R: RngCore + CryptoRng>(self, rng: &mut R) -> bool {
109 self.verifier.verify(rng).is_ok()
110 }
111}
112
113#[derive(Clone)]
115pub struct PrivateKey {
116 raw: [u8; PRIVATE_KEY_LENGTH],
117 key: ed25519_consensus::SigningKey,
118}
119
120impl Array for PrivateKey {
121 type Error = Error;
122}
123
124impl SizedSerialize for PrivateKey {
125 const SERIALIZED_LEN: usize = PRIVATE_KEY_LENGTH;
126}
127
128impl Eq for PrivateKey {}
129
130impl Hash for PrivateKey {
131 fn hash<H: Hasher>(&self, state: &mut H) {
132 self.raw.hash(state);
133 }
134}
135
136impl PartialEq for PrivateKey {
137 fn eq(&self, other: &Self) -> bool {
138 self.raw == other.raw
139 }
140}
141
142impl Ord for PrivateKey {
143 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
144 self.raw.cmp(&other.raw)
145 }
146}
147
148impl PartialOrd for PrivateKey {
149 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
150 Some(self.cmp(other))
151 }
152}
153
154impl AsRef<[u8]> for PrivateKey {
155 fn as_ref(&self) -> &[u8] {
156 &self.raw
157 }
158}
159
160impl Deref for PrivateKey {
161 type Target = [u8];
162 fn deref(&self) -> &[u8] {
163 &self.raw
164 }
165}
166
167impl From<ed25519_consensus::SigningKey> for PrivateKey {
168 fn from(key: ed25519_consensus::SigningKey) -> Self {
169 let raw = key.to_bytes();
170 Self { raw, key }
171 }
172}
173
174impl TryFrom<&[u8]> for PrivateKey {
175 type Error = Error;
176 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
177 let raw: [u8; PRIVATE_KEY_LENGTH] = value
178 .try_into()
179 .map_err(|_| Error::InvalidPrivateKeyLength)?;
180 let key = ed25519_consensus::SigningKey::from(raw);
181 Ok(Self { raw, key })
182 }
183}
184
185impl TryFrom<&Vec<u8>> for PrivateKey {
186 type Error = Error;
187 fn try_from(value: &Vec<u8>) -> Result<Self, Self::Error> {
188 Self::try_from(value.as_slice())
189 }
190}
191
192impl TryFrom<Vec<u8>> for PrivateKey {
193 type Error = Error;
194 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
195 Self::try_from(value.as_slice())
196 }
197}
198
199impl Debug for PrivateKey {
200 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
201 write!(f, "{}", hex(&self.raw))
202 }
203}
204
205impl Display for PrivateKey {
206 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
207 write!(f, "{}", hex(&self.raw))
208 }
209}
210
211#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
213pub struct PublicKey {
214 raw: [u8; PUBLIC_KEY_LENGTH],
215 key: ed25519_consensus::VerificationKey,
216}
217
218impl Array for PublicKey {
219 type Error = Error;
220}
221
222impl SizedSerialize for PublicKey {
223 const SERIALIZED_LEN: usize = PUBLIC_KEY_LENGTH;
224}
225
226impl AsRef<[u8]> for PublicKey {
227 fn as_ref(&self) -> &[u8] {
228 &self.raw
229 }
230}
231
232impl Deref for PublicKey {
233 type Target = [u8];
234 fn deref(&self) -> &[u8] {
235 &self.raw
236 }
237}
238
239impl From<VerificationKey> for PublicKey {
240 fn from(key: VerificationKey) -> Self {
241 let raw = key.to_bytes();
242 Self { raw, key }
243 }
244}
245
246impl TryFrom<&[u8]> for PublicKey {
247 type Error = Error;
248 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
249 let raw: [u8; PUBLIC_KEY_LENGTH] = value
250 .try_into()
251 .map_err(|_| Error::InvalidPublicKeyLength)?;
252 let key = VerificationKey::try_from(value).map_err(|_| Error::InvalidPublicKey)?;
253 Ok(Self { raw, key })
254 }
255}
256
257impl TryFrom<&Vec<u8>> for PublicKey {
258 type Error = Error;
259 fn try_from(value: &Vec<u8>) -> Result<Self, Self::Error> {
260 Self::try_from(value.as_slice())
261 }
262}
263
264impl TryFrom<Vec<u8>> for PublicKey {
265 type Error = Error;
266 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
267 Self::try_from(value.as_slice())
268 }
269}
270
271impl Debug for PublicKey {
272 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
273 write!(f, "{}", hex(&self.raw))
274 }
275}
276
277impl Display for PublicKey {
278 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279 write!(f, "{}", hex(&self.raw))
280 }
281}
282
283#[derive(Clone, Eq, PartialEq)]
285pub struct Signature {
286 raw: [u8; SIGNATURE_LENGTH],
287 signature: ed25519_consensus::Signature,
288}
289
290impl Array for Signature {
291 type Error = Error;
292}
293
294impl SizedSerialize for Signature {
295 const SERIALIZED_LEN: usize = SIGNATURE_LENGTH;
296}
297
298impl Hash for Signature {
299 fn hash<H: Hasher>(&self, state: &mut H) {
300 self.raw.hash(state);
301 }
302}
303
304impl Ord for Signature {
305 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
306 self.raw.cmp(&other.raw)
307 }
308}
309
310impl PartialOrd for Signature {
311 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
312 Some(self.cmp(other))
313 }
314}
315
316impl AsRef<[u8]> for Signature {
317 fn as_ref(&self) -> &[u8] {
318 &self.raw
319 }
320}
321
322impl Deref for Signature {
323 type Target = [u8];
324 fn deref(&self) -> &[u8] {
325 &self.raw
326 }
327}
328
329impl From<ed25519_consensus::Signature> for Signature {
330 fn from(value: ed25519_consensus::Signature) -> Self {
331 let raw = value.to_bytes();
332 Self {
333 raw,
334 signature: value,
335 }
336 }
337}
338
339impl TryFrom<&[u8]> for Signature {
340 type Error = Error;
341 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
342 let raw: [u8; SIGNATURE_LENGTH] = value
343 .try_into()
344 .map_err(|_| Error::InvalidSignatureLength)?;
345 let signature = ed25519_consensus::Signature::from(raw);
346 Ok(Self { raw, signature })
347 }
348}
349
350impl TryFrom<&Vec<u8>> for Signature {
351 type Error = Error;
352 fn try_from(value: &Vec<u8>) -> Result<Self, Self::Error> {
353 Self::try_from(value.as_slice())
354 }
355}
356
357impl TryFrom<Vec<u8>> for Signature {
358 type Error = Error;
359 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
360 Self::try_from(value.as_slice())
361 }
362}
363
364impl Debug for Signature {
365 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
366 write!(f, "{}", hex(&self.raw))
367 }
368}
369
370impl Display for Signature {
371 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
372 write!(f, "{}", hex(&self.raw))
373 }
374}
375
376#[cfg(test)]
378mod tests {
379 use super::*;
380 use rand::rngs::OsRng;
381
382 fn test_sign_and_verify(
383 private_key: PrivateKey,
384 public_key: PublicKey,
385 message: &[u8],
386 signature: Signature,
387 ) {
388 let mut signer = <Ed25519 as Scheme>::from(private_key).unwrap();
389 let computed_signature = signer.sign(None, message);
390 assert_eq!(computed_signature, signature);
391 assert!(Ed25519::verify(
392 None,
393 message,
394 &PublicKey::try_from(public_key.to_vec()).unwrap(),
395 &computed_signature
396 ));
397 }
398
399 fn parse_private_key(private_key: &str) -> PrivateKey {
400 PrivateKey::try_from(commonware_utils::from_hex_formatted(private_key).unwrap()).unwrap()
401 }
402
403 fn parse_public_key(public_key: &str) -> PublicKey {
404 PublicKey::try_from(commonware_utils::from_hex_formatted(public_key).unwrap()).unwrap()
405 }
406
407 fn parse_signature(signature: &str) -> Signature {
408 Signature::try_from(commonware_utils::from_hex_formatted(signature).unwrap()).unwrap()
409 }
410
411 fn vector_1() -> (PrivateKey, PublicKey, Vec<u8>, Signature) {
412 (
413 parse_private_key(
415 "
416 9d61b19deffd5a60ba844af492ec2cc4
417 4449c5697b326919703bac031cae7f60
418 ",
419 ),
420 parse_public_key(
422 "
423 d75a980182b10ab7d54bfed3c964073a
424 0ee172f3daa62325af021a68f707511a
425 ",
426 ),
427 b"".to_vec(),
429 parse_signature(
431 "
432 e5564300c360ac729086e2cc806e828a
433 84877f1eb8e5d974d873e06522490155
434 5fb8821590a33bacc61e39701cf9b46b
435 d25bf5f0595bbe24655141438e7a100b
436 ",
437 ),
438 )
439 }
440
441 fn vector_2() -> (PrivateKey, PublicKey, Vec<u8>, Signature) {
442 (
443 parse_private_key(
445 "
446 4ccd089b28ff96da9db6c346ec114e0f
447 5b8a319f35aba624da8cf6ed4fb8a6fb
448 ",
449 ),
450 parse_public_key(
452 "
453 3d4017c3e843895a92b70aa74d1b7ebc
454 9c982ccf2ec4968cc0cd55f12af4660c
455 ",
456 ),
457 [0x72].to_vec(),
459 parse_signature(
461 "
462 92a009a9f0d4cab8720e820b5f642540
463 a2b27b5416503f8fb3762223ebdb69da
464 085ac1e43e15996e458f3613d0f11d8c
465 387b2eaeb4302aeeb00d291612bb0c00
466 ",
467 ),
468 )
469 }
470
471 #[test]
472 fn rfc8032_test_vector_1() {
473 let (private_key, public_key, message, signature) = vector_1();
474 test_sign_and_verify(private_key, public_key, &message, signature)
475 }
476
477 #[test]
479 #[should_panic]
480 fn bad_signature() {
481 let (private_key, public_key, message, _) = vector_1();
482 let mut signer = <Ed25519 as Scheme>::new(&mut OsRng);
483 let bad_signature = signer.sign(None, message.as_ref());
484 test_sign_and_verify(private_key, public_key, &message, bad_signature);
485 }
486
487 #[test]
489 #[should_panic]
490 fn different_message() {
491 let (private_key, public_key, _, signature) = vector_1();
492 let different_message = b"this is a different message".to_vec();
493 test_sign_and_verify(private_key, public_key, &different_message, signature);
494 }
495
496 #[test]
497 fn rfc8032_test_vector_2() {
498 let (private_key, public_key, message, signature) = vector_2();
499 test_sign_and_verify(private_key, public_key, &message, signature)
500 }
501
502 #[test]
503 fn rfc8032_test_vector_3() {
504 let private_key = parse_private_key(
505 "
506 c5aa8df43f9f837bedb7442f31dcb7b1
507 66d38535076f094b85ce3a2e0b4458f7
508 ",
509 );
510 let public_key = parse_public_key(
511 "
512 fc51cd8e6218a1a38da47ed00230f058
513 0816ed13ba3303ac5deb911548908025
514 ",
515 );
516 let message: [u8; 2] = [0xaf, 0x82];
517 let signature = parse_signature(
518 "
519 6291d657deec24024827e69c3abe01a3
520 0ce548a284743a445e3680d7db5ac3ac
521 18ff9b538d16f290ae67f760984dc659
522 4a7c15e9716ed28dc027beceea1ec40a
523 ",
524 );
525 test_sign_and_verify(private_key, public_key, &message, signature)
526 }
527
528 #[test]
529 fn rfc8032_test_vector_1024() {
530 let private_key = parse_private_key(
531 "
532 f5e5767cf153319517630f226876b86c
533 8160cc583bc013744c6bf255f5cc0ee5
534 ",
535 );
536 let public_key = parse_public_key(
537 "
538 278117fc144c72340f67d0f2316e8386
539 ceffbf2b2428c9c51fef7c597f1d426e
540 ",
541 );
542 let message = commonware_utils::from_hex_formatted(
543 "
544 08b8b2b733424243760fe426a4b54908
545 632110a66c2f6591eabd3345e3e4eb98
546 fa6e264bf09efe12ee50f8f54e9f77b1
547 e355f6c50544e23fb1433ddf73be84d8
548 79de7c0046dc4996d9e773f4bc9efe57
549 38829adb26c81b37c93a1b270b20329d
550 658675fc6ea534e0810a4432826bf58c
551 941efb65d57a338bbd2e26640f89ffbc
552 1a858efcb8550ee3a5e1998bd177e93a
553 7363c344fe6b199ee5d02e82d522c4fe
554 ba15452f80288a821a579116ec6dad2b
555 3b310da903401aa62100ab5d1a36553e
556 06203b33890cc9b832f79ef80560ccb9
557 a39ce767967ed628c6ad573cb116dbef
558 efd75499da96bd68a8a97b928a8bbc10
559 3b6621fcde2beca1231d206be6cd9ec7
560 aff6f6c94fcd7204ed3455c68c83f4a4
561 1da4af2b74ef5c53f1d8ac70bdcb7ed1
562 85ce81bd84359d44254d95629e9855a9
563 4a7c1958d1f8ada5d0532ed8a5aa3fb2
564 d17ba70eb6248e594e1a2297acbbb39d
565 502f1a8c6eb6f1ce22b3de1a1f40cc24
566 554119a831a9aad6079cad88425de6bd
567 e1a9187ebb6092cf67bf2b13fd65f270
568 88d78b7e883c8759d2c4f5c65adb7553
569 878ad575f9fad878e80a0c9ba63bcbcc
570 2732e69485bbc9c90bfbd62481d9089b
571 eccf80cfe2df16a2cf65bd92dd597b07
572 07e0917af48bbb75fed413d238f5555a
573 7a569d80c3414a8d0859dc65a46128ba
574 b27af87a71314f318c782b23ebfe808b
575 82b0ce26401d2e22f04d83d1255dc51a
576 ddd3b75a2b1ae0784504df543af8969b
577 e3ea7082ff7fc9888c144da2af58429e
578 c96031dbcad3dad9af0dcbaaaf268cb8
579 fcffead94f3c7ca495e056a9b47acdb7
580 51fb73e666c6c655ade8297297d07ad1
581 ba5e43f1bca32301651339e22904cc8c
582 42f58c30c04aafdb038dda0847dd988d
583 cda6f3bfd15c4b4c4525004aa06eeff8
584 ca61783aacec57fb3d1f92b0fe2fd1a8
585 5f6724517b65e614ad6808d6f6ee34df
586 f7310fdc82aebfd904b01e1dc54b2927
587 094b2db68d6f903b68401adebf5a7e08
588 d78ff4ef5d63653a65040cf9bfd4aca7
589 984a74d37145986780fc0b16ac451649
590 de6188a7dbdf191f64b5fc5e2ab47b57
591 f7f7276cd419c17a3ca8e1b939ae49e4
592 88acba6b965610b5480109c8b17b80e1
593 b7b750dfc7598d5d5011fd2dcc5600a3
594 2ef5b52a1ecc820e308aa342721aac09
595 43bf6686b64b2579376504ccc493d97e
596 6aed3fb0f9cd71a43dd497f01f17c0e2
597 cb3797aa2a2f256656168e6c496afc5f
598 b93246f6b1116398a346f1a641f3b041
599 e989f7914f90cc2c7fff357876e506b5
600 0d334ba77c225bc307ba537152f3f161
601 0e4eafe595f6d9d90d11faa933a15ef1
602 369546868a7f3a45a96768d40fd9d034
603 12c091c6315cf4fde7cb68606937380d
604 b2eaaa707b4c4185c32eddcdd306705e
605 4dc1ffc872eeee475a64dfac86aba41c
606 0618983f8741c5ef68d3a101e8a3b8ca
607 c60c905c15fc910840b94c00a0b9d0
608 ",
609 )
610 .unwrap();
611 let signature = parse_signature(
612 "
613 0aab4c900501b3e24d7cdf4663326a3a
614 87df5e4843b2cbdb67cbf6e460fec350
615 aa5371b1508f9f4528ecea23c436d94b
616 5e8fcd4f681e30a6ac00a9704a188a03
617 ",
618 );
619 test_sign_and_verify(private_key, public_key, &message, signature)
620 }
621
622 #[test]
623 fn rfc8032_test_vector_sha() {
624 let private_key = commonware_utils::from_hex_formatted(
625 "
626 833fe62409237b9d62ec77587520911e
627 9a759cec1d19755b7da901b96dca3d42
628 ",
629 )
630 .unwrap();
631 let public_key = commonware_utils::from_hex_formatted(
632 "
633 ec172b93ad5e563bf4932c70e1245034
634 c35467ef2efd4d64ebf819683467e2bf
635 ",
636 )
637 .unwrap();
638 let message = commonware_utils::from_hex_formatted(
639 "
640 ddaf35a193617abacc417349ae204131
641 12e6fa4e89a97ea20a9eeee64b55d39a
642 2192992a274fc1a836ba3c23a3feebbd
643 454d4423643ce80e2a9ac94fa54ca49f
644 ",
645 )
646 .unwrap();
647 let signature = commonware_utils::from_hex_formatted(
648 "
649 dc2a4459e7369633a52b1bf277839a00
650 201009a3efbf3ecb69bea2186c26b589
651 09351fc9ac90b3ecfdfbc7c66431e030
652 3dca179c138ac17ad9bef1177331a704
653 ",
654 )
655 .unwrap();
656 test_sign_and_verify(
657 PrivateKey::try_from(private_key).unwrap(),
658 PublicKey::try_from(public_key).unwrap(),
659 &message,
660 Signature::try_from(signature).unwrap(),
661 )
662 }
663
664 #[test]
665 fn batch_verify_valid() {
666 let v1 = vector_1();
667 let v2 = vector_2();
668 let mut batch = Ed25519Batch::new();
669 assert!(batch.add(None, &v1.2, &v1.1, &v1.3));
670 assert!(batch.add(None, &v2.2, &v2.1, &v2.3));
671 assert!(batch.verify(&mut rand::thread_rng()));
672 }
673
674 #[test]
675 fn batch_verify_invalid() {
676 let v1 = vector_1();
677 let v2 = vector_2();
678 let mut bad_signature = v2.3.to_vec();
679 bad_signature[3] = 0xff;
680
681 let mut batch = Ed25519Batch::new();
682 assert!(batch.add(None, &v1.2, &v1.1, &v1.3));
683 assert!(batch.add(
684 None,
685 &v2.2,
686 &v2.1,
687 &Signature::try_from(bad_signature).unwrap()
688 ));
689 assert!(!batch.verify(&mut rand::thread_rng()));
690 }
691}