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::crypto::{
21	CryptoType, CryptoTypeId, DeriveError, DeriveJunction, Pair as TraitPair, PublicBytes,
22	SecretStringError, SignatureBytes,
23};
24
25#[cfg(not(feature = "std"))]
26use alloc::vec::Vec;
27#[cfg(not(feature = "std"))]
28use k256::ecdsa::{SigningKey as SecretKey, VerifyingKey};
29#[cfg(feature = "std")]
30use secp256k1::{
31	ecdsa::{RecoverableSignature, RecoveryId},
32	Message, PublicKey, SecretKey, SECP256K1,
33};
34
35/// An identifier used to match public keys against ecdsa keys
36pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"ecds");
37
38/// The byte length of public key
39pub const PUBLIC_KEY_SERIALIZED_SIZE: usize = 33;
40
41/// The byte length of signature
42pub const SIGNATURE_SERIALIZED_SIZE: usize = 65;
43
44#[doc(hidden)]
45pub struct EcdsaTag;
46
47/// The secret seed.
48///
49/// The raw secret seed, which can be used to create the `Pair`.
50type Seed = [u8; 32];
51
52/// The ECDSA compressed public key.
53pub type Public = PublicBytes<PUBLIC_KEY_SERIALIZED_SIZE, EcdsaTag>;
54
55impl Public {
56	/// Create a new instance from the given full public key.
57	///
58	/// This will convert the full public key into the compressed format.
59	pub fn from_full(full: &[u8]) -> Result<Self, ()> {
60		let mut tagged_full = [0u8; 65];
61		let full = if full.len() == 64 {
62			// Tag it as uncompressed public key.
63			tagged_full[0] = 0x04;
64			tagged_full[1..].copy_from_slice(full);
65			&tagged_full
66		} else {
67			full
68		};
69		#[cfg(feature = "std")]
70		let pubkey = PublicKey::from_slice(&full);
71		#[cfg(not(feature = "std"))]
72		let pubkey = VerifyingKey::from_sec1_bytes(&full);
73		pubkey.map(|k| k.into()).map_err(|_| ())
74	}
75}
76
77#[cfg(feature = "std")]
78impl From<PublicKey> for Public {
79	fn from(pubkey: PublicKey) -> Self {
80		Self::from(pubkey.serialize())
81	}
82}
83
84#[cfg(not(feature = "std"))]
85impl From<VerifyingKey> for Public {
86	fn from(pubkey: VerifyingKey) -> Self {
87		Self::try_from(&pubkey.to_sec1_bytes()[..])
88			.expect("Valid key is serializable to [u8; 33]. qed.")
89	}
90}
91
92#[cfg(feature = "full_crypto")]
93impl From<Pair> for Public {
94	fn from(x: Pair) -> Self {
95		x.public()
96	}
97}
98
99/// A signature (a 512-bit value, plus 8 bits for recovery ID).
100pub type Signature = SignatureBytes<SIGNATURE_SERIALIZED_SIZE, EcdsaTag>;
101
102impl Signature {
103	/// Recover the public key from this signature and a message.
104	pub fn recover<M: AsRef<[u8]>>(&self, message: M) -> Option<Public> {
105		self.recover_prehashed(&sp_crypto_hashing::blake2_256(message.as_ref()))
106	}
107
108	/// Recover the public key from this signature and a pre-hashed message.
109	pub fn recover_prehashed(&self, message: &[u8; 32]) -> Option<Public> {
110		#[cfg(feature = "std")]
111		{
112			let rid = RecoveryId::from_i32(self.0[64] as i32).ok()?;
113			let sig = RecoverableSignature::from_compact(&self.0[..64], rid).ok()?;
114			let message =
115				Message::from_digest_slice(message).expect("Message is a 32 bytes hash; qed");
116			SECP256K1.recover_ecdsa(&message, &sig).ok().map(Public::from)
117		}
118
119		#[cfg(not(feature = "std"))]
120		{
121			let rid = k256::ecdsa::RecoveryId::from_byte(self.0[64])?;
122			let sig = k256::ecdsa::Signature::from_bytes((&self.0[..64]).into()).ok()?;
123			VerifyingKey::recover_from_prehash(message, &sig, rid).map(Public::from).ok()
124		}
125	}
126}
127
128#[cfg(not(feature = "std"))]
129impl From<(k256::ecdsa::Signature, k256::ecdsa::RecoveryId)> for Signature {
130	fn from(recsig: (k256::ecdsa::Signature, k256::ecdsa::RecoveryId)) -> Signature {
131		let mut r = Self::default();
132		r.0[..64].copy_from_slice(&recsig.0.to_bytes());
133		r.0[64] = recsig.1.to_byte();
134		r
135	}
136}
137
138#[cfg(feature = "std")]
139impl From<RecoverableSignature> for Signature {
140	fn from(recsig: RecoverableSignature) -> Signature {
141		let mut r = Self::default();
142		let (recid, sig) = recsig.serialize_compact();
143		r.0[..64].copy_from_slice(&sig);
144		// This is safe due to the limited range of possible valid ids.
145		r.0[64] = recid.to_i32() as u8;
146		r
147	}
148}
149
150/// Derive a single hard junction.
151fn derive_hard_junction(secret_seed: &Seed, cc: &[u8; 32]) -> Seed {
152	use codec::Encode;
153	("Secp256k1HDKD", secret_seed, cc).using_encoded(sp_crypto_hashing::blake2_256)
154}
155
156/// A key pair.
157#[derive(Clone)]
158pub struct Pair {
159	public: Public,
160	secret: SecretKey,
161}
162
163impl TraitPair for Pair {
164	type Public = Public;
165	type Seed = Seed;
166	type Signature = Signature;
167
168	/// Make a new key pair from secret seed material. The slice must be 32 bytes long or it
169	/// will return `None`.
170	///
171	/// You should never need to use this; generate(), generate_with_phrase
172	fn from_seed_slice(seed_slice: &[u8]) -> Result<Pair, SecretStringError> {
173		#[cfg(feature = "std")]
174		{
175			let secret = SecretKey::from_slice(seed_slice)
176				.map_err(|_| SecretStringError::InvalidSeedLength)?;
177			Ok(Pair { public: PublicKey::from_secret_key(&SECP256K1, &secret).into(), secret })
178		}
179
180		#[cfg(not(feature = "std"))]
181		{
182			let secret = SecretKey::from_slice(seed_slice)
183				.map_err(|_| SecretStringError::InvalidSeedLength)?;
184			Ok(Pair { public: VerifyingKey::from(&secret).into(), secret })
185		}
186	}
187
188	/// Derive a child key from a series of given junctions.
189	fn derive<Iter: Iterator<Item = DeriveJunction>>(
190		&self,
191		path: Iter,
192		_seed: Option<Seed>,
193	) -> Result<(Pair, Option<Seed>), DeriveError> {
194		let mut acc = self.seed();
195		for j in path {
196			match j {
197				DeriveJunction::Soft(_cc) => return Err(DeriveError::SoftKeyInPath),
198				DeriveJunction::Hard(cc) => acc = derive_hard_junction(&acc, &cc),
199			}
200		}
201		Ok((Self::from_seed(&acc), Some(acc)))
202	}
203
204	/// Get the public key.
205	fn public(&self) -> Public {
206		self.public
207	}
208
209	/// Sign a message.
210	#[cfg(feature = "full_crypto")]
211	fn sign(&self, message: &[u8]) -> Signature {
212		self.sign_prehashed(&sp_crypto_hashing::blake2_256(message))
213	}
214
215	/// Verify a signature on a message. Returns true if the signature is good.
216	fn verify<M: AsRef<[u8]>>(sig: &Signature, message: M, public: &Public) -> bool {
217		sig.recover(message).map(|actual| actual == *public).unwrap_or_default()
218	}
219
220	/// Return a vec filled with raw data.
221	fn to_raw_vec(&self) -> Vec<u8> {
222		self.seed().to_vec()
223	}
224}
225
226impl Pair {
227	/// Get the seed for this key.
228	pub fn seed(&self) -> Seed {
229		#[cfg(feature = "std")]
230		{
231			self.secret.secret_bytes()
232		}
233		#[cfg(not(feature = "std"))]
234		{
235			self.secret.to_bytes().into()
236		}
237	}
238
239	/// Exactly as `from_string` except that if no matches are found then, the the first 32
240	/// characters are taken (padded with spaces as necessary) and used as the MiniSecretKey.
241	#[cfg(feature = "std")]
242	pub fn from_legacy_string(s: &str, password_override: Option<&str>) -> Pair {
243		Self::from_string(s, password_override).unwrap_or_else(|_| {
244			let mut padded_seed: Seed = [b' '; 32];
245			let len = s.len().min(32);
246			padded_seed[..len].copy_from_slice(&s.as_bytes()[..len]);
247			Self::from_seed(&padded_seed)
248		})
249	}
250
251	/// Sign a pre-hashed message
252	#[cfg(feature = "full_crypto")]
253	pub fn sign_prehashed(&self, message: &[u8; 32]) -> Signature {
254		#[cfg(feature = "std")]
255		{
256			let message =
257				Message::from_digest_slice(message).expect("Message is a 32 bytes hash; qed");
258			SECP256K1.sign_ecdsa_recoverable(&message, &self.secret).into()
259		}
260
261		#[cfg(not(feature = "std"))]
262		{
263			// Signing fails only if the `message` number of bytes is less than the field length
264			// (unfallible as we're using a fixed message length of 32).
265			self.secret
266				.sign_prehash_recoverable(message)
267				.expect("Signing can't fail when using 32 bytes message hash. qed.")
268				.into()
269		}
270	}
271
272	/// Verify a signature on a pre-hashed message. Return `true` if the signature is valid
273	/// and thus matches the given `public` key.
274	pub fn verify_prehashed(sig: &Signature, message: &[u8; 32], public: &Public) -> bool {
275		match sig.recover_prehashed(message) {
276			Some(actual) => actual == *public,
277			None => false,
278		}
279	}
280
281	/// Verify a signature on a message. Returns true if the signature is good.
282	/// Parses Signature using parse_overflowing_slice.
283	#[deprecated(note = "please use `verify` instead")]
284	pub fn verify_deprecated<M: AsRef<[u8]>>(sig: &Signature, message: M, pubkey: &Public) -> bool {
285		let message =
286			libsecp256k1::Message::parse(&sp_crypto_hashing::blake2_256(message.as_ref()));
287
288		let parse_signature_overflowing = |x: [u8; SIGNATURE_SERIALIZED_SIZE]| {
289			let sig = libsecp256k1::Signature::parse_overflowing_slice(&x[..64]).ok()?;
290			let rid = libsecp256k1::RecoveryId::parse(x[64]).ok()?;
291			Some((sig, rid))
292		};
293
294		let (sig, rid) = match parse_signature_overflowing(sig.0) {
295			Some(sigri) => sigri,
296			_ => return false,
297		};
298		match libsecp256k1::recover(&message, &sig, &rid) {
299			Ok(actual) => pubkey.0 == actual.serialize_compressed(),
300			_ => false,
301		}
302	}
303}
304
305// The `secp256k1` backend doesn't implement cleanup for their private keys.
306// Currently we should take care of wiping the secret from memory.
307// NOTE: this solution is not effective when `Pair` is moved around memory.
308// The very same problem affects other cryptographic backends that are just using
309// `zeroize`for their secrets.
310#[cfg(feature = "std")]
311impl Drop for Pair {
312	fn drop(&mut self) {
313		self.secret.non_secure_erase()
314	}
315}
316
317impl CryptoType for Public {
318	type Pair = Pair;
319}
320
321impl CryptoType for Signature {
322	type Pair = Pair;
323}
324
325impl CryptoType for Pair {
326	type Pair = Pair;
327}
328
329#[cfg(test)]
330mod test {
331	use super::*;
332	use crate::crypto::{
333		set_default_ss58_version, PublicError, Ss58AddressFormat, Ss58AddressFormatRegistry,
334		Ss58Codec, DEV_PHRASE,
335	};
336	use serde_json;
337
338	#[test]
339	fn default_phrase_should_be_used() {
340		assert_eq!(
341			Pair::from_string("//Alice///password", None).unwrap().public(),
342			Pair::from_string(&format!("{}//Alice", DEV_PHRASE), Some("password"))
343				.unwrap()
344				.public(),
345		);
346	}
347
348	#[test]
349	fn seed_and_derive_should_work() {
350		let seed = array_bytes::hex2array_unchecked(
351			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
352		);
353		let pair = Pair::from_seed(&seed);
354		assert_eq!(pair.seed(), seed);
355		let path = vec![DeriveJunction::Hard([0u8; 32])];
356		let derived = pair.derive(path.into_iter(), None).ok().unwrap();
357		assert_eq!(
358			derived.0.seed(),
359			array_bytes::hex2array_unchecked::<_, 32>(
360				"b8eefc4937200a8382d00050e050ced2d4ab72cc2ef1b061477afb51564fdd61"
361			)
362		);
363	}
364
365	#[test]
366	fn test_vector_should_work() {
367		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
368			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
369		));
370		let public = pair.public();
371		assert_eq!(
372			public,
373			Public::from_full(
374				&array_bytes::hex2bytes_unchecked("8db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd913ebbe148dd17c56551a52952371071a6c604b3f3abe8f2c8fa742158ea6dd7d4"),
375			).unwrap(),
376		);
377		let message = b"";
378		let signature = array_bytes::hex2array_unchecked("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00");
379		let signature = Signature::from_raw(signature);
380		assert!(pair.sign(&message[..]) == signature);
381		assert!(Pair::verify(&signature, &message[..], &public));
382	}
383
384	#[test]
385	fn test_vector_by_string_should_work() {
386		let pair = Pair::from_string(
387			"0x9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
388			None,
389		)
390		.unwrap();
391		let public = pair.public();
392		assert_eq!(
393			public,
394			Public::from_full(
395				&array_bytes::hex2bytes_unchecked("8db55b05db86c0b1786ca49f095d76344c9e6056b2f02701a7e7f3c20aabfd913ebbe148dd17c56551a52952371071a6c604b3f3abe8f2c8fa742158ea6dd7d4"),
396			).unwrap(),
397		);
398		let message = b"";
399		let signature = array_bytes::hex2array_unchecked("3dde91174bd9359027be59a428b8146513df80a2a3c7eda2194f64de04a69ab97b753169e94db6ffd50921a2668a48b94ca11e3d32c1ff19cfe88890aa7e8f3c00");
400		let signature = Signature::from_raw(signature);
401		assert!(pair.sign(&message[..]) == signature);
402		assert!(Pair::verify(&signature, &message[..], &public));
403	}
404
405	#[test]
406	fn generated_pair_should_work() {
407		let (pair, _) = Pair::generate();
408		let public = pair.public();
409		let message = b"Something important";
410		let signature = pair.sign(&message[..]);
411		assert!(Pair::verify(&signature, &message[..], &public));
412		assert!(!Pair::verify(&signature, b"Something else", &public));
413	}
414
415	#[test]
416	fn seeded_pair_should_work() {
417		let pair = Pair::from_seed(b"12345678901234567890123456789012");
418		let public = pair.public();
419		assert_eq!(
420			public,
421			Public::from_full(
422				&array_bytes::hex2bytes_unchecked("5676109c54b9a16d271abeb4954316a40a32bcce023ac14c8e26e958aa68fba995840f3de562156558efbfdac3f16af0065e5f66795f4dd8262a228ef8c6d813"),
423			).unwrap(),
424		);
425		let message = array_bytes::hex2bytes_unchecked("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000");
426		let signature = pair.sign(&message[..]);
427		println!("Correct signature: {:?}", signature);
428		assert!(Pair::verify(&signature, &message[..], &public));
429		assert!(!Pair::verify(&signature, "Other message", &public));
430	}
431
432	#[test]
433	fn generate_with_phrase_recovery_possible() {
434		let (pair1, phrase, _) = Pair::generate_with_phrase(None);
435		let (pair2, _) = Pair::from_phrase(&phrase, None).unwrap();
436
437		assert_eq!(pair1.public(), pair2.public());
438	}
439
440	#[test]
441	fn generate_with_password_phrase_recovery_possible() {
442		let (pair1, phrase, _) = Pair::generate_with_phrase(Some("password"));
443		let (pair2, _) = Pair::from_phrase(&phrase, Some("password")).unwrap();
444
445		assert_eq!(pair1.public(), pair2.public());
446	}
447
448	#[test]
449	fn generate_with_phrase_should_be_recoverable_with_from_string() {
450		let (pair, phrase, seed) = Pair::generate_with_phrase(None);
451		let repair_seed = Pair::from_seed_slice(seed.as_ref()).expect("seed slice is valid");
452		assert_eq!(pair.public(), repair_seed.public());
453		assert_eq!(pair.secret, repair_seed.secret);
454		let (repair_phrase, reseed) =
455			Pair::from_phrase(phrase.as_ref(), None).expect("seed slice is valid");
456		assert_eq!(seed, reseed);
457		assert_eq!(pair.public(), repair_phrase.public());
458		assert_eq!(pair.secret, repair_phrase.secret);
459		let repair_string = Pair::from_string(phrase.as_str(), None).expect("seed slice is valid");
460		assert_eq!(pair.public(), repair_string.public());
461		assert_eq!(pair.secret, repair_string.secret);
462	}
463
464	#[test]
465	fn password_does_something() {
466		let (pair1, phrase, _) = Pair::generate_with_phrase(Some("password"));
467		let (pair2, _) = Pair::from_phrase(&phrase, None).unwrap();
468
469		assert_ne!(pair1.public(), pair2.public());
470		assert_ne!(pair1.secret, pair2.secret);
471	}
472
473	#[test]
474	fn ss58check_roundtrip_works() {
475		let pair = Pair::from_seed(b"12345678901234567890123456789012");
476		let public = pair.public();
477		let s = public.to_ss58check();
478		println!("Correct: {}", s);
479		let cmp = Public::from_ss58check(&s).unwrap();
480		assert_eq!(cmp, public);
481	}
482
483	#[test]
484	fn ss58check_format_check_works() {
485		let pair = Pair::from_seed(b"12345678901234567890123456789012");
486		let public = pair.public();
487		let format = Ss58AddressFormatRegistry::Reserved46Account.into();
488		let s = public.to_ss58check_with_version(format);
489		assert_eq!(Public::from_ss58check_with_version(&s), Err(PublicError::FormatNotAllowed));
490	}
491
492	#[test]
493	fn ss58check_full_roundtrip_works() {
494		let pair = Pair::from_seed(b"12345678901234567890123456789012");
495		let public = pair.public();
496		let format = Ss58AddressFormatRegistry::PolkadotAccount.into();
497		let s = public.to_ss58check_with_version(format);
498		let (k, f) = Public::from_ss58check_with_version(&s).unwrap();
499		assert_eq!(k, public);
500		assert_eq!(f, format);
501
502		let format = Ss58AddressFormat::custom(64);
503		let s = public.to_ss58check_with_version(format);
504		let (k, f) = Public::from_ss58check_with_version(&s).unwrap();
505		assert_eq!(k, public);
506		assert_eq!(f, format);
507	}
508
509	#[test]
510	fn ss58check_custom_format_works() {
511		// We need to run this test in its own process to not interfere with other tests running in
512		// parallel and also relying on the ss58 version.
513		if std::env::var("RUN_CUSTOM_FORMAT_TEST") == Ok("1".into()) {
514			use crate::crypto::Ss58AddressFormat;
515			// temp save default format version
516			let default_format = crate::crypto::default_ss58_version();
517			// set current ss58 version is custom "200" `Ss58AddressFormat::Custom(200)`
518
519			set_default_ss58_version(Ss58AddressFormat::custom(200));
520			// custom addr encoded by version 200
521			let addr = "4pbsSkWcBaYoFHrKJZp5fDVUKbqSYD9dhZZGvpp3vQ5ysVs5ybV";
522			Public::from_ss58check(addr).unwrap();
523
524			set_default_ss58_version(default_format);
525			// set current ss58 version to default version
526			let addr = "KWAfgC2aRG5UVD6CpbPQXCx4YZZUhvWqqAJE6qcYc9Rtr6g5C";
527			Public::from_ss58check(addr).unwrap();
528
529			println!("CUSTOM_FORMAT_SUCCESSFUL");
530		} else {
531			let executable = std::env::current_exe().unwrap();
532			let output = std::process::Command::new(executable)
533				.env("RUN_CUSTOM_FORMAT_TEST", "1")
534				.args(&["--nocapture", "ss58check_custom_format_works"])
535				.output()
536				.unwrap();
537
538			let output = String::from_utf8(output.stdout).unwrap();
539			assert!(output.contains("CUSTOM_FORMAT_SUCCESSFUL"));
540		}
541	}
542
543	#[test]
544	fn signature_serialization_works() {
545		let pair = Pair::from_seed(b"12345678901234567890123456789012");
546		let message = b"Something important";
547		let signature = pair.sign(&message[..]);
548		let serialized_signature = serde_json::to_string(&signature).unwrap();
549		// Signature is 65 bytes, so 130 chars + 2 quote chars
550		assert_eq!(serialized_signature.len(), SIGNATURE_SERIALIZED_SIZE * 2 + 2);
551		let signature = serde_json::from_str(&serialized_signature).unwrap();
552		assert!(Pair::verify(&signature, &message[..], &pair.public()));
553	}
554
555	#[test]
556	fn signature_serialization_doesnt_panic() {
557		fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
558			serde_json::from_str(text)
559		}
560		assert!(deserialize_signature("Not valid json.").is_err());
561		assert!(deserialize_signature("\"Not an actual signature.\"").is_err());
562		// Poorly-sized
563		assert!(deserialize_signature("\"abc123\"").is_err());
564	}
565
566	#[test]
567	fn sign_prehashed_works() {
568		let (pair, _, _) = Pair::generate_with_phrase(Some("password"));
569
570		// `msg` shouldn't be mangled
571		let msg = [0u8; 32];
572		let sig1 = pair.sign_prehashed(&msg);
573		let sig2: Signature = {
574			#[cfg(feature = "std")]
575			{
576				let message = Message::from_digest_slice(&msg).unwrap();
577				SECP256K1.sign_ecdsa_recoverable(&message, &pair.secret).into()
578			}
579			#[cfg(not(feature = "std"))]
580			{
581				pair.secret
582					.sign_prehash_recoverable(&msg)
583					.expect("signing may not fail (???). qed.")
584					.into()
585			}
586		};
587		assert_eq!(sig1, sig2);
588
589		// signature is actually different
590		let sig2 = pair.sign(&msg);
591		assert_ne!(sig1, sig2);
592
593		// using pre-hashed `msg` works
594		let msg = b"this should be hashed";
595		let sig1 = pair.sign_prehashed(&sp_crypto_hashing::blake2_256(msg));
596		let sig2 = pair.sign(msg);
597		assert_eq!(sig1, sig2);
598	}
599
600	#[test]
601	fn verify_prehashed_works() {
602		let (pair, _, _) = Pair::generate_with_phrase(Some("password"));
603
604		// `msg` and `sig` match
605		let msg = sp_crypto_hashing::blake2_256(b"this should be hashed");
606		let sig = pair.sign_prehashed(&msg);
607		assert!(Pair::verify_prehashed(&sig, &msg, &pair.public()));
608
609		// `msg` and `sig` don't match
610		let msg = sp_crypto_hashing::blake2_256(b"this is a different message");
611		assert!(!Pair::verify_prehashed(&sig, &msg, &pair.public()));
612	}
613
614	#[test]
615	fn recover_prehashed_works() {
616		let (pair, _, _) = Pair::generate_with_phrase(Some("password"));
617
618		// recovered key matches signing key
619		let msg = sp_crypto_hashing::blake2_256(b"this should be hashed");
620		let sig = pair.sign_prehashed(&msg);
621		let key = sig.recover_prehashed(&msg).unwrap();
622		assert_eq!(pair.public(), key);
623
624		// recovered key is useable
625		assert!(Pair::verify_prehashed(&sig, &msg, &key));
626
627		// recovered key and signing key don't match
628		let msg = sp_crypto_hashing::blake2_256(b"this is a different message");
629		let key = sig.recover_prehashed(&msg).unwrap();
630		assert_ne!(pair.public(), key);
631	}
632}