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