1use crate::{ed25519, sr25519, U256};
21use alloc::{format, str, vec::Vec};
22#[cfg(feature = "serde")]
23use alloc::{string::String, vec};
24use bip39::{Language, Mnemonic};
25use codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
26use core::hash::Hash;
27#[doc(hidden)]
28pub use core::ops::Deref;
29#[cfg(feature = "std")]
30use itertools::Itertools;
31#[cfg(feature = "std")]
32use rand::{rngs::OsRng, RngCore};
33use scale_info::TypeInfo;
34pub use secrecy::{ExposeSecret, SecretString};
35pub use ss58_registry::{from_known_address_format, Ss58AddressFormat, Ss58AddressFormatRegistry};
36pub use zeroize::Zeroize;
38
39pub use crate::{
40 address_uri::{AddressUri, Error as AddressUriError},
41 crypto_bytes::{CryptoBytes, PublicBytes, SignatureBytes},
42};
43
44pub const DEV_PHRASE: &str =
46 "bottom drive obey lake curtain smoke basket hold race lonely fit walk";
47
48pub const DEV_ADDRESS: &str = "5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV";
50
51pub const JUNCTION_ID_LEN: usize = 32;
54
55pub trait UncheckedFrom<T> {
59 fn unchecked_from(t: T) -> Self;
63}
64
65pub trait UncheckedInto<T> {
67 fn unchecked_into(self) -> T;
69}
70
71impl<S, T: UncheckedFrom<S>> UncheckedInto<T> for S {
72 fn unchecked_into(self) -> T {
73 T::unchecked_from(self)
74 }
75}
76
77#[cfg_attr(feature = "std", derive(thiserror::Error))]
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum SecretStringError {
81 #[cfg_attr(feature = "std", error("Invalid format {0}"))]
83 InvalidFormat(AddressUriError),
84 #[cfg_attr(feature = "std", error("Invalid phrase"))]
86 InvalidPhrase,
87 #[cfg_attr(feature = "std", error("Invalid password"))]
89 InvalidPassword,
90 #[cfg_attr(feature = "std", error("Invalid seed"))]
92 InvalidSeed,
93 #[cfg_attr(feature = "std", error("Invalid seed length"))]
95 InvalidSeedLength,
96 #[cfg_attr(feature = "std", error("Invalid path"))]
98 InvalidPath,
99}
100
101impl From<AddressUriError> for SecretStringError {
102 fn from(e: AddressUriError) -> Self {
103 Self::InvalidFormat(e)
104 }
105}
106
107#[cfg_attr(feature = "std", derive(thiserror::Error))]
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum DeriveError {
111 #[cfg_attr(feature = "std", error("Soft key in path"))]
113 SoftKeyInPath,
114}
115
116#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Encode, Decode)]
120pub enum DeriveJunction {
121 Soft([u8; JUNCTION_ID_LEN]),
123 Hard([u8; JUNCTION_ID_LEN]),
125}
126
127impl DeriveJunction {
128 pub fn soften(self) -> Self {
130 DeriveJunction::Soft(self.unwrap_inner())
131 }
132
133 pub fn harden(self) -> Self {
135 DeriveJunction::Hard(self.unwrap_inner())
136 }
137
138 pub fn soft<T: Encode>(index: T) -> Self {
142 let mut cc: [u8; JUNCTION_ID_LEN] = Default::default();
143 index.using_encoded(|data| {
144 if data.len() > JUNCTION_ID_LEN {
145 cc.copy_from_slice(&sp_crypto_hashing::blake2_256(data));
146 } else {
147 cc[0..data.len()].copy_from_slice(data);
148 }
149 });
150 DeriveJunction::Soft(cc)
151 }
152
153 pub fn hard<T: Encode>(index: T) -> Self {
157 Self::soft(index).harden()
158 }
159
160 pub fn unwrap_inner(self) -> [u8; JUNCTION_ID_LEN] {
162 match self {
163 DeriveJunction::Hard(c) | DeriveJunction::Soft(c) => c,
164 }
165 }
166
167 pub fn inner(&self) -> &[u8; JUNCTION_ID_LEN] {
169 match self {
170 DeriveJunction::Hard(ref c) | DeriveJunction::Soft(ref c) => c,
171 }
172 }
173
174 pub fn is_soft(&self) -> bool {
176 matches!(*self, DeriveJunction::Soft(_))
177 }
178
179 pub fn is_hard(&self) -> bool {
181 matches!(*self, DeriveJunction::Hard(_))
182 }
183}
184
185impl<T: AsRef<str>> From<T> for DeriveJunction {
186 fn from(j: T) -> DeriveJunction {
187 let j = j.as_ref();
188 let (code, hard) =
189 if let Some(stripped) = j.strip_prefix('/') { (stripped, true) } else { (j, false) };
190
191 let res = if let Ok(n) = str::parse::<u64>(code) {
192 DeriveJunction::soft(n)
194 } else {
195 DeriveJunction::soft(code)
197 };
198
199 if hard {
200 res.harden()
201 } else {
202 res
203 }
204 }
205}
206
207#[cfg_attr(feature = "std", derive(thiserror::Error))]
209#[cfg_attr(not(feature = "std"), derive(Debug))]
210#[derive(Clone, Eq, PartialEq)]
211#[allow(missing_docs)]
212#[cfg(any(feature = "full_crypto", feature = "serde"))]
213pub enum PublicError {
214 #[cfg_attr(feature = "std", error("Base 58 requirement is violated"))]
215 BadBase58,
216 #[cfg_attr(feature = "std", error("Length is bad"))]
217 BadLength,
218 #[cfg_attr(
219 feature = "std",
220 error(
221 "Unknown SS58 address format `{}`. ` \
222 `To support this address format, you need to call `set_default_ss58_version` at node start up.",
223 _0
224 )
225 )]
226 UnknownSs58AddressFormat(Ss58AddressFormat),
227 #[cfg_attr(feature = "std", error("Invalid checksum"))]
228 InvalidChecksum,
229 #[cfg_attr(feature = "std", error("Invalid SS58 prefix byte."))]
230 InvalidPrefix,
231 #[cfg_attr(feature = "std", error("Invalid SS58 format."))]
232 InvalidFormat,
233 #[cfg_attr(feature = "std", error("Invalid derivation path."))]
234 InvalidPath,
235 #[cfg_attr(feature = "std", error("Disallowed SS58 Address Format for this datatype."))]
236 FormatNotAllowed,
237 #[cfg_attr(feature = "std", error("Password not allowed."))]
238 PasswordNotAllowed,
239 #[cfg(feature = "std")]
240 #[cfg_attr(feature = "std", error("Incorrect URI syntax {0}."))]
241 MalformedUri(#[from] AddressUriError),
242}
243
244#[cfg(feature = "std")]
245impl core::fmt::Debug for PublicError {
246 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
247 write!(f, "{}", self)
249 }
250}
251
252pub trait Ss58Codec: Sized + AsMut<[u8]> + AsRef<[u8]> + ByteArray {
257 fn format_is_allowed(f: Ss58AddressFormat) -> bool {
260 !f.is_reserved()
261 }
262
263 #[cfg(feature = "serde")]
265 fn from_ss58check(s: &str) -> Result<Self, PublicError> {
266 Self::from_ss58check_with_version(s).and_then(|(r, v)| match v {
267 v if !v.is_custom() => Ok(r),
268 v if v == default_ss58_version() => Ok(r),
269 v => Err(PublicError::UnknownSs58AddressFormat(v)),
270 })
271 }
272
273 #[cfg(feature = "serde")]
275 fn from_ss58check_with_version(s: &str) -> Result<(Self, Ss58AddressFormat), PublicError> {
276 const CHECKSUM_LEN: usize = 2;
277 let body_len = Self::LEN;
278
279 let data = bs58::decode(s).into_vec().map_err(|_| PublicError::BadBase58)?;
280 if data.len() < 2 {
281 return Err(PublicError::BadLength)
282 }
283 let (prefix_len, ident) = match data[0] {
284 0..=63 => (1, data[0] as u16),
285 64..=127 => {
286 let lower = (data[0] << 2) | (data[1] >> 6);
292 let upper = data[1] & 0b00111111;
293 (2, (lower as u16) | ((upper as u16) << 8))
294 },
295 _ => return Err(PublicError::InvalidPrefix),
296 };
297 if data.len() != prefix_len + body_len + CHECKSUM_LEN {
298 return Err(PublicError::BadLength)
299 }
300 let format = ident.into();
301 if !Self::format_is_allowed(format) {
302 return Err(PublicError::FormatNotAllowed)
303 }
304
305 let hash = ss58hash(&data[0..body_len + prefix_len]);
306 let checksum = &hash[0..CHECKSUM_LEN];
307 if data[body_len + prefix_len..body_len + prefix_len + CHECKSUM_LEN] != *checksum {
308 return Err(PublicError::InvalidChecksum)
310 }
311
312 let result = Self::from_slice(&data[prefix_len..body_len + prefix_len])
313 .map_err(|()| PublicError::BadLength)?;
314 Ok((result, format))
315 }
316
317 #[cfg(feature = "std")]
320 fn from_string(s: &str) -> Result<Self, PublicError> {
321 Self::from_string_with_version(s).and_then(|(r, v)| match v {
322 v if !v.is_custom() => Ok(r),
323 v if v == default_ss58_version() => Ok(r),
324 v => Err(PublicError::UnknownSs58AddressFormat(v)),
325 })
326 }
327
328 #[cfg(feature = "serde")]
330 fn to_ss58check_with_version(&self, version: Ss58AddressFormat) -> String {
331 let ident: u16 = u16::from(version) & 0b0011_1111_1111_1111;
333 let mut v = match ident {
334 0..=63 => vec![ident as u8],
335 64..=16_383 => {
336 let first = ((ident & 0b0000_0000_1111_1100) as u8) >> 2;
338 let second = ((ident >> 8) as u8) | (((ident & 0b0000_0000_0000_0011) as u8) << 6);
341 vec![first | 0b01000000, second]
342 },
343 _ => unreachable!("masked out the upper two bits; qed"),
344 };
345 v.extend(self.as_ref());
346 let r = ss58hash(&v);
347 v.extend(&r[0..2]);
348 bs58::encode(v).into_string()
349 }
350
351 #[cfg(feature = "serde")]
353 fn to_ss58check(&self) -> String {
354 self.to_ss58check_with_version(default_ss58_version())
355 }
356
357 #[cfg(feature = "std")]
360 fn from_string_with_version(s: &str) -> Result<(Self, Ss58AddressFormat), PublicError> {
361 Self::from_ss58check_with_version(s)
362 }
363}
364
365pub trait Derive: Sized {
367 #[cfg(feature = "serde")]
371 fn derive<Iter: Iterator<Item = DeriveJunction>>(&self, _path: Iter) -> Option<Self> {
372 None
373 }
374}
375
376#[cfg(feature = "serde")]
377const PREFIX: &[u8] = b"SS58PRE";
378
379#[cfg(feature = "serde")]
380fn ss58hash(data: &[u8]) -> Vec<u8> {
381 use blake2::{Blake2b512, Digest};
382
383 let mut ctx = Blake2b512::new();
384 ctx.update(PREFIX);
385 ctx.update(data);
386 ctx.finalize().to_vec()
387}
388
389#[cfg(feature = "serde")]
391static DEFAULT_VERSION: core::sync::atomic::AtomicU16 = core::sync::atomic::AtomicU16::new(
392 from_known_address_format(Ss58AddressFormatRegistry::SubstrateAccount),
393);
394
395#[cfg(feature = "serde")]
397pub fn default_ss58_version() -> Ss58AddressFormat {
398 DEFAULT_VERSION.load(core::sync::atomic::Ordering::Relaxed).into()
399}
400
401#[cfg(feature = "serde")]
403pub fn unwrap_or_default_ss58_version(network: Option<Ss58AddressFormat>) -> Ss58AddressFormat {
404 network.unwrap_or_else(default_ss58_version)
405}
406
407#[cfg(feature = "serde")]
417pub fn set_default_ss58_version(new_default: Ss58AddressFormat) {
418 DEFAULT_VERSION.store(new_default.into(), core::sync::atomic::Ordering::Relaxed);
419}
420
421pub fn get_public_from_string_or_panic<TPublic: Public>(
425 s: &str,
426) -> <TPublic::Pair as Pair>::Public {
427 TPublic::Pair::from_string(&format!("//{}", s), None)
428 .expect("Function expects valid argument; qed")
429 .public()
430}
431
432#[cfg(feature = "std")]
433impl<T: Sized + AsMut<[u8]> + AsRef<[u8]> + Public + Derive> Ss58Codec for T {
434 fn from_string(s: &str) -> Result<Self, PublicError> {
435 let cap = AddressUri::parse(s)?;
436 if cap.pass.is_some() {
437 return Err(PublicError::PasswordNotAllowed)
438 }
439 let s = cap.phrase.unwrap_or(DEV_ADDRESS);
440 let addr = if let Some(stripped) = s.strip_prefix("0x") {
441 let d = array_bytes::hex2bytes(stripped).map_err(|_| PublicError::InvalidFormat)?;
442 Self::from_slice(&d).map_err(|()| PublicError::BadLength)?
443 } else {
444 Self::from_ss58check(s)?
445 };
446 if cap.paths.is_empty() {
447 Ok(addr)
448 } else {
449 addr.derive(cap.paths.iter().map(DeriveJunction::from))
450 .ok_or(PublicError::InvalidPath)
451 }
452 }
453
454 fn from_string_with_version(s: &str) -> Result<(Self, Ss58AddressFormat), PublicError> {
455 let cap = AddressUri::parse(s)?;
456 if cap.pass.is_some() {
457 return Err(PublicError::PasswordNotAllowed)
458 }
459 let (addr, v) = Self::from_ss58check_with_version(cap.phrase.unwrap_or(DEV_ADDRESS))?;
460 if cap.paths.is_empty() {
461 Ok((addr, v))
462 } else {
463 addr.derive(cap.paths.iter().map(DeriveJunction::from))
464 .ok_or(PublicError::InvalidPath)
465 .map(|a| (a, v))
466 }
467 }
468}
469
470#[cfg(all(not(feature = "std"), feature = "serde"))]
473impl<T: Sized + AsMut<[u8]> + AsRef<[u8]> + Public + Derive> Ss58Codec for T {}
474
475pub trait ByteArray: AsRef<[u8]> + AsMut<[u8]> + for<'a> TryFrom<&'a [u8], Error = ()> {
477 const LEN: usize;
479
480 fn from_slice(data: &[u8]) -> Result<Self, ()> {
482 Self::try_from(data)
483 }
484
485 fn to_raw_vec(&self) -> Vec<u8> {
487 self.as_slice().to_vec()
488 }
489
490 fn as_slice(&self) -> &[u8] {
492 self.as_ref()
493 }
494}
495
496pub trait Public: CryptoType + ByteArray + PartialEq + Eq + Clone + Send + Sync + Derive {}
498
499pub trait Signature: CryptoType + ByteArray + PartialEq + Eq + Clone + Send + Sync {}
501
502#[derive(
504 Clone,
505 Eq,
506 PartialEq,
507 Ord,
508 PartialOrd,
509 Encode,
510 Decode,
511 DecodeWithMemTracking,
512 MaxEncodedLen,
513 TypeInfo,
514)]
515#[cfg_attr(feature = "std", derive(Hash))]
516pub struct AccountId32([u8; 32]);
517
518impl AccountId32 {
519 pub const fn new(inner: [u8; 32]) -> Self {
524 Self(inner)
525 }
526}
527
528impl UncheckedFrom<crate::hash::H256> for AccountId32 {
529 fn unchecked_from(h: crate::hash::H256) -> Self {
530 AccountId32(h.into())
531 }
532}
533
534impl ByteArray for AccountId32 {
535 const LEN: usize = 32;
536}
537
538#[cfg(feature = "serde")]
539impl Ss58Codec for AccountId32 {}
540
541impl AsRef<[u8]> for AccountId32 {
542 fn as_ref(&self) -> &[u8] {
543 &self.0[..]
544 }
545}
546
547impl AsMut<[u8]> for AccountId32 {
548 fn as_mut(&mut self) -> &mut [u8] {
549 &mut self.0[..]
550 }
551}
552
553impl AsRef<[u8; 32]> for AccountId32 {
554 fn as_ref(&self) -> &[u8; 32] {
555 &self.0
556 }
557}
558
559impl AsMut<[u8; 32]> for AccountId32 {
560 fn as_mut(&mut self) -> &mut [u8; 32] {
561 &mut self.0
562 }
563}
564
565impl From<[u8; 32]> for AccountId32 {
566 fn from(x: [u8; 32]) -> Self {
567 Self::new(x)
568 }
569}
570
571impl<'a> TryFrom<&'a [u8]> for AccountId32 {
572 type Error = ();
573 fn try_from(x: &'a [u8]) -> Result<AccountId32, ()> {
574 if x.len() == 32 {
575 let mut data = [0; 32];
576 data.copy_from_slice(x);
577 Ok(AccountId32(data))
578 } else {
579 Err(())
580 }
581 }
582}
583
584impl From<AccountId32> for [u8; 32] {
585 fn from(x: AccountId32) -> [u8; 32] {
586 x.0
587 }
588}
589
590impl From<sr25519::Public> for AccountId32 {
591 fn from(k: sr25519::Public) -> Self {
592 k.0.into()
593 }
594}
595
596impl From<ed25519::Public> for AccountId32 {
597 fn from(k: ed25519::Public) -> Self {
598 k.0.into()
599 }
600}
601
602#[cfg(feature = "std")]
603impl std::fmt::Display for AccountId32 {
604 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
605 write!(f, "{}", self.to_ss58check())
606 }
607}
608
609impl core::fmt::Debug for AccountId32 {
610 fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
611 #[cfg(feature = "serde")]
612 {
613 let s = self.to_ss58check();
614 write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])?;
615 }
616
617 #[cfg(not(feature = "serde"))]
618 write!(f, "{}", crate::hexdisplay::HexDisplay::from(&self.0))?;
619
620 Ok(())
621 }
622}
623
624#[cfg(feature = "serde")]
625impl serde::Serialize for AccountId32 {
626 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
627 where
628 S: serde::Serializer,
629 {
630 serializer.serialize_str(&self.to_ss58check())
631 }
632}
633
634#[cfg(feature = "serde")]
635impl<'de> serde::Deserialize<'de> for AccountId32 {
636 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
637 where
638 D: serde::Deserializer<'de>,
639 {
640 Ss58Codec::from_ss58check(&String::deserialize(deserializer)?)
641 .map_err(|e| serde::de::Error::custom(format!("{:?}", e)))
642 }
643}
644
645#[cfg(feature = "std")]
646impl std::str::FromStr for AccountId32 {
647 type Err = &'static str;
648
649 fn from_str(s: &str) -> Result<Self, Self::Err> {
650 let hex_or_ss58_without_prefix = s.trim_start_matches("0x");
651 if hex_or_ss58_without_prefix.len() == 64 {
652 array_bytes::hex_n_into(hex_or_ss58_without_prefix).map_err(|_| "invalid hex address.")
653 } else {
654 Self::from_ss58check(s).map_err(|_| "invalid ss58 address.")
655 }
656 }
657}
658
659impl FromEntropy for AccountId32 {
661 fn from_entropy(input: &mut impl codec::Input) -> Result<Self, codec::Error> {
662 Ok(AccountId32::new(FromEntropy::from_entropy(input)?))
663 }
664}
665
666#[cfg(feature = "std")]
667pub use self::dummy::*;
668
669#[cfg(feature = "std")]
670mod dummy {
671 use super::*;
672
673 #[doc(hidden)]
674 pub struct DummyTag;
675
676 pub type Dummy = CryptoBytes<0, DummyTag>;
678
679 impl CryptoType for Dummy {
680 type Pair = Dummy;
681 }
682
683 impl Derive for Dummy {}
684
685 impl Public for Dummy {}
686
687 impl Signature for Dummy {}
688
689 impl Pair for Dummy {
690 type Public = Dummy;
691 type Seed = Dummy;
692 type Signature = Dummy;
693
694 #[cfg(feature = "std")]
695 fn generate_with_phrase(_: Option<&str>) -> (Self, String, Self::Seed) {
696 Default::default()
697 }
698
699 #[cfg(feature = "std")]
700 fn from_phrase(_: &str, _: Option<&str>) -> Result<(Self, Self::Seed), SecretStringError> {
701 Ok(Default::default())
702 }
703
704 fn derive<Iter: Iterator<Item = DeriveJunction>>(
705 &self,
706 _: Iter,
707 _: Option<Dummy>,
708 ) -> Result<(Self, Option<Dummy>), DeriveError> {
709 Ok((Self::default(), None))
710 }
711
712 fn from_seed_slice(_: &[u8]) -> Result<Self, SecretStringError> {
713 Ok(Self::default())
714 }
715
716 fn sign(&self, _: &[u8]) -> Self::Signature {
717 Self::default()
718 }
719
720 fn verify<M: AsRef<[u8]>>(_: &Self::Signature, _: M, _: &Self::Public) -> bool {
721 true
722 }
723
724 fn public(&self) -> Self::Public {
725 Self::default()
726 }
727
728 fn to_raw_vec(&self) -> Vec<u8> {
729 Default::default()
730 }
731 }
732}
733
734pub struct SecretUri {
798 pub phrase: SecretString,
802 pub password: Option<SecretString>,
804 pub junctions: Vec<DeriveJunction>,
806}
807
808impl alloc::str::FromStr for SecretUri {
809 type Err = SecretStringError;
810
811 fn from_str(s: &str) -> Result<Self, Self::Err> {
812 let cap = AddressUri::parse(s)?;
813 let phrase = cap.phrase.unwrap_or(DEV_PHRASE);
814
815 Ok(Self {
816 phrase: SecretString::from_str(phrase).expect("Returns infallible error; qed"),
817 password: cap
818 .pass
819 .map(|v| SecretString::from_str(v).expect("Returns infallible error; qed")),
820 junctions: cap.paths.iter().map(DeriveJunction::from).collect::<Vec<_>>(),
821 })
822 }
823}
824
825pub trait Pair: CryptoType + Sized {
829 type Public: Public + Hash;
831
832 type Seed: Default + AsRef<[u8]> + AsMut<[u8]> + Clone;
835
836 type Signature: Signature;
839
840 #[cfg(feature = "std")]
845 fn generate() -> (Self, Self::Seed) {
846 let mut seed = Self::Seed::default();
847 OsRng.fill_bytes(seed.as_mut());
848 (Self::from_seed(&seed), seed)
849 }
850
851 #[cfg(feature = "std")]
858 fn generate_with_phrase(password: Option<&str>) -> (Self, String, Self::Seed) {
859 let mnemonic = Mnemonic::generate(12).expect("Mnemonic generation always works; qed");
860 let phrase = mnemonic.words().join(" ");
861 let (pair, seed) = Self::from_phrase(&phrase, password)
862 .expect("All phrases generated by Mnemonic are valid; qed");
863 (pair, phrase.to_owned(), seed)
864 }
865
866 fn from_phrase(
868 phrase: &str,
869 password: Option<&str>,
870 ) -> Result<(Self, Self::Seed), SecretStringError> {
871 let mnemonic = Mnemonic::parse_in(Language::English, phrase)
872 .map_err(|_| SecretStringError::InvalidPhrase)?;
873 let (entropy, entropy_len) = mnemonic.to_entropy_array();
874 let big_seed =
875 substrate_bip39::seed_from_entropy(&entropy[0..entropy_len], password.unwrap_or(""))
876 .map_err(|_| SecretStringError::InvalidSeed)?;
877 let mut seed = Self::Seed::default();
878 let seed_slice = seed.as_mut();
879 let seed_len = seed_slice.len();
880 debug_assert!(seed_len <= big_seed.len());
881 seed_slice[..seed_len].copy_from_slice(&big_seed[..seed_len]);
882 Self::from_seed_slice(seed_slice).map(|x| (x, seed))
883 }
884
885 fn derive<Iter: Iterator<Item = DeriveJunction>>(
887 &self,
888 path: Iter,
889 seed: Option<Self::Seed>,
890 ) -> Result<(Self, Option<Self::Seed>), DeriveError>;
891
892 fn from_seed(seed: &Self::Seed) -> Self {
897 Self::from_seed_slice(seed.as_ref()).expect("seed has valid length; qed")
898 }
899
900 fn from_seed_slice(seed: &[u8]) -> Result<Self, SecretStringError>;
906
907 #[cfg(feature = "full_crypto")]
909 fn sign(&self, message: &[u8]) -> Self::Signature;
910
911 fn verify<M: AsRef<[u8]>>(sig: &Self::Signature, message: M, pubkey: &Self::Public) -> bool;
913
914 fn public(&self) -> Self::Public;
916
917 fn from_string_with_seed(
944 s: &str,
945 password_override: Option<&str>,
946 ) -> Result<(Self, Option<Self::Seed>), SecretStringError> {
947 use alloc::str::FromStr;
948 let SecretUri { junctions, phrase, password } = SecretUri::from_str(s)?;
949 let password =
950 password_override.or_else(|| password.as_ref().map(|p| p.expose_secret().as_str()));
951
952 let (root, seed) = if let Some(stripped) = phrase.expose_secret().strip_prefix("0x") {
953 array_bytes::hex2bytes(stripped)
954 .ok()
955 .and_then(|seed_vec| {
956 let mut seed = Self::Seed::default();
957 if seed.as_ref().len() == seed_vec.len() {
958 seed.as_mut().copy_from_slice(&seed_vec);
959 Some((Self::from_seed(&seed), seed))
960 } else {
961 None
962 }
963 })
964 .ok_or(SecretStringError::InvalidSeed)?
965 } else {
966 Self::from_phrase(phrase.expose_secret().as_str(), password)
967 .map_err(|_| SecretStringError::InvalidPhrase)?
968 };
969 root.derive(junctions.into_iter(), Some(seed))
970 .map_err(|_| SecretStringError::InvalidPath)
971 }
972
973 fn from_string(s: &str, password_override: Option<&str>) -> Result<Self, SecretStringError> {
977 Self::from_string_with_seed(s, password_override).map(|x| x.0)
978 }
979
980 fn to_raw_vec(&self) -> Vec<u8>;
982}
983
984pub trait IsWrappedBy<Outer>: From<Outer> + Into<Outer> {
986 fn from_ref(outer: &Outer) -> &Self;
988 fn from_mut(outer: &mut Outer) -> &mut Self;
990}
991
992pub trait Wraps: Sized {
994 type Inner: IsWrappedBy<Self>;
996
997 fn as_inner_ref(&self) -> &Self::Inner {
999 Self::Inner::from_ref(self)
1000 }
1001}
1002
1003impl<T, Outer> IsWrappedBy<Outer> for T
1004where
1005 Outer: AsRef<Self> + AsMut<Self> + From<Self>,
1006 T: From<Outer>,
1007{
1008 fn from_ref(outer: &Outer) -> &Self {
1010 outer.as_ref()
1011 }
1012
1013 fn from_mut(outer: &mut Outer) -> &mut Self {
1015 outer.as_mut()
1016 }
1017}
1018
1019impl<Inner, Outer, T> UncheckedFrom<T> for Outer
1020where
1021 Outer: Wraps<Inner = Inner>,
1022 Inner: IsWrappedBy<Outer> + UncheckedFrom<T>,
1023{
1024 fn unchecked_from(t: T) -> Self {
1025 let inner: Inner = t.unchecked_into();
1026 inner.into()
1027 }
1028}
1029
1030pub trait CryptoType {
1032 type Pair: Pair;
1034}
1035
1036#[derive(
1044 Copy,
1045 Clone,
1046 Default,
1047 PartialEq,
1048 Eq,
1049 PartialOrd,
1050 Ord,
1051 Hash,
1052 Encode,
1053 Decode,
1054 crate::RuntimeDebug,
1055 TypeInfo,
1056)]
1057#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1058#[repr(transparent)]
1059pub struct KeyTypeId(pub [u8; 4]);
1060
1061impl From<u32> for KeyTypeId {
1062 fn from(x: u32) -> Self {
1063 Self(x.to_le_bytes())
1064 }
1065}
1066
1067impl From<KeyTypeId> for u32 {
1068 fn from(x: KeyTypeId) -> Self {
1069 u32::from_le_bytes(x.0)
1070 }
1071}
1072
1073impl From<[u8; 4]> for KeyTypeId {
1074 fn from(value: [u8; 4]) -> Self {
1075 Self(value)
1076 }
1077}
1078
1079impl AsRef<[u8]> for KeyTypeId {
1080 fn as_ref(&self) -> &[u8] {
1081 &self.0
1082 }
1083}
1084
1085impl<'a> TryFrom<&'a str> for KeyTypeId {
1086 type Error = ();
1087
1088 fn try_from(x: &'a str) -> Result<Self, ()> {
1089 let b = x.as_bytes();
1090 if b.len() != 4 {
1091 return Err(())
1092 }
1093 let mut res = KeyTypeId::default();
1094 res.0.copy_from_slice(&b[0..4]);
1095 Ok(res)
1096 }
1097}
1098
1099pub trait VrfCrypto {
1101 type VrfInput;
1103 type VrfPreOutput;
1105 type VrfSignData;
1107 type VrfSignature;
1109}
1110
1111pub trait VrfSecret: VrfCrypto {
1113 fn vrf_pre_output(&self, data: &Self::VrfInput) -> Self::VrfPreOutput;
1115
1116 fn vrf_sign(&self, input: &Self::VrfSignData) -> Self::VrfSignature;
1118}
1119
1120pub trait VrfPublic: VrfCrypto {
1122 fn vrf_verify(&self, data: &Self::VrfSignData, signature: &Self::VrfSignature) -> bool;
1124}
1125
1126#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Encode, Decode)]
1128#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1129pub struct CryptoTypeId(pub [u8; 4]);
1130
1131pub mod key_types {
1137 use super::KeyTypeId;
1138
1139 pub const BABE: KeyTypeId = KeyTypeId(*b"babe");
1141 pub const SASSAFRAS: KeyTypeId = KeyTypeId(*b"sass");
1143 pub const GRANDPA: KeyTypeId = KeyTypeId(*b"gran");
1145 pub const ACCOUNT: KeyTypeId = KeyTypeId(*b"acco");
1147 pub const AURA: KeyTypeId = KeyTypeId(*b"aura");
1149 pub const BEEFY: KeyTypeId = KeyTypeId(*b"beef");
1151 pub const IM_ONLINE: KeyTypeId = KeyTypeId(*b"imon");
1153 pub const AUTHORITY_DISCOVERY: KeyTypeId = KeyTypeId(*b"audi");
1155 pub const STAKING: KeyTypeId = KeyTypeId(*b"stak");
1157 pub const STATEMENT: KeyTypeId = KeyTypeId(*b"stmt");
1159 pub const MIXNET: KeyTypeId = KeyTypeId(*b"mixn");
1161 pub const DUMMY: KeyTypeId = KeyTypeId(*b"dumy");
1163}
1164
1165pub trait FromEntropy: Sized {
1167 fn from_entropy(input: &mut impl codec::Input) -> Result<Self, codec::Error>;
1170}
1171
1172impl FromEntropy for bool {
1173 fn from_entropy(input: &mut impl codec::Input) -> Result<Self, codec::Error> {
1174 Ok(input.read_byte()? % 2 == 1)
1175 }
1176}
1177
1178impl FromEntropy for () {
1180 fn from_entropy(_: &mut impl codec::Input) -> Result<Self, codec::Error> {
1181 Ok(())
1182 }
1183}
1184
1185macro_rules! impl_from_entropy {
1186 ($type:ty , $( $others:tt )*) => {
1187 impl_from_entropy!($type);
1188 impl_from_entropy!($( $others )*);
1189 };
1190 ($type:ty) => {
1191 impl FromEntropy for $type {
1192 fn from_entropy(input: &mut impl codec::Input) -> Result<Self, codec::Error> {
1193 <Self as codec::Decode>::decode(input)
1194 }
1195 }
1196 }
1197}
1198
1199macro_rules! impl_from_entropy_base {
1200 ($type:ty , $( $others:tt )*) => {
1201 impl_from_entropy_base!($type);
1202 impl_from_entropy_base!($( $others )*);
1203 };
1204 ($type:ty) => {
1205 impl_from_entropy!($type,
1206 [$type; 1], [$type; 2], [$type; 3], [$type; 4], [$type; 5], [$type; 6], [$type; 7], [$type; 8],
1207 [$type; 9], [$type; 10], [$type; 11], [$type; 12], [$type; 13], [$type; 14], [$type; 15], [$type; 16],
1208 [$type; 17], [$type; 18], [$type; 19], [$type; 20], [$type; 21], [$type; 22], [$type; 23], [$type; 24],
1209 [$type; 25], [$type; 26], [$type; 27], [$type; 28], [$type; 29], [$type; 30], [$type; 31], [$type; 32],
1210 [$type; 36], [$type; 40], [$type; 44], [$type; 48], [$type; 56], [$type; 64], [$type; 72], [$type; 80],
1211 [$type; 96], [$type; 112], [$type; 128], [$type; 160], [$type; 177], [$type; 192], [$type; 224], [$type; 256]
1212 );
1213 }
1214}
1215
1216impl_from_entropy_base!(u8, u16, u32, u64, u128, i8, i16, i32, i64, i128, U256);
1217
1218#[cfg(test)]
1219mod tests {
1220 use super::*;
1221 use crate::DeriveJunction;
1222 use alloc::{string::String, vec};
1223
1224 struct TestCryptoTag;
1225
1226 #[derive(Clone, Eq, PartialEq, Debug)]
1227 enum TestPair {
1228 Generated,
1229 GeneratedWithPhrase,
1230 GeneratedFromPhrase { phrase: String, password: Option<String> },
1231 Standard { phrase: String, password: Option<String>, path: Vec<DeriveJunction> },
1232 Seed(Vec<u8>),
1233 }
1234
1235 impl Default for TestPair {
1236 fn default() -> Self {
1237 TestPair::Generated
1238 }
1239 }
1240
1241 impl CryptoType for TestPair {
1242 type Pair = Self;
1243 }
1244
1245 type TestPublic = PublicBytes<0, TestCryptoTag>;
1246
1247 impl CryptoType for TestPublic {
1248 type Pair = TestPair;
1249 }
1250
1251 type TestSignature = SignatureBytes<0, TestCryptoTag>;
1252
1253 impl CryptoType for TestSignature {
1254 type Pair = TestPair;
1255 }
1256
1257 impl Pair for TestPair {
1258 type Public = TestPublic;
1259 type Seed = [u8; 8];
1260 type Signature = TestSignature;
1261
1262 fn generate() -> (Self, <Self as Pair>::Seed) {
1263 (TestPair::Generated, [0u8; 8])
1264 }
1265
1266 fn generate_with_phrase(_password: Option<&str>) -> (Self, String, <Self as Pair>::Seed) {
1267 (TestPair::GeneratedWithPhrase, "".into(), [0u8; 8])
1268 }
1269
1270 fn from_phrase(
1271 phrase: &str,
1272 password: Option<&str>,
1273 ) -> Result<(Self, <Self as Pair>::Seed), SecretStringError> {
1274 Ok((
1275 TestPair::GeneratedFromPhrase {
1276 phrase: phrase.to_owned(),
1277 password: password.map(Into::into),
1278 },
1279 [0u8; 8],
1280 ))
1281 }
1282
1283 fn derive<Iter: Iterator<Item = DeriveJunction>>(
1284 &self,
1285 path_iter: Iter,
1286 _: Option<[u8; 8]>,
1287 ) -> Result<(Self, Option<[u8; 8]>), DeriveError> {
1288 Ok((
1289 match self.clone() {
1290 TestPair::Standard { phrase, password, path } => TestPair::Standard {
1291 phrase,
1292 password,
1293 path: path.into_iter().chain(path_iter).collect(),
1294 },
1295 TestPair::GeneratedFromPhrase { phrase, password } =>
1296 TestPair::Standard { phrase, password, path: path_iter.collect() },
1297 x =>
1298 if path_iter.count() == 0 {
1299 x
1300 } else {
1301 return Err(DeriveError::SoftKeyInPath)
1302 },
1303 },
1304 None,
1305 ))
1306 }
1307
1308 fn sign(&self, _message: &[u8]) -> Self::Signature {
1309 TestSignature::default()
1310 }
1311
1312 fn verify<M: AsRef<[u8]>>(_: &Self::Signature, _: M, _: &Self::Public) -> bool {
1313 true
1314 }
1315
1316 fn public(&self) -> Self::Public {
1317 TestPublic::default()
1318 }
1319
1320 fn from_seed_slice(seed: &[u8]) -> Result<Self, SecretStringError> {
1321 Ok(TestPair::Seed(seed.to_owned()))
1322 }
1323
1324 fn to_raw_vec(&self) -> Vec<u8> {
1325 vec![]
1326 }
1327 }
1328
1329 #[test]
1330 fn interpret_std_seed_should_work() {
1331 assert_eq!(
1332 TestPair::from_string("0x0123456789abcdef", None),
1333 Ok(TestPair::Seed(array_bytes::hex2bytes_unchecked("0123456789abcdef")))
1334 );
1335 }
1336
1337 #[test]
1338 fn password_override_should_work() {
1339 assert_eq!(
1340 TestPair::from_string("hello world///password", None),
1341 TestPair::from_string("hello world", Some("password")),
1342 );
1343 assert_eq!(
1344 TestPair::from_string("hello world///password", None),
1345 TestPair::from_string("hello world///other password", Some("password")),
1346 );
1347 }
1348
1349 #[test]
1350 fn interpret_std_secret_string_should_work() {
1351 assert_eq!(
1352 TestPair::from_string("hello world", None),
1353 Ok(TestPair::Standard {
1354 phrase: "hello world".to_owned(),
1355 password: None,
1356 path: vec![]
1357 })
1358 );
1359 assert_eq!(
1360 TestPair::from_string("hello world/1", None),
1361 Ok(TestPair::Standard {
1362 phrase: "hello world".to_owned(),
1363 password: None,
1364 path: vec![DeriveJunction::soft(1)]
1365 })
1366 );
1367 assert_eq!(
1368 TestPair::from_string("hello world/DOT", None),
1369 Ok(TestPair::Standard {
1370 phrase: "hello world".to_owned(),
1371 password: None,
1372 path: vec![DeriveJunction::soft("DOT")]
1373 })
1374 );
1375 assert_eq!(
1376 TestPair::from_string("hello world/0123456789012345678901234567890123456789", None),
1377 Ok(TestPair::Standard {
1378 phrase: "hello world".to_owned(),
1379 password: None,
1380 path: vec![DeriveJunction::soft("0123456789012345678901234567890123456789")]
1381 })
1382 );
1383 assert_eq!(
1384 TestPair::from_string("hello world//1", None),
1385 Ok(TestPair::Standard {
1386 phrase: "hello world".to_owned(),
1387 password: None,
1388 path: vec![DeriveJunction::hard(1)]
1389 })
1390 );
1391 assert_eq!(
1392 TestPair::from_string("hello world//DOT", None),
1393 Ok(TestPair::Standard {
1394 phrase: "hello world".to_owned(),
1395 password: None,
1396 path: vec![DeriveJunction::hard("DOT")]
1397 })
1398 );
1399 assert_eq!(
1400 TestPair::from_string("hello world//0123456789012345678901234567890123456789", None),
1401 Ok(TestPair::Standard {
1402 phrase: "hello world".to_owned(),
1403 password: None,
1404 path: vec![DeriveJunction::hard("0123456789012345678901234567890123456789")]
1405 })
1406 );
1407 assert_eq!(
1408 TestPair::from_string("hello world//1/DOT", None),
1409 Ok(TestPair::Standard {
1410 phrase: "hello world".to_owned(),
1411 password: None,
1412 path: vec![DeriveJunction::hard(1), DeriveJunction::soft("DOT")]
1413 })
1414 );
1415 assert_eq!(
1416 TestPair::from_string("hello world//DOT/1", None),
1417 Ok(TestPair::Standard {
1418 phrase: "hello world".to_owned(),
1419 password: None,
1420 path: vec![DeriveJunction::hard("DOT"), DeriveJunction::soft(1)]
1421 })
1422 );
1423 assert_eq!(
1424 TestPair::from_string("hello world///password", None),
1425 Ok(TestPair::Standard {
1426 phrase: "hello world".to_owned(),
1427 password: Some("password".to_owned()),
1428 path: vec![]
1429 })
1430 );
1431 assert_eq!(
1432 TestPair::from_string("hello world//1/DOT///password", None),
1433 Ok(TestPair::Standard {
1434 phrase: "hello world".to_owned(),
1435 password: Some("password".to_owned()),
1436 path: vec![DeriveJunction::hard(1), DeriveJunction::soft("DOT")]
1437 })
1438 );
1439 assert_eq!(
1440 TestPair::from_string("hello world/1//DOT///password", None),
1441 Ok(TestPair::Standard {
1442 phrase: "hello world".to_owned(),
1443 password: Some("password".to_owned()),
1444 path: vec![DeriveJunction::soft(1), DeriveJunction::hard("DOT")]
1445 })
1446 );
1447 }
1448
1449 #[test]
1450 fn accountid_32_from_str_works() {
1451 use std::str::FromStr;
1452 assert!(AccountId32::from_str("5G9VdMwXvzza9pS8qE8ZHJk3CheHW9uucBn9ngW4C1gmmzpv").is_ok());
1453 assert!(AccountId32::from_str(
1454 "5c55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d"
1455 )
1456 .is_ok());
1457 assert!(AccountId32::from_str(
1458 "0x5c55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d"
1459 )
1460 .is_ok());
1461
1462 assert_eq!(
1463 AccountId32::from_str("99G9VdMwXvzza9pS8qE8ZHJk3CheHW9uucBn9ngW4C1gmmzpv").unwrap_err(),
1464 "invalid ss58 address.",
1465 );
1466 assert_eq!(
1467 AccountId32::from_str(
1468 "gc55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d"
1469 )
1470 .unwrap_err(),
1471 "invalid hex address.",
1472 );
1473 assert_eq!(
1474 AccountId32::from_str(
1475 "0xgc55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d"
1476 )
1477 .unwrap_err(),
1478 "invalid hex address.",
1479 );
1480
1481 assert_eq!(
1483 AccountId32::from_str(
1484 "55c55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d"
1485 )
1486 .unwrap_err(),
1487 "invalid ss58 address.",
1488 );
1489 }
1490}