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#[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(not(substrate_runtime))]
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
301impl NonAggregatable for Pair {}
302
303/// Schnorrkel VRF related types and operations.
304pub mod vrf {
305	use super::*;
306	#[cfg(feature = "full_crypto")]
307	use crate::crypto::VrfSecret;
308	use crate::crypto::{VrfCrypto, VrfPublic};
309	use schnorrkel::{
310		errors::MultiSignatureStage,
311		vrf::{VRF_PREOUT_LENGTH, VRF_PROOF_LENGTH},
312		SignatureError,
313	};
314
315	const DEFAULT_EXTRA_DATA_LABEL: &[u8] = b"VRF";
316
317	/// Transcript ready to be used for VRF related operations.
318	#[derive(Clone)]
319	pub struct VrfTranscript(pub merlin::Transcript);
320
321	impl VrfTranscript {
322		/// Build a new transcript instance.
323		///
324		/// Each `data` element is a tuple `(domain, message)` used to build the transcript.
325		pub fn new(label: &'static [u8], data: &[(&'static [u8], &[u8])]) -> Self {
326			let mut transcript = merlin::Transcript::new(label);
327			data.iter().for_each(|(l, b)| transcript.append_message(l, b));
328			VrfTranscript(transcript)
329		}
330
331		/// Map transcript to `VrfSignData`.
332		pub fn into_sign_data(self) -> VrfSignData {
333			self.into()
334		}
335	}
336
337	/// VRF input.
338	///
339	/// Technically a transcript used by the Fiat-Shamir transform.
340	pub type VrfInput = VrfTranscript;
341
342	/// VRF input ready to be used for VRF sign and verify operations.
343	#[derive(Clone)]
344	pub struct VrfSignData {
345		/// Transcript data contributing to VRF output.
346		pub(super) transcript: VrfTranscript,
347		/// Extra transcript data to be signed by the VRF.
348		pub(super) extra: Option<VrfTranscript>,
349	}
350
351	impl From<VrfInput> for VrfSignData {
352		fn from(transcript: VrfInput) -> Self {
353			VrfSignData { transcript, extra: None }
354		}
355	}
356
357	// Get a reference to the inner VRF input.
358	impl AsRef<VrfInput> for VrfSignData {
359		fn as_ref(&self) -> &VrfInput {
360			&self.transcript
361		}
362	}
363
364	impl VrfSignData {
365		/// Build a new instance ready to be used for VRF signer and verifier.
366		///
367		/// `input` will contribute to the VRF output bytes.
368		pub fn new(input: VrfTranscript) -> Self {
369			input.into()
370		}
371
372		/// Add some extra data to be signed.
373		///
374		/// `extra` will not contribute to the VRF output bytes.
375		pub fn with_extra(mut self, extra: VrfTranscript) -> Self {
376			self.extra = Some(extra);
377			self
378		}
379	}
380
381	/// VRF signature data
382	#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo)]
383	pub struct VrfSignature {
384		/// VRF pre-output.
385		pub pre_output: VrfPreOutput,
386		/// VRF proof.
387		pub proof: VrfProof,
388	}
389
390	/// VRF pre-output type suitable for schnorrkel operations.
391	#[derive(Clone, Debug, PartialEq, Eq)]
392	pub struct VrfPreOutput(pub schnorrkel::vrf::VRFPreOut);
393
394	impl Encode for VrfPreOutput {
395		fn encode(&self) -> Vec<u8> {
396			self.0.as_bytes().encode()
397		}
398	}
399
400	impl Decode for VrfPreOutput {
401		fn decode<R: codec::Input>(i: &mut R) -> Result<Self, codec::Error> {
402			let decoded = <[u8; VRF_PREOUT_LENGTH]>::decode(i)?;
403			Ok(Self(schnorrkel::vrf::VRFPreOut::from_bytes(&decoded).map_err(convert_error)?))
404		}
405	}
406
407	impl MaxEncodedLen for VrfPreOutput {
408		fn max_encoded_len() -> usize {
409			<[u8; VRF_PREOUT_LENGTH]>::max_encoded_len()
410		}
411	}
412
413	impl TypeInfo for VrfPreOutput {
414		type Identity = [u8; VRF_PREOUT_LENGTH];
415
416		fn type_info() -> scale_info::Type {
417			Self::Identity::type_info()
418		}
419	}
420
421	/// VRF proof type suitable for schnorrkel operations.
422	#[derive(Clone, Debug, PartialEq, Eq)]
423	pub struct VrfProof(pub schnorrkel::vrf::VRFProof);
424
425	impl Encode for VrfProof {
426		fn encode(&self) -> Vec<u8> {
427			self.0.to_bytes().encode()
428		}
429	}
430
431	impl Decode for VrfProof {
432		fn decode<R: codec::Input>(i: &mut R) -> Result<Self, codec::Error> {
433			let decoded = <[u8; VRF_PROOF_LENGTH]>::decode(i)?;
434			Ok(Self(schnorrkel::vrf::VRFProof::from_bytes(&decoded).map_err(convert_error)?))
435		}
436	}
437
438	impl MaxEncodedLen for VrfProof {
439		fn max_encoded_len() -> usize {
440			<[u8; VRF_PROOF_LENGTH]>::max_encoded_len()
441		}
442	}
443
444	impl TypeInfo for VrfProof {
445		type Identity = [u8; VRF_PROOF_LENGTH];
446
447		fn type_info() -> scale_info::Type {
448			Self::Identity::type_info()
449		}
450	}
451
452	#[cfg(feature = "full_crypto")]
453	impl VrfCrypto for Pair {
454		type VrfInput = VrfTranscript;
455		type VrfPreOutput = VrfPreOutput;
456		type VrfSignData = VrfSignData;
457		type VrfSignature = VrfSignature;
458	}
459
460	#[cfg(feature = "full_crypto")]
461	impl VrfSecret for Pair {
462		fn vrf_sign(&self, data: &Self::VrfSignData) -> Self::VrfSignature {
463			let inout = self.0.vrf_create_hash(data.transcript.0.clone());
464
465			let extra = data
466				.extra
467				.as_ref()
468				.map(|e| e.0.clone())
469				.unwrap_or_else(|| merlin::Transcript::new(DEFAULT_EXTRA_DATA_LABEL));
470
471			let proof = self.0.dleq_proove(extra, &inout, true).0;
472
473			VrfSignature { pre_output: VrfPreOutput(inout.to_preout()), proof: VrfProof(proof) }
474		}
475
476		fn vrf_pre_output(&self, input: &Self::VrfInput) -> Self::VrfPreOutput {
477			let pre_output = self.0.vrf_create_hash(input.0.clone()).to_preout();
478			VrfPreOutput(pre_output)
479		}
480	}
481
482	impl VrfCrypto for Public {
483		type VrfInput = VrfTranscript;
484		type VrfPreOutput = VrfPreOutput;
485		type VrfSignData = VrfSignData;
486		type VrfSignature = VrfSignature;
487	}
488
489	impl VrfPublic for Public {
490		fn vrf_verify(&self, data: &Self::VrfSignData, signature: &Self::VrfSignature) -> bool {
491			let do_verify = || {
492				let public = schnorrkel::PublicKey::from_bytes(&self.0)?;
493
494				let inout =
495					signature.pre_output.0.attach_input_hash(&public, data.transcript.0.clone())?;
496
497				let extra = data
498					.extra
499					.as_ref()
500					.map(|e| e.0.clone())
501					.unwrap_or_else(|| merlin::Transcript::new(DEFAULT_EXTRA_DATA_LABEL));
502
503				public.dleq_verify(extra, &inout, &signature.proof.0, true)
504			};
505			do_verify().is_ok()
506		}
507	}
508
509	fn convert_error(e: SignatureError) -> codec::Error {
510		use MultiSignatureStage::*;
511		use SignatureError::*;
512		match e {
513			EquationFalse => "Signature error: `EquationFalse`".into(),
514			PointDecompressionError => "Signature error: `PointDecompressionError`".into(),
515			ScalarFormatError => "Signature error: `ScalarFormatError`".into(),
516			NotMarkedSchnorrkel => "Signature error: `NotMarkedSchnorrkel`".into(),
517			BytesLengthError { .. } => "Signature error: `BytesLengthError`".into(),
518			InvalidKey => "Signature error: `InvalidKey`".into(),
519			MuSigAbsent { musig_stage: Commitment } =>
520				"Signature error: `MuSigAbsent` at stage `Commitment`".into(),
521			MuSigAbsent { musig_stage: Reveal } =>
522				"Signature error: `MuSigAbsent` at stage `Reveal`".into(),
523			MuSigAbsent { musig_stage: Cosignature } =>
524				"Signature error: `MuSigAbsent` at stage `Commitment`".into(),
525			MuSigInconsistent { musig_stage: Commitment, duplicate: true } =>
526				"Signature error: `MuSigInconsistent` at stage `Commitment` on duplicate".into(),
527			MuSigInconsistent { musig_stage: Commitment, duplicate: false } =>
528				"Signature error: `MuSigInconsistent` at stage `Commitment` on not duplicate".into(),
529			MuSigInconsistent { musig_stage: Reveal, duplicate: true } =>
530				"Signature error: `MuSigInconsistent` at stage `Reveal` on duplicate".into(),
531			MuSigInconsistent { musig_stage: Reveal, duplicate: false } =>
532				"Signature error: `MuSigInconsistent` at stage `Reveal` on not duplicate".into(),
533			MuSigInconsistent { musig_stage: Cosignature, duplicate: true } =>
534				"Signature error: `MuSigInconsistent` at stage `Cosignature` on duplicate".into(),
535			MuSigInconsistent { musig_stage: Cosignature, duplicate: false } =>
536				"Signature error: `MuSigInconsistent` at stage `Cosignature` on not duplicate"
537					.into(),
538		}
539	}
540
541	#[cfg(feature = "full_crypto")]
542	impl Pair {
543		/// Generate output bytes from the given VRF configuration.
544		pub fn make_bytes<const N: usize>(&self, context: &[u8], input: &VrfInput) -> [u8; N]
545		where
546			[u8; N]: Default,
547		{
548			let inout = self.0.vrf_create_hash(input.0.clone());
549			inout.make_bytes::<[u8; N]>(context)
550		}
551	}
552
553	impl Public {
554		/// Generate output bytes from the given VRF configuration.
555		pub fn make_bytes<const N: usize>(
556			&self,
557			context: &[u8],
558			input: &VrfInput,
559			pre_output: &VrfPreOutput,
560		) -> Result<[u8; N], codec::Error>
561		where
562			[u8; N]: Default,
563		{
564			let pubkey = schnorrkel::PublicKey::from_bytes(&self.0).map_err(convert_error)?;
565			let inout = pre_output
566				.0
567				.attach_input_hash(&pubkey, input.0.clone())
568				.map_err(convert_error)?;
569			Ok(inout.make_bytes::<[u8; N]>(context))
570		}
571	}
572
573	impl VrfPreOutput {
574		/// Generate output bytes from the given VRF configuration.
575		pub fn make_bytes<const N: usize>(
576			&self,
577			context: &[u8],
578			input: &VrfInput,
579			public: &Public,
580		) -> Result<[u8; N], codec::Error>
581		where
582			[u8; N]: Default,
583		{
584			public.make_bytes(context, input, self)
585		}
586	}
587}
588
589#[cfg(test)]
590mod tests {
591	use super::{vrf::*, *};
592	use crate::{
593		crypto::{Ss58Codec, VrfPublic, VrfSecret, DEV_ADDRESS, DEV_PHRASE},
594		proof_of_possession::{ProofOfPossessionGenerator, ProofOfPossessionVerifier},
595		ByteArray as _,
596	};
597	use serde_json;
598
599	#[test]
600	fn derive_soft_known_pair_should_work() {
601		let pair = Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None).unwrap();
602		// known address of DEV_PHRASE with 1.1
603		let known = array_bytes::hex2bytes_unchecked(
604			"d6c71059dbbe9ad2b0ed3f289738b800836eb425544ce694825285b958ca755e",
605		);
606		assert_eq!(pair.public().to_raw_vec(), known);
607	}
608
609	#[test]
610	fn derive_hard_known_pair_should_work() {
611		let pair = Pair::from_string(&format!("{}//Alice", DEV_PHRASE), None).unwrap();
612		// known address of DEV_PHRASE with 1.1
613		let known = array_bytes::hex2bytes_unchecked(
614			"d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d",
615		);
616		assert_eq!(pair.public().to_raw_vec(), known);
617	}
618
619	#[test]
620	fn verify_known_old_message_should_work() {
621		let public = Public::from_raw(array_bytes::hex2array_unchecked(
622			"b4bfa1f7a5166695eb75299fd1c4c03ea212871c342f2c5dfea0902b2c246918",
623		));
624		// signature generated by the 1.1 version with the same ^^ public key.
625		let signature = Signature::from_raw(array_bytes::hex2array_unchecked(
626			"5a9755f069939f45d96aaf125cf5ce7ba1db998686f87f2fb3cbdea922078741a73891ba265f70c31436e18a9acd14d189d73c12317ab6c313285cd938453202"
627		));
628		let message = b"Verifying that I am the owner of 5G9hQLdsKQswNPgB499DeA5PkFBbgkLPJWkkS6FAM6xGQ8xD. Hash: 221455a3\n";
629		assert!(Pair::verify_deprecated(&signature, &message[..], &public));
630		assert!(!Pair::verify(&signature, &message[..], &public));
631	}
632
633	#[test]
634	fn default_phrase_should_be_used() {
635		assert_eq!(
636			Pair::from_string("//Alice///password", None).unwrap().public(),
637			Pair::from_string(&format!("{}//Alice", DEV_PHRASE), Some("password"))
638				.unwrap()
639				.public(),
640		);
641		assert_eq!(
642			Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None)
643				.as_ref()
644				.map(Pair::public),
645			Pair::from_string("/Alice", None).as_ref().map(Pair::public)
646		);
647	}
648
649	#[test]
650	fn default_address_should_be_used() {
651		assert_eq!(
652			Public::from_string(&format!("{}/Alice", DEV_ADDRESS)),
653			Public::from_string("/Alice")
654		);
655	}
656
657	#[test]
658	fn default_phrase_should_correspond_to_default_address() {
659		assert_eq!(
660			Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None).unwrap().public(),
661			Public::from_string(&format!("{}/Alice", DEV_ADDRESS)).unwrap(),
662		);
663		assert_eq!(
664			Pair::from_string("/Alice", None).unwrap().public(),
665			Public::from_string("/Alice").unwrap()
666		);
667	}
668
669	#[test]
670	fn derive_soft_should_work() {
671		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
672			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
673		));
674		let derive_1 = pair.derive(Some(DeriveJunction::soft(1)).into_iter(), None).unwrap().0;
675		let derive_1b = pair.derive(Some(DeriveJunction::soft(1)).into_iter(), None).unwrap().0;
676		let derive_2 = pair.derive(Some(DeriveJunction::soft(2)).into_iter(), None).unwrap().0;
677		assert_eq!(derive_1.public(), derive_1b.public());
678		assert_ne!(derive_1.public(), derive_2.public());
679	}
680
681	#[test]
682	fn derive_hard_should_work() {
683		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
684			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
685		));
686		let derive_1 = pair.derive(Some(DeriveJunction::hard(1)).into_iter(), None).unwrap().0;
687		let derive_1b = pair.derive(Some(DeriveJunction::hard(1)).into_iter(), None).unwrap().0;
688		let derive_2 = pair.derive(Some(DeriveJunction::hard(2)).into_iter(), None).unwrap().0;
689		assert_eq!(derive_1.public(), derive_1b.public());
690		assert_ne!(derive_1.public(), derive_2.public());
691	}
692
693	#[test]
694	fn derive_soft_public_should_work() {
695		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
696			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
697		));
698		let path = Some(DeriveJunction::soft(1));
699		let pair_1 = pair.derive(path.into_iter(), None).unwrap().0;
700		let public_1 = pair.public().derive(path.into_iter()).unwrap();
701		assert_eq!(pair_1.public(), public_1);
702	}
703
704	#[test]
705	fn derive_hard_public_should_fail() {
706		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
707			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
708		));
709		let path = Some(DeriveJunction::hard(1));
710		assert!(pair.public().derive(path.into_iter()).is_none());
711	}
712
713	#[test]
714	fn sr_test_vector_should_work() {
715		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
716			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
717		));
718		let public = pair.public();
719		assert_eq!(
720			public,
721			Public::from_raw(array_bytes::hex2array_unchecked(
722				"44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f"
723			))
724		);
725		let message = b"";
726		let signature = pair.sign(message);
727		assert!(Pair::verify(&signature, &message[..], &public));
728	}
729
730	#[test]
731	fn generate_with_phrase_should_be_recoverable_with_from_string() {
732		let (pair, phrase, seed) = Pair::generate_with_phrase(None);
733		let repair_seed = Pair::from_seed_slice(seed.as_ref()).expect("seed slice is valid");
734		assert_eq!(pair.public(), repair_seed.public());
735		assert_eq!(pair.to_raw_vec(), repair_seed.to_raw_vec());
736		let (repair_phrase, reseed) =
737			Pair::from_phrase(phrase.as_ref(), None).expect("seed slice is valid");
738		assert_eq!(seed, reseed);
739		assert_eq!(pair.public(), repair_phrase.public());
740		assert_eq!(pair.to_raw_vec(), repair_seed.to_raw_vec());
741		let repair_string = Pair::from_string(phrase.as_str(), None).expect("seed slice is valid");
742		assert_eq!(pair.public(), repair_string.public());
743		assert_eq!(pair.to_raw_vec(), repair_seed.to_raw_vec());
744	}
745
746	#[test]
747	fn generated_pair_should_work() {
748		let (pair, _) = Pair::generate();
749		let public = pair.public();
750		let message = b"Something important";
751		let signature = pair.sign(&message[..]);
752		assert!(Pair::verify(&signature, &message[..], &public));
753	}
754
755	#[test]
756	fn messed_signature_should_not_work() {
757		let (pair, _) = Pair::generate();
758		let public = pair.public();
759		let message = b"Signed payload";
760		let mut signature = pair.sign(&message[..]);
761		let bytes = &mut signature.0;
762		bytes[0] = !bytes[0];
763		bytes[2] = !bytes[2];
764		assert!(!Pair::verify(&signature, &message[..], &public));
765	}
766
767	#[test]
768	fn messed_message_should_not_work() {
769		let (pair, _) = Pair::generate();
770		let public = pair.public();
771		let message = b"Something important";
772		let signature = pair.sign(&message[..]);
773		assert!(!Pair::verify(&signature, &b"Something unimportant", &public));
774	}
775
776	#[test]
777	fn seeded_pair_should_work() {
778		let pair = Pair::from_seed(b"12345678901234567890123456789012");
779		let public = pair.public();
780		assert_eq!(
781			public,
782			Public::from_raw(array_bytes::hex2array_unchecked(
783				"741c08a06f41c596608f6774259bd9043304adfa5d3eea62760bd9be97634d63"
784			))
785		);
786		let message = array_bytes::hex2bytes_unchecked("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000");
787		let signature = pair.sign(&message[..]);
788		assert!(Pair::verify(&signature, &message[..], &public));
789	}
790
791	#[test]
792	fn ss58check_roundtrip_works() {
793		let (pair, _) = Pair::generate();
794		let public = pair.public();
795		let s = public.to_ss58check();
796		println!("Correct: {}", s);
797		let cmp = Public::from_ss58check(&s).unwrap();
798		assert_eq!(cmp, public);
799	}
800
801	#[test]
802	fn verify_from_old_wasm_works() {
803		// The values in this test case are compared to the output of `node-test.js` in
804		// schnorrkel-js.
805		//
806		// This is to make sure that the wasm library is compatible.
807		let pk = Pair::from_seed(&array_bytes::hex2array_unchecked(
808			"0000000000000000000000000000000000000000000000000000000000000000",
809		));
810		let public = pk.public();
811		let js_signature = Signature::from_raw(array_bytes::hex2array_unchecked(
812			"28a854d54903e056f89581c691c1f7d2ff39f8f896c9e9c22475e60902cc2b3547199e0e91fa32902028f2ca2355e8cdd16cfe19ba5e8b658c94aa80f3b81a00"
813		));
814		assert!(Pair::verify_deprecated(&js_signature, b"SUBSTRATE", &public));
815		assert!(!Pair::verify(&js_signature, b"SUBSTRATE", &public));
816	}
817
818	#[test]
819	fn signature_serialization_works() {
820		let pair = Pair::from_seed(b"12345678901234567890123456789012");
821		let message = b"Something important";
822		let signature = pair.sign(&message[..]);
823		let serialized_signature = serde_json::to_string(&signature).unwrap();
824		// Signature is 64 bytes, so 128 chars + 2 quote chars
825		assert_eq!(serialized_signature.len(), 130);
826		let signature = serde_json::from_str(&serialized_signature).unwrap();
827		assert!(Pair::verify(&signature, &message[..], &pair.public()));
828	}
829
830	#[test]
831	fn signature_serialization_doesnt_panic() {
832		fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
833			serde_json::from_str(text)
834		}
835		assert!(deserialize_signature("Not valid json.").is_err());
836		assert!(deserialize_signature("\"Not an actual signature.\"").is_err());
837		// Poorly-sized
838		assert!(deserialize_signature("\"abc123\"").is_err());
839	}
840
841	#[test]
842	fn vrf_sign_verify() {
843		let pair = Pair::from_seed(b"12345678901234567890123456789012");
844		let public = pair.public();
845
846		let data = VrfTranscript::new(b"label", &[(b"domain1", b"data1")]).into();
847
848		let signature = pair.vrf_sign(&data);
849
850		assert!(public.vrf_verify(&data, &signature));
851	}
852
853	#[test]
854	fn vrf_sign_verify_with_extra() {
855		let pair = Pair::from_seed(b"12345678901234567890123456789012");
856		let public = pair.public();
857
858		let extra = VrfTranscript::new(b"extra", &[(b"domain2", b"data2")]);
859		let data = VrfTranscript::new(b"label", &[(b"domain1", b"data1")])
860			.into_sign_data()
861			.with_extra(extra);
862
863		let signature = pair.vrf_sign(&data);
864
865		assert!(public.vrf_verify(&data, &signature));
866	}
867
868	#[test]
869	fn vrf_make_bytes_matches() {
870		let pair = Pair::from_seed(b"12345678901234567890123456789012");
871		let public = pair.public();
872		let ctx = b"vrfbytes";
873
874		let input = VrfTranscript::new(b"label", &[(b"domain1", b"data1")]);
875
876		let pre_output = pair.vrf_pre_output(&input);
877
878		let out1 = pair.make_bytes::<32>(ctx, &input);
879		let out2 = pre_output.make_bytes::<32>(ctx, &input, &public).unwrap();
880		assert_eq!(out1, out2);
881
882		let extra = VrfTranscript::new(b"extra", &[(b"domain2", b"data2")]);
883		let data = input.clone().into_sign_data().with_extra(extra);
884		let signature = pair.vrf_sign(&data);
885		assert!(public.vrf_verify(&data, &signature));
886
887		let out3 = public.make_bytes::<32>(ctx, &input, &signature.pre_output).unwrap();
888		assert_eq!(out2, out3);
889	}
890
891	#[test]
892	fn vrf_backend_compat() {
893		let pair = Pair::from_seed(b"12345678901234567890123456789012");
894		let public = pair.public();
895		let ctx = b"vrfbytes";
896
897		let input = VrfInput::new(b"label", &[(b"domain1", b"data1")]);
898		let extra = VrfTranscript::new(b"extra", &[(b"domain2", b"data2")]);
899
900		let data = input.clone().into_sign_data().with_extra(extra.clone());
901		let signature = pair.vrf_sign(&data);
902		assert!(public.vrf_verify(&data, &signature));
903
904		let out1 = pair.make_bytes::<32>(ctx, &input);
905		let out2 = public.make_bytes::<32>(ctx, &input, &signature.pre_output).unwrap();
906		assert_eq!(out1, out2);
907
908		// Direct call to backend version of sign after check with extra params
909		let (inout, proof, _) = pair
910			.0
911			.vrf_sign_extra_after_check(input.0.clone(), |inout| {
912				let out3 = inout.make_bytes::<[u8; 32]>(ctx);
913				assert_eq!(out2, out3);
914				Some(extra.0.clone())
915			})
916			.unwrap();
917		let signature2 =
918			VrfSignature { pre_output: VrfPreOutput(inout.to_preout()), proof: VrfProof(proof) };
919
920		assert!(public.vrf_verify(&data, &signature2));
921		assert_eq!(signature.pre_output, signature2.pre_output);
922	}
923
924	#[test]
925	fn good_proof_of_possession_should_work_bad_proof_of_possession_should_fail() {
926		let mut pair = Pair::from_seed(b"12345678901234567890123456789012");
927		let other_pair = Pair::from_seed(b"23456789012345678901234567890123");
928		let proof_of_possession = pair.generate_proof_of_possession();
929		assert!(Pair::verify_proof_of_possession(&proof_of_possession, &pair.public()));
930		assert!(!Pair::verify_proof_of_possession(&proof_of_possession, &other_pair.public()));
931	}
932}