sp_core/
ecdsa.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//! Simple ECDSA secp256k1 API.
19
20use crate::{
21	crypto::{
22		CryptoType, CryptoTypeId, DeriveError, DeriveJunction, Pair as TraitPair, PublicBytes,
23		SecretStringError, SignatureBytes,
24	},
25	proof_of_possession::NonAggregatable,
26};
27
28#[cfg(not(feature = "std"))]
29use alloc::vec::Vec;
30#[cfg(not(feature = "std"))]
31use k256::ecdsa::{SigningKey as SecretKey, VerifyingKey};
32#[cfg(feature = "std")]
33use secp256k1::{
34	ecdsa::{RecoverableSignature, RecoveryId},
35	Message, PublicKey, SecretKey, SECP256K1,
36};
37
38#[cfg(all(feature = "std", feature = "full_crypto"))]
39type NativeSignature = secp256k1::ecdsa::RecoverableSignature;
40
41#[cfg(all(not(feature = "std"), feature = "full_crypto"))]
42type NativeSignature = (k256::ecdsa::Signature, k256::ecdsa::RecoveryId);
43
44/// An identifier used to match public keys against ecdsa keys
45pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"ecds");
46
47/// The byte length of public key
48pub const PUBLIC_KEY_SERIALIZED_SIZE: usize = 33;
49
50/// The byte length of signature
51pub const SIGNATURE_SERIALIZED_SIZE: usize = 65;
52
53#[doc(hidden)]
54#[derive(Clone)]
55pub struct EcdsaTag;
56
57#[doc(hidden)]
58#[derive(Clone)]
59pub struct EcdsaKeccakTag;
60
61/// The secret seed.
62///
63/// The raw secret seed, which can be used to create the `Pair`.
64type Seed = [u8; 32];
65
66#[doc(hidden)]
67pub type GenericPublic<TAG> = PublicBytes<PUBLIC_KEY_SERIALIZED_SIZE, TAG>;
68
69/// The ECDSA compressed public key.
70///
71/// Uses blake2 during key recovery.
72pub type Public = GenericPublic<EcdsaTag>;
73
74/// The ECDSA compressed public key.
75///
76/// Uses keccak during key recovery.
77pub type KeccakPublic = GenericPublic<EcdsaKeccakTag>;
78
79impl<TAG> GenericPublic<TAG> {
80	/// Create a new instance from the given full public key.
81	///
82	/// This will convert the full public key into the compressed format.
83	pub fn from_full(full: &[u8]) -> Result<Self, ()> {
84		let mut tagged_full = [0u8; 65];
85		let full = if full.len() == 64 {
86			// Tag it as uncompressed public key.
87			tagged_full[0] = 0x04;
88			tagged_full[1..].copy_from_slice(full);
89			&tagged_full
90		} else {
91			full
92		};
93		#[cfg(feature = "std")]
94		let pubkey = PublicKey::from_slice(&full);
95		#[cfg(not(feature = "std"))]
96		let pubkey = VerifyingKey::from_sec1_bytes(&full);
97		pubkey.map(|k| k.into()).map_err(|_| ())
98	}
99}
100
101impl<TAG> PartialEq<[u8; 33]> for GenericPublic<TAG> {
102	fn eq(&self, other: &[u8; 33]) -> bool {
103		&self.0 == other
104	}
105}
106
107#[cfg(feature = "std")]
108impl<TAG> From<PublicKey> for GenericPublic<TAG> {
109	fn from(pubkey: PublicKey) -> Self {
110		Self::from(pubkey.serialize())
111	}
112}
113
114#[cfg(not(feature = "std"))]
115impl<TAG> From<VerifyingKey> for GenericPublic<TAG> {
116	fn from(pubkey: VerifyingKey) -> Self {
117		Self::try_from(&pubkey.to_sec1_bytes()[..])
118			.expect("Valid key is serializable to [u8; 33]. qed.")
119	}
120}
121
122#[cfg(feature = "full_crypto")]
123impl<TAG> From<GenericPair<GenericPublic<TAG>>> for GenericPublic<TAG> {
124	fn from(x: GenericPair<GenericPublic<TAG>>) -> Self {
125		x.public
126	}
127}
128
129#[doc(hidden)]
130pub type GenericSignature<PUBLIC> = SignatureBytes<SIGNATURE_SERIALIZED_SIZE, PUBLIC>;
131
132/// A signature (a 512-bit value, plus 8 bits for recovery ID).
133///
134/// Uses blake2 during key recovery.
135pub type Signature = GenericSignature<Public>;
136
137/// A signature (a 512-bit value, plus 8 bits for recovery ID).
138///
139/// Uses keccak during key recovery.
140pub type KeccakSignature = GenericSignature<KeccakPublic>;
141
142/// A signature that allows recovering the public key from a message.
143pub trait Recover: seal::Sealed {
144	/// The public key that will be recovered from the signature.
145	type Public;
146
147	/// Recover the public key from this signature and a pre-hashed message.
148	fn recover_prehashed(&self, message: &[u8; 32]) -> Option<Self::Public>;
149
150	/// Recover the public key from this signature and a message.
151	fn recover<M: AsRef<[u8]>>(&self, message: M) -> Option<Self::Public>;
152}
153
154#[cfg(feature = "std")]
155impl<PUBLIC: From<PublicKey>> GenericSignature<PUBLIC> {
156	/// Recover the public key from this signature and a pre-hashed message.
157	pub fn recover_prehashed(&self, message: &[u8; 32]) -> Option<PUBLIC> {
158		let rid = RecoveryId::from_i32(self.0[64] as i32).ok()?;
159		let sig = RecoverableSignature::from_compact(&self.0[..64], rid).ok()?;
160		let message = Message::from_digest_slice(message).expect("Message is a 32 bytes hash; qed");
161		SECP256K1.recover_ecdsa(&message, &sig).ok().map(From::from)
162	}
163}
164
165#[cfg(not(feature = "std"))]
166impl<PUBLIC: From<VerifyingKey>> GenericSignature<PUBLIC> {
167	/// Recover the public key from this signature and a pre-hashed message.
168	pub fn recover_prehashed(&self, message: &[u8; 32]) -> Option<PUBLIC> {
169		let rid = k256::ecdsa::RecoveryId::from_byte(self.0[64])?;
170		let sig = k256::ecdsa::Signature::from_bytes((&self.0[..64]).into()).ok()?;
171		VerifyingKey::recover_from_prehash(message, &sig, rid).map(From::from).ok()
172	}
173}
174
175/// Proof of Possession is the same as Signature.
176///
177/// Uses blake2 during key recovery.
178pub type ProofOfPossession = Signature;
179
180/// Proof of Possession is the same as Signature.
181///
182/// Uses keccak during key recovery.
183pub type KeccakProofOfPossession = KeccakSignature;
184
185impl Signature {
186	/// Recover the public key from this signature and a message.
187	pub fn recover<M: AsRef<[u8]>>(&self, message: M) -> Option<Public> {
188		self.recover_prehashed(&sp_crypto_hashing::blake2_256(message.as_ref()))
189	}
190}
191
192impl KeccakSignature {
193	/// Recover the public key from this signature and a message.
194	pub fn recover<M: AsRef<[u8]>>(&self, message: M) -> Option<KeccakPublic> {
195		self.recover_prehashed(&sp_crypto_hashing::keccak_256(message.as_ref()))
196	}
197}
198
199impl Recover for Signature {
200	type Public = Public;
201
202	fn recover_prehashed(&self, message: &[u8; 32]) -> Option<Self::Public> {
203		self.recover_prehashed(message)
204	}
205
206	fn recover<M: AsRef<[u8]>>(&self, message: M) -> Option<Self::Public> {
207		self.recover(message)
208	}
209}
210
211impl Recover for KeccakSignature {
212	type Public = KeccakPublic;
213
214	fn recover_prehashed(&self, message: &[u8; 32]) -> Option<Self::Public> {
215		self.recover_prehashed(message)
216	}
217
218	fn recover<M: AsRef<[u8]>>(&self, message: M) -> Option<Self::Public> {
219		self.recover(message)
220	}
221}
222
223#[cfg(not(feature = "std"))]
224impl<PUBLIC> From<(k256::ecdsa::Signature, k256::ecdsa::RecoveryId)> for GenericSignature<PUBLIC> {
225	fn from(recsig: (k256::ecdsa::Signature, k256::ecdsa::RecoveryId)) -> Self {
226		let mut r = Self::default();
227		r.0[..64].copy_from_slice(&recsig.0.to_bytes());
228		r.0[64] = recsig.1.to_byte();
229		r
230	}
231}
232
233#[cfg(feature = "std")]
234impl<PUBLIC> From<RecoverableSignature> for GenericSignature<PUBLIC> {
235	fn from(recsig: RecoverableSignature) -> Self {
236		let mut r = Self::default();
237		let (recid, sig) = recsig.serialize_compact();
238		r.0[..64].copy_from_slice(&sig);
239		// This is safe due to the limited range of possible valid ids.
240		r.0[64] = recid.to_i32() as u8;
241		r
242	}
243}
244
245/// Derive a single hard junction.
246fn derive_hard_junction(secret_seed: &Seed, cc: &[u8; 32]) -> Seed {
247	use codec::Encode;
248	("Secp256k1HDKD", secret_seed, cc).using_encoded(sp_crypto_hashing::blake2_256)
249}
250
251#[derive(Clone)]
252#[doc(hidden)]
253pub struct GenericPair<PUBLIC> {
254	public: PUBLIC,
255	secret: SecretKey,
256}
257
258/// An ecdsa key pair using the blake2 algorithm for hashing the message.
259pub type Pair = GenericPair<Public>;
260
261/// An ecdsa key pair using the keccak algorithm for hashing the message.
262pub type KeccakPair = GenericPair<KeccakPublic>;
263
264impl TraitPair for Pair {
265	type Public = Public;
266	type Seed = Seed;
267	type Signature = Signature;
268	type ProofOfPossession = ProofOfPossession;
269
270	fn from_seed_slice(seed_slice: &[u8]) -> Result<Self, SecretStringError> {
271		Self::from_seed_slice(seed_slice)
272	}
273
274	fn derive<Iter: Iterator<Item = DeriveJunction>>(
275		&self,
276		path: Iter,
277		_seed: Option<Seed>,
278	) -> Result<(Self, Option<Seed>), DeriveError> {
279		self.derive(path)
280	}
281
282	fn public(&self) -> Self::Public {
283		self.public
284	}
285
286	#[cfg(feature = "full_crypto")]
287	fn sign(&self, message: &[u8]) -> Self::Signature {
288		self.sign(message)
289	}
290
291	/// Verify a signature on a message. Returns true if the signature is good.
292	fn verify<M: AsRef<[u8]>>(sig: &Self::Signature, message: M, public: &Public) -> bool {
293		Self::verify(sig, message, public)
294	}
295
296	/// Return a vec filled with raw data.
297	fn to_raw_vec(&self) -> Vec<u8> {
298		self.to_raw_vec()
299	}
300}
301
302impl TraitPair for KeccakPair {
303	type Public = KeccakPublic;
304	type Seed = Seed;
305	type Signature = KeccakSignature;
306	type ProofOfPossession = KeccakProofOfPossession;
307
308	fn from_seed_slice(seed_slice: &[u8]) -> Result<Self, SecretStringError> {
309		Self::from_seed_slice(seed_slice)
310	}
311
312	fn derive<Iter: Iterator<Item = DeriveJunction>>(
313		&self,
314		path: Iter,
315		_seed: Option<Seed>,
316	) -> Result<(Self, Option<Seed>), DeriveError> {
317		self.derive(path)
318	}
319
320	fn public(&self) -> Self::Public {
321		self.public
322	}
323
324	#[cfg(feature = "full_crypto")]
325	fn sign(&self, message: &[u8]) -> Self::Signature {
326		self.sign(message)
327	}
328
329	/// Verify a signature on a message. Returns true if the signature is good.
330	fn verify<M: AsRef<[u8]>>(sig: &Self::Signature, message: M, public: &Self::Public) -> bool {
331		Self::verify(sig, message, public)
332	}
333
334	/// Return a vec filled with raw data.
335	fn to_raw_vec(&self) -> Vec<u8> {
336		self.to_raw_vec()
337	}
338}
339
340impl<PUBLIC> GenericPair<PUBLIC>
341where
342	Self: TraitPair<Seed = Seed, Signature: Recover>,
343	<<Self as TraitPair>::Signature as Recover>::Public: PartialEq<PUBLIC>,
344	PUBLIC: PartialEq<[u8; 33]>,
345{
346	/// Get the seed for this key.
347	pub fn seed(&self) -> Seed {
348		#[cfg(feature = "std")]
349		{
350			self.secret.secret_bytes()
351		}
352		#[cfg(not(feature = "std"))]
353		{
354			self.secret.to_bytes().into()
355		}
356	}
357
358	/// Exactly as `from_string` except that if no matches are found then, the the first 32
359	/// characters are taken (padded with spaces as necessary) and used as the MiniSecretKey.
360	#[cfg(feature = "std")]
361	pub fn from_legacy_string(s: &str, password_override: Option<&str>) -> Self {
362		Self::from_string(s, password_override).unwrap_or_else(|_| {
363			let mut padded_seed: Seed = [b' '; 32];
364			let len = s.len().min(32);
365			padded_seed[..len].copy_from_slice(&s.as_bytes()[..len]);
366			Self::from_seed(&padded_seed)
367		})
368	}
369
370	/// Verify a signature on a pre-hashed message. Return `true` if the signature is valid
371	/// and thus matches the given `public` key.
372	pub fn verify_prehashed(
373		sig: &<Self as TraitPair>::Signature,
374		message: &[u8; 32],
375		public: &PUBLIC,
376	) -> bool {
377		match sig.recover_prehashed(message) {
378			Some(actual) => actual == *public,
379			None => false,
380		}
381	}
382
383	/// Verify a signature on a message. Returns true if the signature is good.
384	/// Parses Signature using parse_overflowing_slice.
385	#[deprecated(note = "please use `verify` instead")]
386	pub fn verify_deprecated<M: AsRef<[u8]>>(sig: &Signature, message: M, pubkey: &Public) -> bool {
387		let message =
388			libsecp256k1::Message::parse(&sp_crypto_hashing::blake2_256(message.as_ref()));
389
390		let parse_signature_overflowing = |x: [u8; SIGNATURE_SERIALIZED_SIZE]| {
391			let sig = libsecp256k1::Signature::parse_overflowing_slice(&x[..64]).ok()?;
392			let rid = libsecp256k1::RecoveryId::parse(x[64]).ok()?;
393			Some((sig, rid))
394		};
395
396		let (sig, rid) = match parse_signature_overflowing(sig.0) {
397			Some(sigri) => sigri,
398			_ => return false,
399		};
400		match libsecp256k1::recover(&message, &sig, &rid) {
401			Ok(actual) => pubkey == &actual.serialize_compressed(),
402			_ => false,
403		}
404	}
405
406	fn derive<Iter: Iterator<Item = DeriveJunction>>(
407		&self,
408		path: Iter,
409	) -> Result<(Self, Option<Seed>), DeriveError> {
410		let mut acc = self.seed();
411		for j in path {
412			match j {
413				DeriveJunction::Soft(_cc) => return Err(DeriveError::SoftKeyInPath),
414				DeriveJunction::Hard(cc) => acc = derive_hard_junction(&acc, &cc),
415			}
416		}
417		Ok((Self::from_seed(&acc), Some(acc)))
418	}
419
420	fn verify<M: AsRef<[u8]>>(
421		sig: &<Self as TraitPair>::Signature,
422		message: M,
423		public: &PUBLIC,
424	) -> bool {
425		sig.recover(message).map(|actual| actual == *public).unwrap_or_default()
426	}
427
428	fn to_raw_vec(&self) -> Vec<u8> {
429		self.seed().to_vec()
430	}
431}
432
433#[cfg(feature = "std")]
434impl<PUBLIC: From<PublicKey>> GenericPair<PUBLIC> {
435	fn from_seed_slice(seed_slice: &[u8]) -> Result<Self, SecretStringError> {
436		let secret =
437			SecretKey::from_slice(seed_slice).map_err(|_| SecretStringError::InvalidSeedLength)?;
438		Ok(Self { public: PublicKey::from_secret_key(&SECP256K1, &secret).into(), secret })
439	}
440}
441
442#[cfg(not(feature = "std"))]
443impl<PUBLIC: From<VerifyingKey>> GenericPair<PUBLIC> {
444	fn from_seed_slice(seed_slice: &[u8]) -> Result<Self, SecretStringError> {
445		let secret =
446			SecretKey::from_slice(seed_slice).map_err(|_| SecretStringError::InvalidSeedLength)?;
447		Ok(Self { public: VerifyingKey::from(&secret).into(), secret })
448	}
449}
450
451#[cfg(feature = "full_crypto")]
452impl<PUBLIC> GenericPair<PUBLIC>
453where
454	Self: TraitPair,
455	<Self as TraitPair>::Signature: From<NativeSignature>,
456{
457	/// Sign a pre-hashed message
458	pub fn sign_prehashed(&self, message: &[u8; 32]) -> <Self as TraitPair>::Signature {
459		#[cfg(feature = "std")]
460		{
461			let message =
462				Message::from_digest_slice(message).expect("Message is a 32 bytes hash; qed");
463			SECP256K1.sign_ecdsa_recoverable(&message, &self.secret).into()
464		}
465
466		#[cfg(not(feature = "std"))]
467		{
468			// Signing fails only if the `message` number of bytes is less than the field length
469			// (unfallible as we're using a fixed message length of 32).
470			self.secret
471				.sign_prehash_recoverable(message)
472				.expect("Signing can't fail when using 32 bytes message hash. qed.")
473				.into()
474		}
475	}
476}
477
478#[cfg(feature = "full_crypto")]
479impl Pair
480where
481	<Self as TraitPair>::Signature: From<NativeSignature>,
482{
483	fn sign(&self, message: &[u8]) -> Signature {
484		self.sign_prehashed(&sp_crypto_hashing::blake2_256(message))
485	}
486}
487
488#[cfg(feature = "full_crypto")]
489impl KeccakPair
490where
491	<Self as TraitPair>::Signature: From<NativeSignature>,
492{
493	fn sign(&self, message: &[u8]) -> KeccakSignature {
494		self.sign_prehashed(&sp_crypto_hashing::keccak_256(message))
495	}
496}
497
498// The `secp256k1` backend doesn't implement cleanup for their private keys.
499// Currently we should take care of wiping the secret from memory.
500// NOTE: this solution is not effective when `Pair` is moved around memory.
501// The very same problem affects other cryptographic backends that are just using
502// `zeroize`for their secrets.
503#[cfg(feature = "std")]
504impl<PUBLIC> Drop for GenericPair<PUBLIC> {
505	fn drop(&mut self) {
506		self.secret.non_secure_erase()
507	}
508}
509
510impl CryptoType for Public {
511	type Pair = Pair;
512}
513
514impl CryptoType for KeccakPublic {
515	type Pair = KeccakPair;
516}
517
518impl CryptoType for Signature {
519	type Pair = Pair;
520}
521
522impl CryptoType for KeccakSignature {
523	type Pair = KeccakPair;
524}
525
526impl CryptoType for Pair {
527	type Pair = Self;
528}
529
530impl CryptoType for KeccakPair {
531	type Pair = Self;
532}
533
534impl NonAggregatable for Pair {}
535
536mod seal {
537	pub trait Sealed {}
538	impl Sealed for super::Signature {}
539	impl Sealed for super::KeccakSignature {}
540}
541
542#[cfg(test)]
543mod test {
544	use super::*;
545	use crate::{
546		crypto::{
547			set_default_ss58_version, PublicError, Ss58AddressFormat, Ss58AddressFormatRegistry,
548			Ss58Codec, DEV_PHRASE,
549		},
550		proof_of_possession::{ProofOfPossessionGenerator, ProofOfPossessionVerifier},
551	};
552	use serde_json;
553
554	#[test]
555	fn default_phrase_should_be_used() {
556		assert_eq!(
557			Pair::from_string("//Alice///password", None).unwrap().public(),
558			Pair::from_string(&format!("{}//Alice", DEV_PHRASE), Some("password"))
559				.unwrap()
560				.public(),
561		);
562	}
563
564	#[test]
565	fn seed_and_derive_should_work() {
566		let seed = array_bytes::hex2array_unchecked(
567			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
568		);
569		let pair = Pair::from_seed(&seed);
570		assert_eq!(pair.seed(), seed);
571		let path = vec![DeriveJunction::Hard([0u8; 32])];
572		let derived = pair.derive(path.into_iter()).ok().unwrap();
573		assert_eq!(
574			derived.0.seed(),
575			array_bytes::hex2array_unchecked::<_, 32>(
576				"b8eefc4937200a8382d00050e050ced2d4ab72cc2ef1b061477afb51564fdd61"
577			)
578		);
579	}
580
581	#[test]
582	fn test_vector_should_work() {
583		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
584			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
585		));
586		let public = pair.public();
587		assert_eq!(
588			public,
589			Public::from_full(
590				&array_bytes::hex2bytes_unchecked("8db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd913ebbe148dd17c56551a52952371071a6c604b3f3abe8f2c8fa742158ea6dd7d4"),
591			).unwrap(),
592		);
593		let message = b"";
594		let signature = array_bytes::hex2array_unchecked("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00");
595		let signature = Signature::from_raw(signature);
596		assert!(pair.sign(&message[..]) == signature);
597		assert!(Pair::verify(&signature, &message[..], &public));
598	}
599
600	#[test]
601	fn test_vector_by_string_should_work() {
602		let pair = Pair::from_string(
603			"0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
604			None,
605		)
606		.unwrap();
607		let public = pair.public();
608		assert_eq!(
609			public,
610			Public::from_full(
611				&array_bytes::hex2bytes_unchecked("8db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd913ebbe148dd17c56551a52952371071a6c604b3f3abe8f2c8fa742158ea6dd7d4"),
612			).unwrap(),
613		);
614		let message = b"";
615		let signature = array_bytes::hex2array_unchecked("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00");
616		let signature = Signature::from_raw(signature);
617		assert!(pair.sign(&message[..]) == signature);
618		assert!(Pair::verify(&signature, &message[..], &public));
619	}
620
621	#[test]
622	fn generated_pair_should_work() {
623		let (pair, _) = Pair::generate();
624		let public = pair.public();
625		let message = b"Something important";
626		let signature = pair.sign(&message[..]);
627		assert!(Pair::verify(&signature, &message[..], &public));
628		assert!(!Pair::verify(&signature, b"Something else", &public));
629	}
630
631	#[test]
632	fn generated_pair_should_work_keccak() {
633		let (pair, _) = KeccakPair::generate();
634		let public = pair.public();
635		let message = b"Something important";
636		let signature = pair.sign(&message[..]);
637		assert!(KeccakPair::verify(&signature, &message[..], &public));
638		assert!(!KeccakPair::verify(&signature, b"Something else", &public));
639	}
640
641	#[test]
642	fn seeded_pair_should_work() {
643		let pair = Pair::from_seed(b"12345678901234567890123456789012");
644		let public = pair.public();
645		assert_eq!(
646			public,
647			Public::from_full(
648				&array_bytes::hex2bytes_unchecked("5676109c54b9a16d271abeb4954316a40a32bcce023ac14c8e26e958aa68fba995840f3de562156558efbfdac3f16af0065e5f66795f4dd8262a228ef8c6d813"),
649			).unwrap(),
650		);
651		let message = array_bytes::hex2bytes_unchecked("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000");
652		let signature = pair.sign(&message[..]);
653		println!("Correct signature: {:?}", signature);
654		assert!(Pair::verify(&signature, &message[..], &public));
655		assert!(!Pair::verify(&signature, "Other message", &public));
656	}
657
658	#[test]
659	fn generate_with_phrase_recovery_possible() {
660		let (pair1, phrase, _) = Pair::generate_with_phrase(None);
661		let (pair2, _) = Pair::from_phrase(&phrase, None).unwrap();
662
663		assert_eq!(pair1.public(), pair2.public());
664	}
665
666	#[test]
667	fn generate_with_password_phrase_recovery_possible() {
668		let (pair1, phrase, _) = Pair::generate_with_phrase(Some("password"));
669		let (pair2, _) = Pair::from_phrase(&phrase, Some("password")).unwrap();
670
671		assert_eq!(pair1.public(), pair2.public());
672	}
673
674	#[test]
675	fn generate_with_phrase_should_be_recoverable_with_from_string() {
676		let (pair, phrase, seed) = Pair::generate_with_phrase(None);
677		let repair_seed = Pair::from_seed_slice(seed.as_ref()).expect("seed slice is valid");
678		assert_eq!(pair.public(), repair_seed.public());
679		assert_eq!(pair.secret, repair_seed.secret);
680		let (repair_phrase, reseed) =
681			Pair::from_phrase(phrase.as_ref(), None).expect("seed slice is valid");
682		assert_eq!(seed, reseed);
683		assert_eq!(pair.public(), repair_phrase.public());
684		assert_eq!(pair.secret, repair_phrase.secret);
685		let repair_string = Pair::from_string(phrase.as_str(), None).expect("seed slice is valid");
686		assert_eq!(pair.public(), repair_string.public());
687		assert_eq!(pair.secret, repair_string.secret);
688	}
689
690	#[test]
691	fn password_does_something() {
692		let (pair1, phrase, _) = Pair::generate_with_phrase(Some("password"));
693		let (pair2, _) = Pair::from_phrase(&phrase, None).unwrap();
694
695		assert_ne!(pair1.public(), pair2.public());
696		assert_ne!(pair1.secret, pair2.secret);
697	}
698
699	#[test]
700	fn ss58check_roundtrip_works() {
701		let pair = Pair::from_seed(b"12345678901234567890123456789012");
702		let public = pair.public();
703		let s = public.to_ss58check();
704		println!("Correct: {}", s);
705		let cmp = Public::from_ss58check(&s).unwrap();
706		assert_eq!(cmp, public);
707	}
708
709	#[test]
710	fn ss58check_format_check_works() {
711		let pair = Pair::from_seed(b"12345678901234567890123456789012");
712		let public = pair.public();
713		let format = Ss58AddressFormatRegistry::Reserved46Account.into();
714		let s = public.to_ss58check_with_version(format);
715		assert_eq!(Public::from_ss58check_with_version(&s), Err(PublicError::FormatNotAllowed));
716	}
717
718	#[test]
719	fn ss58check_full_roundtrip_works() {
720		let pair = Pair::from_seed(b"12345678901234567890123456789012");
721		let public = pair.public();
722		let format = Ss58AddressFormatRegistry::PolkadotAccount.into();
723		let s = public.to_ss58check_with_version(format);
724		let (k, f) = Public::from_ss58check_with_version(&s).unwrap();
725		assert_eq!(k, public);
726		assert_eq!(f, format);
727
728		let format = Ss58AddressFormat::custom(64);
729		let s = public.to_ss58check_with_version(format);
730		let (k, f) = Public::from_ss58check_with_version(&s).unwrap();
731		assert_eq!(k, public);
732		assert_eq!(f, format);
733	}
734
735	#[test]
736	fn ss58check_custom_format_works() {
737		// We need to run this test in its own process to not interfere with other tests running in
738		// parallel and also relying on the ss58 version.
739		if std::env::var("RUN_CUSTOM_FORMAT_TEST") == Ok("1".into()) {
740			use crate::crypto::Ss58AddressFormat;
741			// temp save default format version
742			let default_format = crate::crypto::default_ss58_version();
743			// set current ss58 version is custom "200" `Ss58AddressFormat::Custom(200)`
744
745			set_default_ss58_version(Ss58AddressFormat::custom(200));
746			// custom addr encoded by version 200
747			let addr = "4pbsSkWcBaYoFHrKJZp5fDVUKbqSYD9dhZZGvpp3vQ5ysVs5ybV";
748			Public::from_ss58check(addr).unwrap();
749
750			set_default_ss58_version(default_format);
751			// set current ss58 version to default version
752			let addr = "KWAfgC2aRG5UVD6CpbPQXCx4YZZUhvWqqAJE6qcYc9Rtr6g5C";
753			Public::from_ss58check(addr).unwrap();
754
755			println!("CUSTOM_FORMAT_SUCCESSFUL");
756		} else {
757			let executable = std::env::current_exe().unwrap();
758			let output = std::process::Command::new(executable)
759				.env("RUN_CUSTOM_FORMAT_TEST", "1")
760				.args(&["--nocapture", "ss58check_custom_format_works"])
761				.output()
762				.unwrap();
763
764			let output = String::from_utf8(output.stdout).unwrap();
765			assert!(output.contains("CUSTOM_FORMAT_SUCCESSFUL"));
766		}
767	}
768
769	#[test]
770	fn signature_serialization_works() {
771		let pair = Pair::from_seed(b"12345678901234567890123456789012");
772		let message = b"Something important";
773		let signature = pair.sign(&message[..]);
774		let serialized_signature = serde_json::to_string(&signature).unwrap();
775		// Signature is 65 bytes, so 130 chars + 2 quote chars
776		assert_eq!(serialized_signature.len(), SIGNATURE_SERIALIZED_SIZE * 2 + 2);
777		let signature = serde_json::from_str(&serialized_signature).unwrap();
778		assert!(Pair::verify(&signature, &message[..], &pair.public()));
779	}
780
781	#[test]
782	fn signature_serialization_doesnt_panic() {
783		fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
784			serde_json::from_str(text)
785		}
786		assert!(deserialize_signature("Not valid json.").is_err());
787		assert!(deserialize_signature("\"Not an actual signature.\"").is_err());
788		// Poorly-sized
789		assert!(deserialize_signature("\"abc123\"").is_err());
790	}
791
792	#[test]
793	fn sign_prehashed_works() {
794		let (pair, _, _) = Pair::generate_with_phrase(Some("password"));
795
796		// `msg` shouldn't be mangled
797		let msg = [0u8; 32];
798		let sig1 = pair.sign_prehashed(&msg);
799		let sig2: Signature = {
800			#[cfg(feature = "std")]
801			{
802				let message = Message::from_digest_slice(&msg).unwrap();
803				SECP256K1.sign_ecdsa_recoverable(&message, &pair.secret).into()
804			}
805			#[cfg(not(feature = "std"))]
806			{
807				pair.secret
808					.sign_prehash_recoverable(&msg)
809					.expect("signing may not fail (???). qed.")
810					.into()
811			}
812		};
813		assert_eq!(sig1, sig2);
814
815		// signature is actually different
816		let sig2 = pair.sign(&msg);
817		assert_ne!(sig1, sig2);
818
819		// using pre-hashed `msg` works
820		let msg = b"this should be hashed";
821		let sig1 = pair.sign_prehashed(&sp_crypto_hashing::blake2_256(msg));
822		let sig2 = pair.sign(msg);
823		assert_eq!(sig1, sig2);
824	}
825
826	#[test]
827	fn verify_prehashed_works() {
828		let (pair, _, _) = Pair::generate_with_phrase(Some("password"));
829
830		// `msg` and `sig` match
831		let msg = sp_crypto_hashing::blake2_256(b"this should be hashed");
832		let sig = pair.sign_prehashed(&msg);
833		assert!(Pair::verify_prehashed(&sig, &msg, &pair.public()));
834
835		// `msg` and `sig` don't match
836		let msg = sp_crypto_hashing::blake2_256(b"this is a different message");
837		assert!(!Pair::verify_prehashed(&sig, &msg, &pair.public()));
838	}
839
840	#[test]
841	fn recover_prehashed_works() {
842		let (pair, _, _) = Pair::generate_with_phrase(Some("password"));
843
844		// recovered key matches signing key
845		let msg = sp_crypto_hashing::blake2_256(b"this should be hashed");
846		let sig = pair.sign_prehashed(&msg);
847		let key = sig.recover_prehashed(&msg).unwrap();
848		assert_eq!(pair.public(), key);
849
850		// recovered key is useable
851		assert!(Pair::verify_prehashed(&sig, &msg, &key));
852
853		// recovered key and signing key don't match
854		let msg = sp_crypto_hashing::blake2_256(b"this is a different message");
855		let key = sig.recover_prehashed(&msg).unwrap();
856		assert_ne!(pair.public(), key);
857	}
858
859	#[test]
860	fn good_proof_of_possession_should_work_bad_proof_of_possession_should_fail() {
861		let owner = b"owner";
862		let not_owner = b"not owner";
863		let mut pair = Pair::from_seed(b"12345678901234567890123456789012");
864		let other_pair = Pair::from_seed(b"23456789012345678901234567890123");
865		let proof_of_possession = pair.generate_proof_of_possession(owner);
866		assert!(Pair::verify_proof_of_possession(owner, &proof_of_possession, &pair.public()));
867		assert_eq!(
868			Pair::verify_proof_of_possession(owner, &proof_of_possession, &other_pair.public()),
869			false
870		);
871		assert!(!Pair::verify_proof_of_possession(not_owner, &proof_of_possession, &pair.public()));
872	}
873}