tet_core/
sr25519.rs

1// This file is part of Tetcore.
2
3// Copyright (C) 2017-2021 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// tag::description[]
19//! Simple sr25519 (Schnorr-Ristretto) API.
20//!
21//! Note: `CHAIN_CODE_LENGTH` must be equal to `crate::crypto::JUNCTION_ID_LEN`
22//! for this to work.
23// end::description[]
24#[cfg(feature = "full_crypto")]
25use tetcore_std::vec::Vec;
26#[cfg(feature = "full_crypto")]
27use schnorrkel::{signing_context, ExpansionMode, Keypair, SecretKey, MiniSecretKey, PublicKey,
28	derive::{Derivation, ChainCode, CHAIN_CODE_LENGTH}
29};
30#[cfg(feature = "std")]
31use std::convert::TryFrom;
32#[cfg(feature = "std")]
33use tetcore_bip39::mini_secret_from_entropy;
34#[cfg(feature = "std")]
35use bip39::{Mnemonic, Language, MnemonicType};
36#[cfg(feature = "full_crypto")]
37use crate::crypto::{
38	Pair as TraitPair, DeriveJunction, Infallible, SecretStringError
39};
40#[cfg(feature = "std")]
41use crate::crypto::Ss58Codec;
42
43use crate::crypto::{Public as TraitPublic, CryptoTypePublicPair, UncheckedFrom, CryptoType, Derive, CryptoTypeId};
44use crate::hash::{H256, H512};
45use codec::{Encode, Decode};
46use tetcore_std::ops::Deref;
47
48#[cfg(feature = "std")]
49use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
50#[cfg(feature = "full_crypto")]
51use schnorrkel::keys::{MINI_SECRET_KEY_LENGTH, SECRET_KEY_LENGTH};
52use tp_runtime_interface::pass_by::PassByInner;
53
54// signing context
55#[cfg(feature = "full_crypto")]
56const SIGNING_CTX: &[u8] = b"tetcore";
57
58/// An identifier used to match public keys against sr25519 keys
59pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"sr25");
60
61/// An Schnorrkel/Ristretto x25519 ("sr25519") public key.
62#[cfg_attr(feature = "full_crypto", derive(Hash))]
63#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Encode, Decode, Default, PassByInner)]
64pub struct Public(pub [u8; 32]);
65
66/// An Schnorrkel/Ristretto x25519 ("sr25519") key pair.
67#[cfg(feature = "full_crypto")]
68pub struct Pair(Keypair);
69
70#[cfg(feature = "full_crypto")]
71impl Clone for Pair {
72	fn clone(&self) -> Self {
73		Pair(schnorrkel::Keypair {
74			public: self.0.public,
75			secret: schnorrkel::SecretKey::from_bytes(&self.0.secret.to_bytes()[..])
76				.expect("key is always the correct size; qed")
77		})
78	}
79}
80
81impl AsRef<[u8; 32]> for Public {
82	fn as_ref(&self) -> &[u8; 32] {
83		&self.0
84	}
85}
86
87impl AsRef<[u8]> for Public {
88	fn as_ref(&self) -> &[u8] {
89		&self.0[..]
90	}
91}
92
93impl AsMut<[u8]> for Public {
94	fn as_mut(&mut self) -> &mut [u8] {
95		&mut self.0[..]
96	}
97}
98
99impl Deref for Public {
100	type Target = [u8];
101
102	fn deref(&self) -> &Self::Target {
103		&self.0
104	}
105}
106
107impl From<Public> for [u8; 32] {
108	fn from(x: Public) -> [u8; 32] {
109		x.0
110	}
111}
112
113impl From<Public> for H256 {
114	fn from(x: Public) -> H256 {
115		x.0.into()
116	}
117}
118
119#[cfg(feature = "std")]
120impl std::str::FromStr for Public {
121	type Err = crate::crypto::PublicError;
122
123	fn from_str(s: &str) -> Result<Self, Self::Err> {
124		Self::from_ss58check(s)
125	}
126}
127
128impl tetcore_std::convert::TryFrom<&[u8]> for Public {
129	type Error = ();
130
131	fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
132		if data.len() == 32 {
133			let mut inner = [0u8; 32];
134			inner.copy_from_slice(data);
135			Ok(Public(inner))
136		} else {
137			Err(())
138		}
139	}
140}
141
142impl UncheckedFrom<[u8; 32]> for Public {
143	fn unchecked_from(x: [u8; 32]) -> Self {
144		Public::from_raw(x)
145	}
146}
147
148impl UncheckedFrom<H256> for Public {
149	fn unchecked_from(x: H256) -> Self {
150		Public::from_h256(x)
151	}
152}
153
154#[cfg(feature = "std")]
155impl std::fmt::Display for Public {
156	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
157		write!(f, "{}", self.to_ss58check())
158	}
159}
160
161impl tetcore_std::fmt::Debug for Public {
162	#[cfg(feature = "std")]
163	fn fmt(&self, f: &mut tetcore_std::fmt::Formatter) -> tetcore_std::fmt::Result {
164		let s = self.to_ss58check();
165		write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
166	}
167
168	#[cfg(not(feature = "std"))]
169	fn fmt(&self, _: &mut tetcore_std::fmt::Formatter) -> tetcore_std::fmt::Result {
170		Ok(())
171	}
172}
173
174#[cfg(feature = "std")]
175impl Serialize for Public {
176	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
177		serializer.serialize_str(&self.to_ss58check())
178	}
179}
180
181#[cfg(feature = "std")]
182impl<'de> Deserialize<'de> for Public {
183	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
184		Public::from_ss58check(&String::deserialize(deserializer)?)
185			.map_err(|e| de::Error::custom(format!("{:?}", e)))
186	}
187}
188
189/// An Schnorrkel/Ristretto x25519 ("sr25519") signature.
190///
191/// Instead of importing it for the local module, alias it to be available as a public type
192#[derive(Encode, Decode, PassByInner)]
193pub struct Signature(pub [u8; 64]);
194
195impl tetcore_std::convert::TryFrom<&[u8]> for Signature {
196	type Error = ();
197
198	fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
199		if data.len() == 64 {
200			let mut inner = [0u8; 64];
201			inner.copy_from_slice(data);
202			Ok(Signature(inner))
203		} else {
204			Err(())
205		}
206	}
207}
208
209#[cfg(feature = "std")]
210impl Serialize for Signature {
211	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer {
212		serializer.serialize_str(&hex::encode(self))
213	}
214}
215
216#[cfg(feature = "std")]
217impl<'de> Deserialize<'de> for Signature {
218	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de> {
219		let signature_hex = hex::decode(&String::deserialize(deserializer)?)
220			.map_err(|e| de::Error::custom(format!("{:?}", e)))?;
221		Ok(Signature::try_from(signature_hex.as_ref())
222			.map_err(|e| de::Error::custom(format!("{:?}", e)))?)
223	}
224}
225
226impl Clone for Signature {
227	fn clone(&self) -> Self {
228		let mut r = [0u8; 64];
229		r.copy_from_slice(&self.0[..]);
230		Signature(r)
231	}
232}
233
234impl Default for Signature {
235	fn default() -> Self {
236		Signature([0u8; 64])
237	}
238}
239
240impl PartialEq for Signature {
241	fn eq(&self, b: &Self) -> bool {
242		self.0[..] == b.0[..]
243	}
244}
245
246impl Eq for Signature {}
247
248impl From<Signature> for [u8; 64] {
249	fn from(v: Signature) -> [u8; 64] {
250		v.0
251	}
252}
253
254impl From<Signature> for H512 {
255	fn from(v: Signature) -> H512 {
256		H512::from(v.0)
257	}
258}
259
260impl AsRef<[u8; 64]> for Signature {
261	fn as_ref(&self) -> &[u8; 64] {
262		&self.0
263	}
264}
265
266impl AsRef<[u8]> for Signature {
267	fn as_ref(&self) -> &[u8] {
268		&self.0[..]
269	}
270}
271
272impl AsMut<[u8]> for Signature {
273	fn as_mut(&mut self) -> &mut [u8] {
274		&mut self.0[..]
275	}
276}
277
278#[cfg(feature = "full_crypto")]
279impl From<schnorrkel::Signature> for Signature {
280	fn from(s: schnorrkel::Signature) -> Signature {
281		Signature(s.to_bytes())
282	}
283}
284
285impl tetcore_std::fmt::Debug for Signature {
286	#[cfg(feature = "std")]
287	fn fmt(&self, f: &mut tetcore_std::fmt::Formatter) -> tetcore_std::fmt::Result {
288		write!(f, "{}", crate::hexdisplay::HexDisplay::from(&self.0))
289	}
290
291	#[cfg(not(feature = "std"))]
292	fn fmt(&self, _: &mut tetcore_std::fmt::Formatter) -> tetcore_std::fmt::Result {
293		Ok(())
294	}
295}
296
297#[cfg(feature = "full_crypto")]
298impl tetcore_std::hash::Hash for Signature {
299	fn hash<H: tetcore_std::hash::Hasher>(&self, state: &mut H) {
300		tetcore_std::hash::Hash::hash(&self.0[..], state);
301	}
302}
303
304/// A localized signature also contains sender information.
305/// NOTE: Encode and Decode traits are supported in ed25519 but not possible for now here.
306#[cfg(feature = "std")]
307#[derive(PartialEq, Eq, Clone, Debug)]
308pub struct LocalizedSignature {
309	/// The signer of the signature.
310	pub signer: Public,
311	/// The signature itself.
312	pub signature: Signature,
313}
314
315impl Signature {
316	/// A new instance from the given 64-byte `data`.
317	///
318	/// NOTE: No checking goes on to ensure this is a real signature. Only use
319	/// it if you are certain that the array actually is a signature, or if you
320	/// immediately verify the signature.  All functions that verify signatures
321	/// will fail if the `Signature` is not actually a valid signature.
322	pub fn from_raw(data: [u8; 64]) -> Signature {
323		Signature(data)
324	}
325
326	/// A new instance from the given slice that should be 64 bytes long.
327	///
328	/// NOTE: No checking goes on to ensure this is a real signature. Only use it if
329	/// you are certain that the array actually is a signature. GIGO!
330	pub fn from_slice(data: &[u8]) -> Self {
331		let mut r = [0u8; 64];
332		r.copy_from_slice(data);
333		Signature(r)
334	}
335
336	/// A new instance from an H512.
337	///
338	/// NOTE: No checking goes on to ensure this is a real signature. Only use it if
339	/// you are certain that the array actually is a signature. GIGO!
340	pub fn from_h512(v: H512) -> Signature {
341		Signature(v.into())
342	}
343}
344
345impl Derive for Public {
346	/// Derive a child key from a series of given junctions.
347	///
348	/// `None` if there are any hard junctions in there.
349	#[cfg(feature = "std")]
350	fn derive<Iter: Iterator<Item=DeriveJunction>>(&self, path: Iter) -> Option<Public> {
351		let mut acc = PublicKey::from_bytes(self.as_ref()).ok()?;
352		for j in path {
353			match j {
354				DeriveJunction::Soft(cc) => acc = acc.derived_key_simple(ChainCode(cc), &[]).0,
355				DeriveJunction::Hard(_cc) => return None,
356			}
357		}
358		Some(Self(acc.to_bytes()))
359	}
360}
361
362impl Public {
363	/// A new instance from the given 32-byte `data`.
364	///
365	/// NOTE: No checking goes on to ensure this is a real public key. Only use it if
366	/// you are certain that the array actually is a pubkey. GIGO!
367	pub fn from_raw(data: [u8; 32]) -> Self {
368		Public(data)
369	}
370
371	/// A new instance from an H256.
372	///
373	/// NOTE: No checking goes on to ensure this is a real public key. Only use it if
374	/// you are certain that the array actually is a pubkey. GIGO!
375	pub fn from_h256(x: H256) -> Self {
376		Public(x.into())
377	}
378
379	/// Return a slice filled with raw data.
380	pub fn as_array_ref(&self) -> &[u8; 32] {
381		self.as_ref()
382	}
383}
384
385impl TraitPublic for Public {
386	/// A new instance from the given slice that should be 32 bytes long.
387	///
388	/// NOTE: No checking goes on to ensure this is a real public key. Only use it if
389	/// you are certain that the array actually is a pubkey. GIGO!
390	fn from_slice(data: &[u8]) -> Self {
391		let mut r = [0u8; 32];
392		r.copy_from_slice(data);
393		Public(r)
394	}
395
396	fn to_public_crypto_pair(&self) -> CryptoTypePublicPair {
397		CryptoTypePublicPair(CRYPTO_ID, self.to_raw_vec())
398	}
399}
400
401impl From<Public> for CryptoTypePublicPair {
402	fn from(key: Public) -> Self {
403		(&key).into()
404	}
405}
406
407impl From<&Public> for CryptoTypePublicPair {
408	fn from(key: &Public) -> Self {
409		CryptoTypePublicPair(CRYPTO_ID, key.to_raw_vec())
410	}
411}
412
413#[cfg(feature = "std")]
414impl From<MiniSecretKey> for Pair {
415	fn from(sec: MiniSecretKey) -> Pair {
416		Pair(sec.expand_to_keypair(ExpansionMode::Ed25519))
417	}
418}
419
420#[cfg(feature = "std")]
421impl From<SecretKey> for Pair {
422	fn from(sec: SecretKey) -> Pair {
423		Pair(Keypair::from(sec))
424	}
425}
426
427#[cfg(feature = "full_crypto")]
428impl From<schnorrkel::Keypair> for Pair {
429	fn from(p: schnorrkel::Keypair) -> Pair {
430		Pair(p)
431	}
432}
433
434#[cfg(feature = "full_crypto")]
435impl From<Pair> for schnorrkel::Keypair {
436	fn from(p: Pair) -> schnorrkel::Keypair {
437		p.0
438	}
439}
440
441#[cfg(feature = "full_crypto")]
442impl AsRef<schnorrkel::Keypair> for Pair {
443	fn as_ref(&self) -> &schnorrkel::Keypair {
444		&self.0
445	}
446}
447
448/// Derive a single hard junction.
449#[cfg(feature = "full_crypto")]
450fn derive_hard_junction(secret: &SecretKey, cc: &[u8; CHAIN_CODE_LENGTH]) -> MiniSecretKey {
451	secret.hard_derive_mini_secret_key(Some(ChainCode(cc.clone())), b"").0
452}
453
454/// The raw secret seed, which can be used to recreate the `Pair`.
455#[cfg(feature = "full_crypto")]
456type Seed = [u8; MINI_SECRET_KEY_LENGTH];
457
458#[cfg(feature = "full_crypto")]
459impl TraitPair for Pair {
460	type Public = Public;
461	type Seed = Seed;
462	type Signature = Signature;
463	type DeriveError = Infallible;
464
465	/// Make a new key pair from raw secret seed material.
466	///
467	/// This is generated using schnorrkel's Mini-Secret-Keys.
468	///
469	/// A MiniSecretKey is literally what Ed25519 calls a SecretKey, which is just 32 random bytes.
470	fn from_seed(seed: &Seed) -> Pair {
471		Self::from_seed_slice(&seed[..])
472			.expect("32 bytes can always build a key; qed")
473	}
474
475	/// Get the public key.
476	fn public(&self) -> Public {
477		let mut pk = [0u8; 32];
478		pk.copy_from_slice(&self.0.public.to_bytes());
479		Public(pk)
480	}
481
482	/// Make a new key pair from secret seed material. The slice must be 32 bytes long or it
483	/// will return `None`.
484	///
485	/// You should never need to use this; generate(), generate_with_phrase(), from_phrase()
486	fn from_seed_slice(seed: &[u8]) -> Result<Pair, SecretStringError> {
487		match seed.len() {
488			MINI_SECRET_KEY_LENGTH => {
489				Ok(Pair(
490					MiniSecretKey::from_bytes(seed)
491						.map_err(|_| SecretStringError::InvalidSeed)?
492						.expand_to_keypair(ExpansionMode::Ed25519)
493				))
494			}
495			SECRET_KEY_LENGTH => {
496				Ok(Pair(
497					SecretKey::from_bytes(seed)
498						.map_err(|_| SecretStringError::InvalidSeed)?
499						.to_keypair()
500				))
501			}
502			_ => Err(SecretStringError::InvalidSeedLength)
503		}
504	}
505	#[cfg(feature = "std")]
506	fn generate_with_phrase(password: Option<&str>) -> (Pair, String, Seed) {
507		let mnemonic = Mnemonic::new(MnemonicType::Words12, Language::English);
508		let phrase = mnemonic.phrase();
509		let (pair, seed) = Self::from_phrase(phrase, password)
510			.expect("All phrases generated by Mnemonic are valid; qed");
511		(
512			pair,
513			phrase.to_owned(),
514			seed,
515		)
516	}
517	#[cfg(feature = "std")]
518	fn from_phrase(phrase: &str, password: Option<&str>) -> Result<(Pair, Seed), SecretStringError> {
519		Mnemonic::from_phrase(phrase, Language::English)
520			.map_err(|_| SecretStringError::InvalidPhrase)
521			.map(|m| Self::from_entropy(m.entropy(), password))
522	}
523
524	fn derive<Iter: Iterator<Item=DeriveJunction>>(&self,
525		path: Iter,
526		seed: Option<Seed>,
527	) -> Result<(Pair, Option<Seed>), Self::DeriveError> {
528		let seed = if let Some(s) = seed {
529			if let Ok(msk) = MiniSecretKey::from_bytes(&s) {
530				if msk.expand(ExpansionMode::Ed25519) == self.0.secret {
531					Some(msk)
532				} else { None }
533			} else { None }
534		} else { None };
535		let init = self.0.secret.clone();
536		let (result, seed) = path.fold((init, seed), |(acc, acc_seed), j| match (j, acc_seed) {
537			(DeriveJunction::Soft(cc), _) =>
538				(acc.derived_key_simple(ChainCode(cc), &[]).0, None),
539			(DeriveJunction::Hard(cc), maybe_seed) => {
540				let seed = derive_hard_junction(&acc, &cc);
541				(seed.expand(ExpansionMode::Ed25519), maybe_seed.map(|_| seed))
542			}
543		});
544		Ok((Self(result.into()), seed.map(|s| MiniSecretKey::to_bytes(&s))))
545	}
546
547	fn sign(&self, message: &[u8]) -> Signature {
548		let context = signing_context(SIGNING_CTX);
549		self.0.sign(context.bytes(message)).into()
550	}
551
552	fn verify<M: AsRef<[u8]>>(sig: &Self::Signature, message: M, pubkey: &Self::Public) -> bool {
553		Self::verify_weak(&sig.0[..], message, pubkey)
554	}
555
556	fn verify_weak<P: AsRef<[u8]>, M: AsRef<[u8]>>(sig: &[u8], message: M, pubkey: P) -> bool {
557		let signature = match schnorrkel::Signature::from_bytes(sig) {
558			Ok(signature) => signature,
559			Err(_) => return false,
560		};
561
562		let pub_key = match PublicKey::from_bytes(pubkey.as_ref()) {
563			Ok(pub_key) => pub_key,
564			Err(_) => return false,
565		};
566
567		pub_key.verify_simple(SIGNING_CTX, message.as_ref(), &signature).is_ok()
568	}
569
570	fn to_raw_vec(&self) -> Vec<u8> {
571		self.0.secret.to_bytes().to_vec()
572	}
573}
574
575#[cfg(feature = "std")]
576impl Pair {
577	/// Make a new key pair from binary data derived from a valid seed phrase.
578	///
579	/// This uses a key derivation function to convert the entropy into a seed, then returns
580	/// the pair generated from it.
581	pub fn from_entropy(entropy: &[u8], password: Option<&str>) -> (Pair, Seed) {
582		let mini_key: MiniSecretKey = mini_secret_from_entropy(entropy, password.unwrap_or(""))
583			.expect("32 bytes can always build a key; qed");
584
585		let kp = mini_key.expand_to_keypair(ExpansionMode::Ed25519);
586		(Pair(kp), mini_key.to_bytes())
587	}
588
589	/// Verify a signature on a message. Returns `true` if the signature is good.
590	/// Supports old 0.1.1 deprecated signatures and should be used only for backward
591	/// compatibility.
592	pub fn verify_deprecated<M: AsRef<[u8]>>(sig: &Signature, message: M, pubkey: &Public) -> bool {
593		// Match both schnorrkel 0.1.1 and 0.8.0+ signatures, supporting both wallets
594		// that have not been upgraded and those that have.
595		match PublicKey::from_bytes(pubkey.as_ref()) {
596			Ok(pk) => pk.verify_simple_preaudit_deprecated(
597				SIGNING_CTX, message.as_ref(), &sig.0[..],
598			).is_ok(),
599			Err(_) => false,
600		}
601	}
602}
603
604impl CryptoType for Public {
605	#[cfg(feature = "full_crypto")]
606	type Pair = Pair;
607}
608
609impl CryptoType for Signature {
610	#[cfg(feature = "full_crypto")]
611	type Pair = Pair;
612}
613
614#[cfg(feature = "full_crypto")]
615impl CryptoType for Pair {
616	type Pair = Pair;
617}
618
619/// Batch verification.
620///
621/// `messages`, `signatures` and `pub_keys` should all have equal length.
622///
623/// Returns `true` if all signatures are correct, `false` otherwise.
624#[cfg(feature = "std")]
625pub fn verify_batch(
626	messages: Vec<&[u8]>,
627	signatures: Vec<&Signature>,
628	pub_keys: Vec<&Public>,
629) -> bool {
630	let mut sr_pub_keys = Vec::with_capacity(pub_keys.len());
631	for pub_key in pub_keys {
632		match schnorrkel::PublicKey::from_bytes(pub_key.as_ref()) {
633			Ok(pk) => sr_pub_keys.push(pk),
634			Err(_) => return false,
635		};
636	}
637
638	let mut sr_signatures = Vec::with_capacity(signatures.len());
639	for signature in signatures {
640		match schnorrkel::Signature::from_bytes(signature.as_ref()) {
641			Ok(s) => sr_signatures.push(s),
642			Err(_) => return false
643		};
644	}
645
646	let mut messages: Vec<merlin::Transcript> = messages.into_iter().map(
647		|msg| signing_context(SIGNING_CTX).bytes(msg)
648	).collect();
649
650	schnorrkel::verify_batch(
651		&mut messages,
652		&sr_signatures,
653		&sr_pub_keys,
654		true,
655	).is_ok()
656}
657
658#[cfg(test)]
659mod compatibility_test {
660	use super::*;
661	use crate::crypto::DEV_PHRASE;
662	use hex_literal::hex;
663
664	// NOTE: tests to ensure addresses that are created with the `0.1.x` version (pre-audit) are
665	// still functional.
666
667	#[test]
668	fn derive_soft_known_pair_should_work() {
669		let pair = Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None).unwrap();
670		// known address of DEV_PHRASE with 1.1
671		let known = hex!("d6c71059dbbe9ad2b0ed3f289738b800836eb425544ce694825285b958ca755e");
672		assert_eq!(pair.public().to_raw_vec(), known);
673	}
674
675	#[test]
676	fn derive_hard_known_pair_should_work() {
677		let pair = Pair::from_string(&format!("{}//Alice", DEV_PHRASE), None).unwrap();
678		// known address of DEV_PHRASE with 1.1
679		let known = hex!("d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d");
680		assert_eq!(pair.public().to_raw_vec(), known);
681	}
682
683	#[test]
684	fn verify_known_old_message_should_work() {
685		let public = Public::from_raw(hex!("b4bfa1f7a5166695eb75299fd1c4c03ea212871c342f2c5dfea0902b2c246918"));
686		// signature generated by the 1.1 version with the same ^^ public key.
687		let signature = Signature::from_raw(hex!(
688			"5a9755f069939f45d96aaf125cf5ce7ba1db998686f87f2fb3cbdea922078741a73891ba265f70c31436e18a9acd14d189d73c12317ab6c313285cd938453202"
689		));
690		let message = b"Verifying that I am the owner of 5G9hQLdsKQswNPgB499DeA5PkFBbgkLPJWkkS6FAM6xGQ8xD. Hash: 221455a3\n";
691		assert!(Pair::verify_deprecated(&signature, &message[..], &public));
692		assert!(!Pair::verify(&signature, &message[..], &public));
693	}
694}
695
696#[cfg(test)]
697mod test {
698	use super::*;
699	use crate::crypto::{Ss58Codec, DEV_PHRASE, DEV_ADDRESS};
700	use hex_literal::hex;
701	use serde_json;
702
703	#[test]
704	fn default_phrase_should_be_used() {
705		assert_eq!(
706			Pair::from_string("//Alice///password", None).unwrap().public(),
707			Pair::from_string(&format!("{}//Alice", DEV_PHRASE), Some("password")).unwrap().public(),
708		);
709		assert_eq!(
710			Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None).as_ref().map(Pair::public),
711			Pair::from_string("/Alice", None).as_ref().map(Pair::public)
712		);
713	}
714
715	#[test]
716	fn default_address_should_be_used() {
717		assert_eq!(
718			Public::from_string(&format!("{}/Alice", DEV_ADDRESS)),
719			Public::from_string("/Alice")
720		);
721	}
722
723	#[test]
724	fn default_phrase_should_correspond_to_default_address() {
725		assert_eq!(
726			Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None).unwrap().public(),
727			Public::from_string(&format!("{}/Alice", DEV_ADDRESS)).unwrap(),
728		);
729		assert_eq!(
730			Pair::from_string("/Alice", None).unwrap().public(),
731			Public::from_string("/Alice").unwrap()
732		);
733	}
734
735	#[test]
736	fn derive_soft_should_work() {
737		let pair = Pair::from_seed(&hex!(
738			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
739		));
740		let derive_1 = pair.derive(Some(DeriveJunction::soft(1)).into_iter(), None).unwrap().0;
741		let derive_1b = pair.derive(Some(DeriveJunction::soft(1)).into_iter(), None).unwrap().0;
742		let derive_2 = pair.derive(Some(DeriveJunction::soft(2)).into_iter(), None).unwrap().0;
743		assert_eq!(derive_1.public(), derive_1b.public());
744		assert_ne!(derive_1.public(), derive_2.public());
745	}
746
747	#[test]
748	fn derive_hard_should_work() {
749		let pair = Pair::from_seed(&hex!(
750			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
751		));
752		let derive_1 = pair.derive(Some(DeriveJunction::hard(1)).into_iter(), None).unwrap().0;
753		let derive_1b = pair.derive(Some(DeriveJunction::hard(1)).into_iter(), None).unwrap().0;
754		let derive_2 = pair.derive(Some(DeriveJunction::hard(2)).into_iter(), None).unwrap().0;
755		assert_eq!(derive_1.public(), derive_1b.public());
756		assert_ne!(derive_1.public(), derive_2.public());
757	}
758
759	#[test]
760	fn derive_soft_public_should_work() {
761		let pair = Pair::from_seed(&hex!(
762			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
763		));
764		let path = Some(DeriveJunction::soft(1));
765		let pair_1 = pair.derive(path.clone().into_iter(), None).unwrap().0;
766		let public_1 = pair.public().derive(path.into_iter()).unwrap();
767		assert_eq!(pair_1.public(), public_1);
768	}
769
770	#[test]
771	fn derive_hard_public_should_fail() {
772		let pair = Pair::from_seed(&hex!(
773			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
774		));
775		let path = Some(DeriveJunction::hard(1));
776		assert!(pair.public().derive(path.into_iter()).is_none());
777	}
778
779	#[test]
780	fn sr_test_vector_should_work() {
781		let pair = Pair::from_seed(&hex!(
782			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60"
783		));
784		let public = pair.public();
785		assert_eq!(
786			public,
787			Public::from_raw(hex!(
788				"44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f"
789			))
790		);
791		let message = b"";
792		let signature = pair.sign(message);
793		assert!(Pair::verify(&signature, &message[..], &public));
794	}
795
796	#[test]
797	fn generated_pair_should_work() {
798		let (pair, _) = Pair::generate();
799		let public = pair.public();
800		let message = b"Something important";
801		let signature = pair.sign(&message[..]);
802		assert!(Pair::verify(&signature, &message[..], &public));
803	}
804
805	#[test]
806	fn messed_signature_should_not_work() {
807		let (pair, _) = Pair::generate();
808		let public = pair.public();
809		let message = b"Signed payload";
810		let Signature(mut bytes) = pair.sign(&message[..]);
811		bytes[0] = !bytes[0];
812		bytes[2] = !bytes[2];
813		let signature = Signature(bytes);
814		assert!(!Pair::verify(&signature, &message[..], &public));
815	}
816
817	#[test]
818	fn messed_message_should_not_work() {
819		let (pair, _) = Pair::generate();
820		let public = pair.public();
821		let message = b"Something important";
822		let signature = pair.sign(&message[..]);
823		assert!(!Pair::verify(&signature, &b"Something unimportant", &public));
824	}
825
826	#[test]
827	fn seeded_pair_should_work() {
828		let pair = Pair::from_seed(b"12345678901234567890123456789012");
829		let public = pair.public();
830		assert_eq!(
831			public,
832			Public::from_raw(hex!(
833				"741c08a06f41c596608f6774259bd9043304adfa5d3eea62760bd9be97634d63"
834			))
835		);
836		let message = hex!("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000");
837		let signature = pair.sign(&message[..]);
838		assert!(Pair::verify(&signature, &message[..], &public));
839	}
840
841	#[test]
842	fn ss58check_roundtrip_works() {
843		let (pair, _) = Pair::generate();
844		let public = pair.public();
845		let s = public.to_ss58check();
846		println!("Correct: {}", s);
847		let cmp = Public::from_ss58check(&s).unwrap();
848		assert_eq!(cmp, public);
849	}
850
851	#[test]
852	fn verify_from_old_wasm_works() {
853		// The values in this test case are compared to the output of `node-test.js` in schnorrkel-js.
854		//
855		// This is to make sure that the wasm library is compatible.
856		let pk = Pair::from_seed(
857			&hex!("0000000000000000000000000000000000000000000000000000000000000000")
858		);
859		let public = pk.public();
860		let js_signature = Signature::from_raw(hex!(
861			"28a854d54903e056f89581c691c1f7d2ff39f8f896c9e9c22475e60902cc2b3547199e0e91fa32902028f2ca2355e8cdd16cfe19ba5e8b658c94aa80f3b81a00"
862		));
863		assert!(Pair::verify_deprecated(&js_signature, b"TETCORE", &public));
864		assert!(!Pair::verify(&js_signature, b"TETCORE", &public));
865	}
866
867	#[test]
868	fn signature_serialization_works() {
869		let pair = Pair::from_seed(b"12345678901234567890123456789012");
870		let message = b"Something important";
871		let signature = pair.sign(&message[..]);
872		let serialized_signature = serde_json::to_string(&signature).unwrap();
873		// Signature is 64 bytes, so 128 chars + 2 quote chars
874		assert_eq!(serialized_signature.len(), 130);
875		let signature = serde_json::from_str(&serialized_signature).unwrap();
876		assert!(Pair::verify(&signature, &message[..], &pair.public()));
877	}
878
879	#[test]
880	fn signature_serialization_doesnt_panic() {
881		fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
882			Ok(serde_json::from_str(text)?)
883		}
884		assert!(deserialize_signature("Not valid json.").is_err());
885		assert!(deserialize_signature("\"Not an actual signature.\"").is_err());
886		// Poorly-sized
887		assert!(deserialize_signature("\"abc123\"").is_err());
888	}
889}