referrerpolicy=no-referrer-when-downgrade

sp_core/
crypto.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18//! Cryptographic utilities.
19
20use 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};
36/// Trait to zeroize a memory buffer.
37pub use zeroize::Zeroize;
38
39pub use crate::{
40	address_uri::{AddressUri, Error as AddressUriError},
41	crypto_bytes::{CryptoBytes, PublicBytes, SignatureBytes},
42};
43
44/// The root phrase for our publicly known keys.
45pub const DEV_PHRASE: &str =
46	"bottom drive obey lake curtain smoke basket hold race lonely fit walk";
47
48/// The address of the associated root phrase for our publicly known keys.
49pub const DEV_ADDRESS: &str = "5DfhGyQdFobKM8NsWvEeAKk5EQQgYe9AydgJ7rMB6E1EqRzV";
50
51/// The length of the junction identifier. Note that this is also referred to as the
52/// `CHAIN_CODE_LENGTH` in the context of Schnorrkel.
53pub const JUNCTION_ID_LEN: usize = 32;
54
55/// Similar to `From`, except that the onus is on the part of the caller to ensure
56/// that data passed in makes sense. Basically, you're not guaranteed to get anything
57/// sensible out.
58pub trait UncheckedFrom<T> {
59	/// Convert from an instance of `T` to Self. This is not guaranteed to be
60	/// whatever counts as a valid instance of `T` and it's up to the caller to
61	/// ensure that it makes sense.
62	fn unchecked_from(t: T) -> Self;
63}
64
65/// The counterpart to `UncheckedFrom`.
66pub trait UncheckedInto<T> {
67	/// The counterpart to `unchecked_from`.
68	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/// An error with the interpretation of a secret.
78#[cfg_attr(feature = "std", derive(thiserror::Error))]
79#[derive(Debug, Clone, PartialEq, Eq)]
80pub enum SecretStringError {
81	/// The overall format was invalid (e.g. the seed phrase contained symbols).
82	#[cfg_attr(feature = "std", error("Invalid format {0}"))]
83	InvalidFormat(AddressUriError),
84	/// The seed phrase provided is not a valid BIP39 phrase.
85	#[cfg_attr(feature = "std", error("Invalid phrase"))]
86	InvalidPhrase,
87	/// The supplied password was invalid.
88	#[cfg_attr(feature = "std", error("Invalid password"))]
89	InvalidPassword,
90	/// The seed is invalid (bad content).
91	#[cfg_attr(feature = "std", error("Invalid seed"))]
92	InvalidSeed,
93	/// The seed has an invalid length.
94	#[cfg_attr(feature = "std", error("Invalid seed length"))]
95	InvalidSeedLength,
96	/// The derivation path was invalid (e.g. contains soft junctions when they are not supported).
97	#[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/// An error when deriving a key.
108#[cfg_attr(feature = "std", derive(thiserror::Error))]
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub enum DeriveError {
111	/// A soft key was found in the path (and is unsupported).
112	#[cfg_attr(feature = "std", error("Soft key in path"))]
113	SoftKeyInPath,
114}
115
116/// A since derivation junction description. It is the single parameter used when creating
117/// a new secret key from an existing secret key and, in the case of `SoftRaw` and `SoftIndex`
118/// a new public key from an existing public key.
119#[derive(Copy, Clone, Eq, PartialEq, Hash, Debug, Encode, Decode)]
120pub enum DeriveJunction {
121	/// Soft (vanilla) derivation. Public keys have a correspondent derivation.
122	Soft([u8; JUNCTION_ID_LEN]),
123	/// Hard ("hardened") derivation. Public keys do not have a correspondent derivation.
124	Hard([u8; JUNCTION_ID_LEN]),
125}
126
127impl DeriveJunction {
128	/// Consume self to return a soft derive junction with the same chain code.
129	pub fn soften(self) -> Self {
130		DeriveJunction::Soft(self.unwrap_inner())
131	}
132
133	/// Consume self to return a hard derive junction with the same chain code.
134	pub fn harden(self) -> Self {
135		DeriveJunction::Hard(self.unwrap_inner())
136	}
137
138	/// Create a new soft (vanilla) DeriveJunction from a given, encodable, value.
139	///
140	/// If you need a hard junction, use `hard()`.
141	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	/// Create a new hard (hardened) DeriveJunction from a given, encodable, value.
154	///
155	/// If you need a soft junction, use `soft()`.
156	pub fn hard<T: Encode>(index: T) -> Self {
157		Self::soft(index).harden()
158	}
159
160	/// Consume self to return the chain code.
161	pub fn unwrap_inner(self) -> [u8; JUNCTION_ID_LEN] {
162		match self {
163			DeriveJunction::Hard(c) | DeriveJunction::Soft(c) => c,
164		}
165	}
166
167	/// Get a reference to the inner junction id.
168	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	/// Return `true` if the junction is soft.
175	pub fn is_soft(&self) -> bool {
176		matches!(*self, DeriveJunction::Soft(_))
177	}
178
179	/// Return `true` if the junction is hard.
180	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			// number
193			DeriveJunction::soft(n)
194		} else {
195			// something else
196			DeriveJunction::soft(code)
197		};
198
199		if hard {
200			res.harden()
201		} else {
202			res
203		}
204	}
205}
206
207/// An error type for SS58 decoding.
208#[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		// Just use the `Display` implementation
248		write!(f, "{}", self)
249	}
250}
251
252/// Key that can be encoded to/from SS58.
253///
254/// See <https://docs.substrate.io/v3/advanced/ss58/>
255/// for information on the codec.
256pub trait Ss58Codec: Sized + AsMut<[u8]> + AsRef<[u8]> + ByteArray {
257	/// A format filterer, can be used to ensure that `from_ss58check` family only decode for
258	/// allowed identifiers. By default just refuses the two reserved identifiers.
259	fn format_is_allowed(f: Ss58AddressFormat) -> bool {
260		!f.is_reserved()
261	}
262
263	/// Some if the string is a properly encoded SS58Check address.
264	#[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	/// Some if the string is a properly encoded SS58Check address.
274	#[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				// weird bit manipulation owing to the combination of LE encoding and missing two
287				// bits from the left.
288				// d[0] d[1] are: 01aaaaaa bbcccccc
289				// they make the LE-encoded 16-bit value: aaaaaabb 00cccccc
290				// so the lower byte is formed of aaaaaabb and the higher byte is 00cccccc
291				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			// Invalid checksum.
309			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	/// Some if the string is a properly encoded SS58Check address, optionally with
318	/// a derivation path following.
319	#[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	/// Return the ss58-check string for this key.
329	#[cfg(feature = "serde")]
330	fn to_ss58check_with_version(&self, version: Ss58AddressFormat) -> String {
331		// We mask out the upper two bits of the ident - SS58 Prefix currently only supports 14-bits
332		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				// upper six bits of the lower byte(!)
337				let first = ((ident & 0b0000_0000_1111_1100) as u8) >> 2;
338				// lower two bits of the lower byte in the high pos,
339				// lower bits of the upper byte in the low pos
340				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	/// Return the ss58-check string for this key.
352	#[cfg(feature = "serde")]
353	fn to_ss58check(&self) -> String {
354		self.to_ss58check_with_version(default_ss58_version())
355	}
356
357	/// Some if the string is a properly encoded SS58Check address, optionally with
358	/// a derivation path following.
359	#[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
365/// Derivable key trait.
366pub trait Derive: Sized {
367	/// Derive a child key from a series of given junctions.
368	///
369	/// Will be `None` for public keys if there are any hard junctions in there.
370	#[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/// Default prefix number
390#[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/// Returns default SS58 format used by the current active process.
396#[cfg(feature = "serde")]
397pub fn default_ss58_version() -> Ss58AddressFormat {
398	DEFAULT_VERSION.load(core::sync::atomic::Ordering::Relaxed).into()
399}
400
401/// Returns either the input address format or the default.
402#[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/// Set the default SS58 "version".
408///
409/// This SS58 version/format will be used when encoding/decoding SS58 addresses.
410///
411/// If you want to support a custom SS58 prefix (that isn't yet registered in the `ss58-registry`),
412/// you are required to call this function with your desired prefix [`Ss58AddressFormat::custom`].
413/// This will enable the node to decode ss58 addresses with this prefix.
414///
415/// This SS58 version/format is also only used by the node and not by the runtime.
416#[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
421/// Interprets the string `s` in order to generate a public key without password.
422///
423/// Function will panic when invalid string is provided.
424pub 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// Use the default implementations of the trait in serde feature.
471// The std implementation is not available because of std only crate Regex.
472#[cfg(all(not(feature = "std"), feature = "serde"))]
473impl<T: Sized + AsMut<[u8]> + AsRef<[u8]> + Public + Derive> Ss58Codec for T {}
474
475/// Trait used for types that are really just a fixed-length array.
476pub trait ByteArray: AsRef<[u8]> + AsMut<[u8]> + for<'a> TryFrom<&'a [u8], Error = ()> {
477	/// The "length" of the values of this type, which is always the same.
478	const LEN: usize;
479
480	/// A new instance from the given slice that should be `Self::LEN` bytes long.
481	fn from_slice(data: &[u8]) -> Result<Self, ()> {
482		Self::try_from(data)
483	}
484
485	/// Return a `Vec<u8>` filled with raw data.
486	fn to_raw_vec(&self) -> Vec<u8> {
487		self.as_slice().to_vec()
488	}
489
490	/// Return a slice filled with raw data.
491	fn as_slice(&self) -> &[u8] {
492		self.as_ref()
493	}
494}
495
496/// Trait suitable for cryptographic public keys.
497pub trait Public: CryptoType + ByteArray + PartialEq + Eq + Clone + Send + Sync + Derive {}
498
499/// Trait suitable for cryptographic signatures.
500pub trait Signature: CryptoType + ByteArray + PartialEq + Eq + Clone + Send + Sync {}
501
502/// An opaque 32-byte cryptographic identifier.
503#[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	/// Create a new instance from its raw inner byte value.
520	///
521	/// Equivalent to this types `From<[u8; 32]>` implementation. For the lack of const
522	/// support in traits we have this constructor.
523	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
659/// Creates an [`AccountId32`] from the input, which should contain at least 32 bytes.
660impl 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	/// Dummy cryptography. Doesn't do anything.
677	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
734/// A secret uri (`SURI`) that can be used to generate a key pair.
735///
736/// The `SURI` can be parsed from a string. The string is interpreted in the following way:
737///
738/// - If `string` is a possibly `0x` prefixed 64-digit hex string, then it will be interpreted
739/// directly as a `MiniSecretKey` (aka "seed" in `subkey`).
740/// - If `string` is a valid BIP-39 key phrase of 12, 15, 18, 21 or 24 words, then the key will
741/// be derived from it. In this case:
742///   - the phrase may be followed by one or more items delimited by `/` characters.
743///   - the path may be followed by `///`, in which case everything after the `///` is treated
744/// as a password.
745/// - If `string` begins with a `/` character it is prefixed with the Substrate public `DEV_PHRASE`
746///   and interpreted as above.
747///
748/// In this case they are interpreted as HDKD junctions; purely numeric items are interpreted as
749/// integers, non-numeric items as strings. Junctions prefixed with `/` are interpreted as soft
750/// junctions, and with `//` as hard junctions.
751///
752/// There is no correspondence mapping between `SURI` strings and the keys they represent.
753/// Two different non-identical strings can actually lead to the same secret being derived.
754/// Notably, integer junction indices may be legally prefixed with arbitrary number of zeros.
755/// Similarly an empty password (ending the `SURI` with `///`) is perfectly valid and will
756/// generally be equivalent to no password at all.
757///
758/// The `password` is used as salt when generating the seed from the BIP-39 key phrase.
759///
760/// # Example
761///
762/// Parse [`DEV_PHRASE`] secret uri with junction:
763///
764/// ```
765/// # use sp_core::crypto::{SecretUri, DeriveJunction, DEV_PHRASE, ExposeSecret};
766/// # use std::str::FromStr;
767/// let suri = SecretUri::from_str("//Alice").expect("Parse SURI");
768///
769/// assert_eq!(vec![DeriveJunction::from("Alice").harden()], suri.junctions);
770/// assert_eq!(DEV_PHRASE, suri.phrase.expose_secret());
771/// assert!(suri.password.is_none());
772/// ```
773///
774/// Parse [`DEV_PHRASE`] secret ui with junction and password:
775///
776/// ```
777/// # use sp_core::crypto::{SecretUri, DeriveJunction, DEV_PHRASE, ExposeSecret};
778/// # use std::str::FromStr;
779/// let suri = SecretUri::from_str("//Alice///SECRET_PASSWORD").expect("Parse SURI");
780///
781/// assert_eq!(vec![DeriveJunction::from("Alice").harden()], suri.junctions);
782/// assert_eq!(DEV_PHRASE, suri.phrase.expose_secret());
783/// assert_eq!("SECRET_PASSWORD", suri.password.unwrap().expose_secret());
784/// ```
785///
786/// Parse [`DEV_PHRASE`] secret ui with hex phrase and junction:
787///
788/// ```
789/// # use sp_core::crypto::{SecretUri, DeriveJunction, DEV_PHRASE, ExposeSecret};
790/// # use std::str::FromStr;
791/// let suri = SecretUri::from_str("0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a//Alice").expect("Parse SURI");
792///
793/// assert_eq!(vec![DeriveJunction::from("Alice").harden()], suri.junctions);
794/// assert_eq!("0xe5be9a5092b81bca64be81d212e7f2f9eba183bb7a90954f7b76361f6edb5c0a", suri.phrase.expose_secret());
795/// assert!(suri.password.is_none());
796/// ```
797pub struct SecretUri {
798	/// The phrase to derive the private key.
799	///
800	/// This can either be a 64-bit hex string or a BIP-39 key phrase.
801	pub phrase: SecretString,
802	/// Optional password as given as part of the uri.
803	pub password: Option<SecretString>,
804	/// The junctions as part of the uri.
805	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
825/// Trait suitable for typical cryptographic PKI key pair type.
826///
827/// For now it just specifies how to create a key from a phrase and derivation path.
828pub trait Pair: CryptoType + Sized {
829	/// The type which is used to encode a public key.
830	type Public: Public + Hash;
831
832	/// The type used to (minimally) encode the data required to securely create
833	/// a new key pair.
834	type Seed: Default + AsRef<[u8]> + AsMut<[u8]> + Clone;
835
836	/// The type used to represent a signature. Can be created from a key pair and a message
837	/// and verified with the message and a public key.
838	type Signature: Signature;
839
840	/// Generate new secure (random) key pair.
841	///
842	/// This is only for ephemeral keys really, since you won't have access to the secret key
843	/// for storage. If you want a persistent key pair, use `generate_with_phrase` instead.
844	#[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	/// Generate new secure (random) key pair and provide the recovery phrase.
852	///
853	/// You can recover the same key later with `from_phrase`.
854	///
855	/// This is generally slower than `generate()`, so prefer that unless you need to persist
856	/// the key from the current session.
857	#[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	/// Returns the KeyPair from the English BIP39 seed `phrase`, or an error if it's invalid.
867	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	/// Derive a child key from a series of given junctions.
886	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	/// Generate new key pair from the provided `seed`.
893	///
894	/// @WARNING: THIS WILL ONLY BE SECURE IF THE `seed` IS SECURE. If it can be guessed
895	/// by an attacker then they can also derive your key.
896	fn from_seed(seed: &Self::Seed) -> Self {
897		Self::from_seed_slice(seed.as_ref()).expect("seed has valid length; qed")
898	}
899
900	/// Make a new key pair from secret seed material. The slice must be the correct size or
901	/// an error will be returned.
902	///
903	/// @WARNING: THIS WILL ONLY BE SECURE IF THE `seed` IS SECURE. If it can be guessed
904	/// by an attacker then they can also derive your key.
905	fn from_seed_slice(seed: &[u8]) -> Result<Self, SecretStringError>;
906
907	/// Sign a message.
908	#[cfg(feature = "full_crypto")]
909	fn sign(&self, message: &[u8]) -> Self::Signature;
910
911	/// Verify a signature on a message. Returns true if the signature is good.
912	fn verify<M: AsRef<[u8]>>(sig: &Self::Signature, message: M, pubkey: &Self::Public) -> bool;
913
914	/// Get the public key.
915	fn public(&self) -> Self::Public;
916
917	/// Interprets the string `s` in order to generate a key Pair. Returns both the pair and an
918	/// optional seed, in the case that the pair can be expressed as a direct derivation from a seed
919	/// (some cases, such as Sr25519 derivations with path components, cannot).
920	///
921	/// This takes a helper function to do the key generation from a phrase, password and
922	/// junction iterator.
923	///
924	/// - If `s` is a possibly `0x` prefixed 64-digit hex string, then it will be interpreted
925	/// directly as a `MiniSecretKey` (aka "seed" in `subkey`).
926	/// - If `s` is a valid BIP-39 key phrase of 12, 15, 18, 21 or 24 words, then the key will
927	/// be derived from it. In this case:
928	///   - the phrase may be followed by one or more items delimited by `/` characters.
929	///   - the path may be followed by `///`, in which case everything after the `///` is treated
930	/// as a password.
931	/// - If `s` begins with a `/` character it is prefixed with the Substrate public `DEV_PHRASE`
932	///   and interpreted as above.
933	///
934	/// In this case they are interpreted as HDKD junctions; purely numeric items are interpreted as
935	/// integers, non-numeric items as strings. Junctions prefixed with `/` are interpreted as soft
936	/// junctions, and with `//` as hard junctions.
937	///
938	/// There is no correspondence mapping between SURI strings and the keys they represent.
939	/// Two different non-identical strings can actually lead to the same secret being derived.
940	/// Notably, integer junction indices may be legally prefixed with arbitrary number of zeros.
941	/// Similarly an empty password (ending the SURI with `///`) is perfectly valid and will
942	/// generally be equivalent to no password at all.
943	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	/// Interprets the string `s` in order to generate a key pair.
974	///
975	/// See [`from_string_with_seed`](Pair::from_string_with_seed) for more extensive documentation.
976	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	/// Return a vec filled with raw data.
981	fn to_raw_vec(&self) -> Vec<u8>;
982}
983
984/// One type is wrapped by another.
985pub trait IsWrappedBy<Outer>: From<Outer> + Into<Outer> {
986	/// Get a reference to the inner from the outer.
987	fn from_ref(outer: &Outer) -> &Self;
988	/// Get a mutable reference to the inner from the outer.
989	fn from_mut(outer: &mut Outer) -> &mut Self;
990}
991
992/// Opposite of `IsWrappedBy` - denotes a type which is a simple wrapper around another type.
993pub trait Wraps: Sized {
994	/// The inner type it is wrapping.
995	type Inner: IsWrappedBy<Self>;
996
997	/// Get a reference to the inner type that is wrapped.
998	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	/// Get a reference to the inner from the outer.
1009	fn from_ref(outer: &Outer) -> &Self {
1010		outer.as_ref()
1011	}
1012
1013	/// Get a mutable reference to the inner from the outer.
1014	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
1030/// Type which has a particular kind of crypto associated with it.
1031pub trait CryptoType {
1032	/// The pair key type of this crypto.
1033	type Pair: Pair;
1034}
1035
1036/// An identifier for a type of cryptographic key.
1037///
1038/// To avoid clashes with other modules when distributing your module publicly, register your
1039/// `KeyTypeId` on the list here by making a PR.
1040///
1041/// Values whose first character is `_` are reserved for private use and won't conflict with any
1042/// public modules.
1043#[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
1099/// Trait grouping types shared by a VRF signer and verifiers.
1100pub trait VrfCrypto {
1101	/// VRF input.
1102	type VrfInput;
1103	/// VRF pre-output.
1104	type VrfPreOutput;
1105	/// VRF signing data.
1106	type VrfSignData;
1107	/// VRF signature.
1108	type VrfSignature;
1109}
1110
1111/// VRF Secret Key.
1112pub trait VrfSecret: VrfCrypto {
1113	/// Get VRF-specific pre-output.
1114	fn vrf_pre_output(&self, data: &Self::VrfInput) -> Self::VrfPreOutput;
1115
1116	/// Sign VRF-specific data.
1117	fn vrf_sign(&self, input: &Self::VrfSignData) -> Self::VrfSignature;
1118}
1119
1120/// VRF Public Key.
1121pub trait VrfPublic: VrfCrypto {
1122	/// Verify input data signature.
1123	fn vrf_verify(&self, data: &Self::VrfSignData, signature: &Self::VrfSignature) -> bool;
1124}
1125
1126/// An identifier for a specific cryptographic algorithm used by a key pair
1127#[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
1131/// Known key types; this also functions as a global registry of key types for projects wishing to
1132/// avoid collisions with each other.
1133///
1134/// It's not universal in the sense that *all* key types need to be mentioned here, it's just a
1135/// handy place to put common key types.
1136pub mod key_types {
1137	use super::KeyTypeId;
1138
1139	/// Key type for Babe module, built-in. Identified as `babe`.
1140	pub const BABE: KeyTypeId = KeyTypeId(*b"babe");
1141	/// Key type for Sassafras module, built-in. Identified as `sass`.
1142	pub const SASSAFRAS: KeyTypeId = KeyTypeId(*b"sass");
1143	/// Key type for Grandpa module, built-in. Identified as `gran`.
1144	pub const GRANDPA: KeyTypeId = KeyTypeId(*b"gran");
1145	/// Key type for controlling an account in a Substrate runtime, built-in. Identified as `acco`.
1146	pub const ACCOUNT: KeyTypeId = KeyTypeId(*b"acco");
1147	/// Key type for Aura module, built-in. Identified as `aura`.
1148	pub const AURA: KeyTypeId = KeyTypeId(*b"aura");
1149	/// Key type for BEEFY module.
1150	pub const BEEFY: KeyTypeId = KeyTypeId(*b"beef");
1151	/// Key type for ImOnline module, built-in. Identified as `imon`.
1152	pub const IM_ONLINE: KeyTypeId = KeyTypeId(*b"imon");
1153	/// Key type for AuthorityDiscovery module, built-in. Identified as `audi`.
1154	pub const AUTHORITY_DISCOVERY: KeyTypeId = KeyTypeId(*b"audi");
1155	/// Key type for staking, built-in. Identified as `stak`.
1156	pub const STAKING: KeyTypeId = KeyTypeId(*b"stak");
1157	/// A key type for signing statements
1158	pub const STATEMENT: KeyTypeId = KeyTypeId(*b"stmt");
1159	/// Key type for Mixnet module, used to sign key-exchange public keys. Identified as `mixn`.
1160	pub const MIXNET: KeyTypeId = KeyTypeId(*b"mixn");
1161	/// A key type ID useful for tests.
1162	pub const DUMMY: KeyTypeId = KeyTypeId(*b"dumy");
1163}
1164
1165/// Create random values of `Self` given a stream of entropy.
1166pub trait FromEntropy: Sized {
1167	/// Create a random value of `Self` given a stream of random bytes on `input`. May only fail if
1168	/// `input` has an error.
1169	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
1178/// Create the unit type for any given input.
1179impl 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		// valid hex but invalid length will be treated as ss58.
1482		assert_eq!(
1483			AccountId32::from_str(
1484				"55c55177d67b064bb5d189a3e1ddad9bc6646e02e64d6e308f5acbb1533ac430d"
1485			)
1486			.unwrap_err(),
1487			"invalid ss58 address.",
1488		);
1489	}
1490}