referrerpolicy=no-referrer-when-downgrade

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