1#[cfg(feature = "full_crypto")]
23use tetcore_std::vec::Vec;
24
25use crate::{hash::H256, hash::H512};
26use codec::{Encode, Decode};
27
28#[cfg(feature = "full_crypto")]
29use blake2_rfc;
30#[cfg(feature = "full_crypto")]
31use core::convert::TryFrom;
32#[cfg(feature = "full_crypto")]
33use ed25519_dalek::{Signer as _, Verifier as _};
34#[cfg(feature = "std")]
35use tetcore_bip39::seed_from_entropy;
36#[cfg(feature = "std")]
37use bip39::{Mnemonic, Language, MnemonicType};
38#[cfg(feature = "full_crypto")]
39use crate::crypto::{Pair as TraitPair, DeriveJunction, SecretStringError};
40#[cfg(feature = "std")]
41use crate::crypto::Ss58Codec;
42#[cfg(feature = "std")]
43use serde::{de, Serializer, Serialize, Deserializer, Deserialize};
44use crate::crypto::{Public as TraitPublic, CryptoTypePublicPair, UncheckedFrom, CryptoType, Derive, CryptoTypeId};
45use tp_runtime_interface::pass_by::PassByInner;
46use tetcore_std::ops::Deref;
47
48pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"ed25");
50
51#[cfg(feature = "full_crypto")]
55type Seed = [u8; 32];
56
57#[cfg_attr(feature = "full_crypto", derive(Hash))]
59#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Encode, Decode, Default, PassByInner)]
60pub struct Public(pub [u8; 32]);
61
62#[cfg(feature = "full_crypto")]
64pub struct Pair(ed25519_dalek::Keypair);
65
66#[cfg(feature = "full_crypto")]
67impl Clone for Pair {
68 fn clone(&self) -> Self {
69 Pair(ed25519_dalek::Keypair {
70 public: self.0.public.clone(),
71 secret: ed25519_dalek::SecretKey::from_bytes(self.0.secret.as_bytes())
72 .expect("key is always the correct size; qed")
73 })
74 }
75}
76
77impl AsRef<[u8; 32]> for Public {
78 fn as_ref(&self) -> &[u8; 32] {
79 &self.0
80 }
81}
82
83impl AsRef<[u8]> for Public {
84 fn as_ref(&self) -> &[u8] {
85 &self.0[..]
86 }
87}
88
89impl AsMut<[u8]> for Public {
90 fn as_mut(&mut self) -> &mut [u8] {
91 &mut self.0[..]
92 }
93}
94
95impl Deref for Public {
96 type Target = [u8];
97
98 fn deref(&self) -> &Self::Target {
99 &self.0
100 }
101}
102
103impl tetcore_std::convert::TryFrom<&[u8]> for Public {
104 type Error = ();
105
106 fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
107 if data.len() == 32 {
108 let mut inner = [0u8; 32];
109 inner.copy_from_slice(data);
110 Ok(Public(inner))
111 } else {
112 Err(())
113 }
114 }
115}
116
117impl From<Public> for [u8; 32] {
118 fn from(x: Public) -> Self {
119 x.0
120 }
121}
122
123#[cfg(feature = "full_crypto")]
124impl From<Pair> for Public {
125 fn from(x: Pair) -> Self {
126 x.public()
127 }
128}
129
130impl From<Public> for H256 {
131 fn from(x: Public) -> Self {
132 x.0.into()
133 }
134}
135
136#[cfg(feature = "std")]
137impl std::str::FromStr for Public {
138 type Err = crate::crypto::PublicError;
139
140 fn from_str(s: &str) -> Result<Self, Self::Err> {
141 Self::from_ss58check(s)
142 }
143}
144
145impl UncheckedFrom<[u8; 32]> for Public {
146 fn unchecked_from(x: [u8; 32]) -> Self {
147 Public::from_raw(x)
148 }
149}
150
151impl UncheckedFrom<H256> for Public {
152 fn unchecked_from(x: H256) -> Self {
153 Public::from_h256(x)
154 }
155}
156
157#[cfg(feature = "std")]
158impl std::fmt::Display for Public {
159 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
160 write!(f, "{}", self.to_ss58check())
161 }
162}
163
164impl tetcore_std::fmt::Debug for Public {
165 #[cfg(feature = "std")]
166 fn fmt(&self, f: &mut tetcore_std::fmt::Formatter) -> tetcore_std::fmt::Result {
167 let s = self.to_ss58check();
168 write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
169 }
170
171 #[cfg(not(feature = "std"))]
172 fn fmt(&self, _: &mut tetcore_std::fmt::Formatter) -> tetcore_std::fmt::Result {
173 Ok(())
174 }
175}
176
177#[cfg(feature = "std")]
178impl Serialize for Public {
179 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
180 serializer.serialize_str(&self.to_ss58check())
181 }
182}
183
184#[cfg(feature = "std")]
185impl<'de> Deserialize<'de> for Public {
186 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
187 Public::from_ss58check(&String::deserialize(deserializer)?)
188 .map_err(|e| de::Error::custom(format!("{:?}", e)))
189 }
190}
191
192#[derive(Encode, Decode, PassByInner)]
194pub struct Signature(pub [u8; 64]);
195
196impl tetcore_std::convert::TryFrom<&[u8]> for Signature {
197 type Error = ();
198
199 fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
200 if data.len() == 64 {
201 let mut inner = [0u8; 64];
202 inner.copy_from_slice(data);
203 Ok(Signature(inner))
204 } else {
205 Err(())
206 }
207 }
208}
209
210#[cfg(feature = "std")]
211impl Serialize for Signature {
212 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
213 serializer.serialize_str(&hex::encode(self))
214 }
215}
216
217#[cfg(feature = "std")]
218impl<'de> Deserialize<'de> for Signature {
219 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
220 let signature_hex = hex::decode(&String::deserialize(deserializer)?)
221 .map_err(|e| de::Error::custom(format!("{:?}", e)))?;
222 Ok(Signature::try_from(signature_hex.as_ref())
223 .map_err(|e| de::Error::custom(format!("{:?}", e)))?)
224 }
225}
226
227impl Clone for Signature {
228 fn clone(&self) -> Self {
229 let mut r = [0u8; 64];
230 r.copy_from_slice(&self.0[..]);
231 Signature(r)
232 }
233}
234
235impl Default for Signature {
236 fn default() -> Self {
237 Signature([0u8; 64])
238 }
239}
240
241impl PartialEq for Signature {
242 fn eq(&self, b: &Self) -> bool {
243 self.0[..] == b.0[..]
244 }
245}
246
247impl Eq for Signature {}
248
249impl From<Signature> for H512 {
250 fn from(v: Signature) -> H512 {
251 H512::from(v.0)
252 }
253}
254
255impl From<Signature> for [u8; 64] {
256 fn from(v: Signature) -> [u8; 64] {
257 v.0
258 }
259}
260
261impl AsRef<[u8; 64]> for Signature {
262 fn as_ref(&self) -> &[u8; 64] {
263 &self.0
264 }
265}
266
267impl AsRef<[u8]> for Signature {
268 fn as_ref(&self) -> &[u8] {
269 &self.0[..]
270 }
271}
272
273impl AsMut<[u8]> for Signature {
274 fn as_mut(&mut self) -> &mut [u8] {
275 &mut self.0[..]
276 }
277}
278
279impl tetcore_std::fmt::Debug for Signature {
280 #[cfg(feature = "std")]
281 fn fmt(&self, f: &mut tetcore_std::fmt::Formatter) -> tetcore_std::fmt::Result {
282 write!(f, "{}", crate::hexdisplay::HexDisplay::from(&self.0))
283 }
284
285 #[cfg(not(feature = "std"))]
286 fn fmt(&self, _: &mut tetcore_std::fmt::Formatter) -> tetcore_std::fmt::Result {
287 Ok(())
288 }
289}
290
291#[cfg(feature = "full_crypto")]
292impl tetcore_std::hash::Hash for Signature {
293 fn hash<H: tetcore_std::hash::Hasher>(&self, state: &mut H) {
294 tetcore_std::hash::Hash::hash(&self.0[..], state);
295 }
296}
297
298impl Signature {
299 pub fn from_raw(data: [u8; 64]) -> Signature {
304 Signature(data)
305 }
306
307 pub fn from_slice(data: &[u8]) -> Self {
312 let mut r = [0u8; 64];
313 r.copy_from_slice(data);
314 Signature(r)
315 }
316
317 pub fn from_h512(v: H512) -> Signature {
322 Signature(v.into())
323 }
324}
325
326#[cfg(feature = "std")]
328#[derive(PartialEq, Eq, Clone, Debug, Encode, Decode)]
329pub struct LocalizedSignature {
330 pub signer: Public,
332 pub signature: Signature,
334}
335
336#[cfg(feature = "std")]
338#[derive(Clone, Copy, Eq, PartialEq, Debug, thiserror::Error)]
339pub enum PublicError {
340 #[error("Base 58 requirement is violated")]
342 BadBase58,
343 #[error("Length is bad")]
345 BadLength,
346 #[error("Unknown version")]
348 UnknownVersion,
349 #[error("Invalid checksum")]
351 InvalidChecksum,
352}
353
354impl Public {
355 pub fn from_raw(data: [u8; 32]) -> Self {
360 Public(data)
361 }
362
363 pub fn from_h256(x: H256) -> Self {
368 Public(x.into())
369 }
370
371 pub fn as_array_ref(&self) -> &[u8; 32] {
373 self.as_ref()
374 }
375}
376
377impl TraitPublic for Public {
378 fn from_slice(data: &[u8]) -> Self {
383 let mut r = [0u8; 32];
384 r.copy_from_slice(data);
385 Public(r)
386 }
387
388 fn to_public_crypto_pair(&self) -> CryptoTypePublicPair {
389 CryptoTypePublicPair(CRYPTO_ID, self.to_raw_vec())
390 }
391}
392
393impl Derive for Public {}
394
395impl From<Public> for CryptoTypePublicPair {
396 fn from(key: Public) -> Self {
397 (&key).into()
398 }
399}
400
401impl From<&Public> for CryptoTypePublicPair {
402 fn from(key: &Public) -> Self {
403 CryptoTypePublicPair(CRYPTO_ID, key.to_raw_vec())
404 }
405}
406
407#[cfg(feature = "full_crypto")]
409fn derive_hard_junction(secret_seed: &Seed, cc: &[u8; 32]) -> Seed {
410 ("Ed25519HDKD", secret_seed, cc).using_encoded(|data| {
411 let mut res = [0u8; 32];
412 res.copy_from_slice(blake2_rfc::blake2b::blake2b(32, &[], data).as_bytes());
413 res
414 })
415}
416
417#[cfg(feature = "full_crypto")]
419pub enum DeriveError {
420 SoftKeyInPath,
422}
423
424#[cfg(feature = "full_crypto")]
425impl TraitPair for Pair {
426 type Public = Public;
427 type Seed = Seed;
428 type Signature = Signature;
429 type DeriveError = DeriveError;
430
431 #[cfg(feature = "std")]
435 fn generate_with_phrase(password: Option<&str>) -> (Pair, String, Seed) {
436 let mnemonic = Mnemonic::new(MnemonicType::Words12, Language::English);
437 let phrase = mnemonic.phrase();
438 let (pair, seed) = Self::from_phrase(phrase, password)
439 .expect("All phrases generated by Mnemonic are valid; qed");
440 (
441 pair,
442 phrase.to_owned(),
443 seed,
444 )
445 }
446
447 #[cfg(feature = "std")]
449 fn from_phrase(phrase: &str, password: Option<&str>) -> Result<(Pair, Seed), SecretStringError> {
450 let big_seed = seed_from_entropy(
451 Mnemonic::from_phrase(phrase, Language::English)
452 .map_err(|_| SecretStringError::InvalidPhrase)?.entropy(),
453 password.unwrap_or(""),
454 ).map_err(|_| SecretStringError::InvalidSeed)?;
455 let mut seed = Seed::default();
456 seed.copy_from_slice(&big_seed[0..32]);
457 Self::from_seed_slice(&big_seed[0..32]).map(|x| (x, seed))
458 }
459
460 fn from_seed(seed: &Seed) -> Pair {
464 Self::from_seed_slice(&seed[..]).expect("seed has valid length; qed")
465 }
466
467 fn from_seed_slice(seed_slice: &[u8]) -> Result<Pair, SecretStringError> {
472 let secret = ed25519_dalek::SecretKey::from_bytes(seed_slice)
473 .map_err(|_| SecretStringError::InvalidSeedLength)?;
474 let public = ed25519_dalek::PublicKey::from(&secret);
475 Ok(Pair(ed25519_dalek::Keypair { secret, public }))
476 }
477
478 fn derive<Iter: Iterator<Item=DeriveJunction>>(&self,
480 path: Iter,
481 _seed: Option<Seed>,
482 ) -> Result<(Pair, Option<Seed>), DeriveError> {
483 let mut acc = self.0.secret.to_bytes();
484 for j in path {
485 match j {
486 DeriveJunction::Soft(_cc) => return Err(DeriveError::SoftKeyInPath),
487 DeriveJunction::Hard(cc) => acc = derive_hard_junction(&acc, &cc),
488 }
489 }
490 Ok((Self::from_seed(&acc), Some(acc)))
491 }
492
493 fn public(&self) -> Public {
495 let mut r = [0u8; 32];
496 let pk = self.0.public.as_bytes();
497 r.copy_from_slice(pk);
498 Public(r)
499 }
500
501 fn sign(&self, message: &[u8]) -> Signature {
503 let r = self.0.sign(message).to_bytes();
504 Signature::from_raw(r)
505 }
506
507 fn verify<M: AsRef<[u8]>>(sig: &Self::Signature, message: M, pubkey: &Self::Public) -> bool {
509 Self::verify_weak(&sig.0[..], message.as_ref(), pubkey)
510 }
511
512 fn verify_weak<P: AsRef<[u8]>, M: AsRef<[u8]>>(sig: &[u8], message: M, pubkey: P) -> bool {
517 let public_key = match ed25519_dalek::PublicKey::from_bytes(pubkey.as_ref()) {
518 Ok(pk) => pk,
519 Err(_) => return false,
520 };
521
522 let sig = match ed25519_dalek::Signature::try_from(sig) {
523 Ok(s) => s,
524 Err(_) => return false
525 };
526
527 match public_key.verify(message.as_ref(), &sig) {
528 Ok(_) => true,
529 _ => false,
530 }
531 }
532
533 fn to_raw_vec(&self) -> Vec<u8> {
535 self.seed().to_vec()
536 }
537}
538
539#[cfg(feature = "full_crypto")]
540impl Pair {
541 pub fn seed(&self) -> &Seed {
543 self.0.secret.as_bytes()
544 }
545
546 #[cfg(feature = "std")]
549 pub fn from_legacy_string(s: &str, password_override: Option<&str>) -> Pair {
550 Self::from_string(s, password_override).unwrap_or_else(|_| {
551 let mut padded_seed: Seed = [' ' as u8; 32];
552 let len = s.len().min(32);
553 padded_seed[..len].copy_from_slice(&s.as_bytes()[..len]);
554 Self::from_seed(&padded_seed)
555 })
556 }
557}
558
559impl CryptoType for Public {
560 #[cfg(feature = "full_crypto")]
561 type Pair = Pair;
562}
563
564impl CryptoType for Signature {
565 #[cfg(feature = "full_crypto")]
566 type Pair = Pair;
567}
568
569#[cfg(feature = "full_crypto")]
570impl CryptoType for Pair {
571 type Pair = Pair;
572}
573
574#[cfg(test)]
575mod test {
576 use super::*;
577 use hex_literal::hex;
578 use crate::crypto::DEV_PHRASE;
579 use serde_json;
580
581 #[test]
582 fn default_phrase_should_be_used() {
583 assert_eq!(
584 Pair::from_string("//Alice///password", None).unwrap().public(),
585 Pair::from_string(&format!("{}//Alice", DEV_PHRASE), Some("password")).unwrap().public(),
586 );
587 }
588
589 #[test]
590 fn seed_and_derive_should_work() {
591 let seed = hex!("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60");
592 let pair = Pair::from_seed(&seed);
593 assert_eq!(pair.seed(), &seed);
594 let path = vec![DeriveJunction::Hard([0u8; 32])];
595 let derived = pair.derive(path.into_iter(), None).ok().unwrap().0;
596 assert_eq!(
597 derived.seed(),
598 &hex!("ede3354e133f9c8e337ddd6ee5415ed4b4ffe5fc7d21e933f4930a3730e5b21c")
599 );
600 }
601
602 #[test]
603 fn test_vector_should_work() {
604 let pair = Pair::from_seed(
605 &hex!("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60")
606 );
607 let public = pair.public();
608 assert_eq!(public, Public::from_raw(
609 hex!("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a")
610 ));
611 let message = b"";
612 let signature = hex!("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
613 let signature = Signature::from_raw(signature);
614 assert!(&pair.sign(&message[..]) == &signature);
615 assert!(Pair::verify(&signature, &message[..], &public));
616 }
617
618 #[test]
619 fn test_vector_by_string_should_work() {
620 let pair = Pair::from_string(
621 "0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
622 None
623 ).unwrap();
624 let public = pair.public();
625 assert_eq!(public, Public::from_raw(
626 hex!("d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a")
627 ));
628 let message = b"";
629 let signature = hex!("e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b");
630 let signature = Signature::from_raw(signature);
631 assert!(&pair.sign(&message[..]) == &signature);
632 assert!(Pair::verify(&signature, &message[..], &public));
633 }
634
635 #[test]
636 fn generated_pair_should_work() {
637 let (pair, _) = Pair::generate();
638 let public = pair.public();
639 let message = b"Something important";
640 let signature = pair.sign(&message[..]);
641 assert!(Pair::verify(&signature, &message[..], &public));
642 assert!(!Pair::verify(&signature, b"Something else", &public));
643 }
644
645 #[test]
646 fn seeded_pair_should_work() {
647 let pair = Pair::from_seed(b"12345678901234567890123456789012");
648 let public = pair.public();
649 assert_eq!(public, Public::from_raw(
650 hex!("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee")
651 ));
652 let message = hex!("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000");
653 let signature = pair.sign(&message[..]);
654 println!("Correct signature: {:?}", signature);
655 assert!(Pair::verify(&signature, &message[..], &public));
656 assert!(!Pair::verify(&signature, "Other message", &public));
657 }
658
659 #[test]
660 fn generate_with_phrase_recovery_possible() {
661 let (pair1, phrase, _) = Pair::generate_with_phrase(None);
662 let (pair2, _) = Pair::from_phrase(&phrase, None).unwrap();
663
664 assert_eq!(pair1.public(), pair2.public());
665 }
666
667 #[test]
668 fn generate_with_password_phrase_recovery_possible() {
669 let (pair1, phrase, _) = Pair::generate_with_phrase(Some("password"));
670 let (pair2, _) = Pair::from_phrase(&phrase, Some("password")).unwrap();
671
672 assert_eq!(pair1.public(), pair2.public());
673 }
674
675 #[test]
676 fn password_does_something() {
677 let (pair1, phrase, _) = Pair::generate_with_phrase(Some("password"));
678 let (pair2, _) = Pair::from_phrase(&phrase, None).unwrap();
679
680 assert_ne!(pair1.public(), pair2.public());
681 }
682
683 #[test]
684 fn ss58check_roundtrip_works() {
685 let pair = Pair::from_seed(b"12345678901234567890123456789012");
686 let public = pair.public();
687 let s = public.to_ss58check();
688 println!("Correct: {}", s);
689 let cmp = Public::from_ss58check(&s).unwrap();
690 assert_eq!(cmp, public);
691 }
692
693 #[test]
694 fn signature_serialization_works() {
695 let pair = Pair::from_seed(b"12345678901234567890123456789012");
696 let message = b"Something important";
697 let signature = pair.sign(&message[..]);
698 let serialized_signature = serde_json::to_string(&signature).unwrap();
699 assert_eq!(serialized_signature.len(), 130);
701 let signature = serde_json::from_str(&serialized_signature).unwrap();
702 assert!(Pair::verify(&signature, &message[..], &pair.public()));
703 }
704
705 #[test]
706 fn signature_serialization_doesnt_panic() {
707 fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
708 Ok(serde_json::from_str(text)?)
709 }
710 assert!(deserialize_signature("Not valid json.").is_err());
711 assert!(deserialize_signature("\"Not an actual signature.\"").is_err());
712 assert!(deserialize_signature("\"abc123\"").is_err());
714 }
715}