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