referrerpolicy=no-referrer-when-downgrade

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