Skip to main content

subsoil/core/
sr25519.rs

1// This file is part of Soil.
2
3// Copyright (C) Soil contributors.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: Apache-2.0 OR GPL-3.0-or-later WITH Classpath-exception-2.0
6
7//! Simple sr25519 (Schnorr-Ristretto) API.
8//!
9//! Note: `CHAIN_CODE_LENGTH` must be equal to `crate::core::crypto::JUNCTION_ID_LEN`
10//! for this to work.
11
12#[cfg(feature = "serde")]
13use crate::core::crypto::Ss58Codec;
14use crate::core::{
15	crypto::{CryptoBytes, DeriveError, DeriveJunction, Pair as TraitPair, SecretStringError},
16	proof_of_possession::NonAggregatable,
17};
18
19use alloc::vec::Vec;
20#[cfg(feature = "full_crypto")]
21use schnorrkel::signing_context;
22use schnorrkel::{
23	derive::{ChainCode, Derivation, CHAIN_CODE_LENGTH},
24	ExpansionMode, Keypair, MiniSecretKey, PublicKey, SecretKey,
25};
26
27use crate::core::crypto::{
28	CryptoType, CryptoTypeId, Derive, Public as TraitPublic, SignatureBytes,
29};
30use codec::{Decode, Encode, MaxEncodedLen};
31use scale_info::TypeInfo;
32
33#[cfg(all(not(feature = "std"), feature = "serde"))]
34use alloc::{format, string::String};
35use schnorrkel::keys::{MINI_SECRET_KEY_LENGTH, SECRET_KEY_LENGTH};
36#[cfg(feature = "serde")]
37use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
38
39// signing context
40const SIGNING_CTX: &[u8] = b"substrate";
41
42/// An identifier used to match public keys against sr25519 keys
43pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"sr25");
44
45/// The byte length of public key
46pub const PUBLIC_KEY_SERIALIZED_SIZE: usize = 32;
47
48/// The byte length of signature
49pub const SIGNATURE_SERIALIZED_SIZE: usize = 64;
50
51#[doc(hidden)]
52pub struct Sr25519Tag;
53#[doc(hidden)]
54pub struct Sr25519PublicTag;
55
56/// An Schnorrkel/Ristretto x25519 ("sr25519") public key.
57pub type Public = CryptoBytes<PUBLIC_KEY_SERIALIZED_SIZE, Sr25519PublicTag>;
58
59impl TraitPublic for Public {}
60
61impl Derive for Public {
62	/// Derive a child key from a series of given junctions.
63	///
64	/// `None` if there are any hard junctions in there.
65	#[cfg(feature = "serde")]
66	fn derive<Iter: Iterator<Item = DeriveJunction>>(&self, path: Iter) -> Option<Public> {
67		let mut acc = PublicKey::from_bytes(self.as_ref()).ok()?;
68		for j in path {
69			match j {
70				DeriveJunction::Soft(cc) => acc = acc.derived_key_simple(ChainCode(cc), &[]).0,
71				DeriveJunction::Hard(_cc) => return None,
72			}
73		}
74		Some(Self::from(acc.to_bytes()))
75	}
76}
77
78#[cfg(feature = "std")]
79impl std::str::FromStr for Public {
80	type Err = crate::core::crypto::PublicError;
81
82	fn from_str(s: &str) -> Result<Self, Self::Err> {
83		Self::from_ss58check(s)
84	}
85}
86
87#[cfg(feature = "std")]
88impl std::fmt::Display for Public {
89	fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
90		write!(f, "{}", self.to_ss58check())
91	}
92}
93
94impl ::core::fmt::Debug for Public {
95	#[cfg(feature = "std")]
96	fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
97		let s = self.to_ss58check();
98		write!(f, "{} ({}...)", crate::core::hexdisplay::HexDisplay::from(&self.0), &s[0..8])
99	}
100
101	#[cfg(not(feature = "std"))]
102	fn fmt(&self, _: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
103		Ok(())
104	}
105}
106
107#[cfg(feature = "serde")]
108impl Serialize for Public {
109	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
110	where
111		S: Serializer,
112	{
113		serializer.serialize_str(&self.to_ss58check())
114	}
115}
116
117#[cfg(feature = "serde")]
118impl<'de> Deserialize<'de> for Public {
119	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
120	where
121		D: Deserializer<'de>,
122	{
123		Public::from_ss58check(&String::deserialize(deserializer)?)
124			.map_err(|e| de::Error::custom(format!("{:?}", e)))
125	}
126}
127
128/// An Schnorrkel/Ristretto x25519 ("sr25519") signature.
129pub type Signature = SignatureBytes<SIGNATURE_SERIALIZED_SIZE, Sr25519Tag>;
130
131/// Proof of Possession is the same as Signature for sr25519
132pub type ProofOfPossession = Signature;
133
134#[cfg(feature = "full_crypto")]
135impl From<schnorrkel::Signature> for Signature {
136	fn from(s: schnorrkel::Signature) -> Signature {
137		Signature::from(s.to_bytes())
138	}
139}
140
141/// An Schnorrkel/Ristretto x25519 ("sr25519") key pair.
142pub struct Pair(Keypair);
143
144impl Clone for Pair {
145	fn clone(&self) -> Self {
146		Pair(schnorrkel::Keypair {
147			public: self.0.public,
148			secret: schnorrkel::SecretKey::from_bytes(&self.0.secret.to_bytes()[..])
149				.expect("key is always the correct size; qed"),
150		})
151	}
152}
153
154#[cfg(feature = "std")]
155impl From<MiniSecretKey> for Pair {
156	fn from(sec: MiniSecretKey) -> Pair {
157		Pair(sec.expand_to_keypair(ExpansionMode::Ed25519))
158	}
159}
160
161#[cfg(feature = "std")]
162impl From<SecretKey> for Pair {
163	fn from(sec: SecretKey) -> Pair {
164		Pair(Keypair::from(sec))
165	}
166}
167
168#[cfg(feature = "full_crypto")]
169impl From<schnorrkel::Keypair> for Pair {
170	fn from(p: schnorrkel::Keypair) -> Pair {
171		Pair(p)
172	}
173}
174
175#[cfg(feature = "full_crypto")]
176impl From<Pair> for schnorrkel::Keypair {
177	fn from(p: Pair) -> schnorrkel::Keypair {
178		p.0
179	}
180}
181
182#[cfg(feature = "full_crypto")]
183impl AsRef<schnorrkel::Keypair> for Pair {
184	fn as_ref(&self) -> &schnorrkel::Keypair {
185		&self.0
186	}
187}
188
189/// Derive a single hard junction.
190fn derive_hard_junction(secret: &SecretKey, cc: &[u8; CHAIN_CODE_LENGTH]) -> MiniSecretKey {
191	secret.hard_derive_mini_secret_key(Some(ChainCode(*cc)), b"").0
192}
193
194/// The raw secret seed, which can be used to recreate the `Pair`.
195type Seed = [u8; MINI_SECRET_KEY_LENGTH];
196
197impl TraitPair for Pair {
198	type Public = Public;
199	type Seed = Seed;
200	type Signature = Signature;
201	type ProofOfPossession = ProofOfPossession;
202
203	/// Get the public key.
204	fn public(&self) -> Public {
205		Public::from(self.0.public.to_bytes())
206	}
207
208	/// Make a new key pair from raw secret seed material.
209	///
210	/// This is generated using schnorrkel's Mini-Secret-Keys.
211	///
212	/// A `MiniSecretKey` is literally what Ed25519 calls a `SecretKey`, which is just 32 random
213	/// bytes.
214	fn from_seed_slice(seed: &[u8]) -> Result<Pair, SecretStringError> {
215		match seed.len() {
216			MINI_SECRET_KEY_LENGTH => Ok(Pair(
217				MiniSecretKey::from_bytes(seed)
218					.map_err(|_| SecretStringError::InvalidSeed)?
219					.expand_to_keypair(ExpansionMode::Ed25519),
220			)),
221			SECRET_KEY_LENGTH => Ok(Pair(
222				SecretKey::from_bytes(seed)
223					.map_err(|_| SecretStringError::InvalidSeed)?
224					.to_keypair(),
225			)),
226			_ => Err(SecretStringError::InvalidSeedLength),
227		}
228	}
229
230	fn derive<Iter: Iterator<Item = DeriveJunction>>(
231		&self,
232		path: Iter,
233		seed: Option<Seed>,
234	) -> Result<(Pair, Option<Seed>), DeriveError> {
235		let seed = seed
236			.and_then(|s| MiniSecretKey::from_bytes(&s).ok())
237			.filter(|msk| msk.expand(ExpansionMode::Ed25519) == self.0.secret);
238
239		let init = self.0.secret.clone();
240		let (result, seed) = path.fold((init, seed), |(acc, acc_seed), j| match (j, acc_seed) {
241			(DeriveJunction::Soft(cc), _) => (acc.derived_key_simple(ChainCode(cc), &[]).0, None),
242			(DeriveJunction::Hard(cc), maybe_seed) => {
243				let seed = derive_hard_junction(&acc, &cc);
244				(seed.expand(ExpansionMode::Ed25519), maybe_seed.map(|_| seed))
245			},
246		});
247		Ok((Self(result.into()), seed.map(|s| MiniSecretKey::to_bytes(&s))))
248	}
249
250	#[cfg(feature = "full_crypto")]
251	fn sign(&self, message: &[u8]) -> Signature {
252		let context = signing_context(SIGNING_CTX);
253		self.0.sign(context.bytes(message)).into()
254	}
255
256	fn verify<M: AsRef<[u8]>>(sig: &Signature, message: M, pubkey: &Public) -> bool {
257		let Ok(signature) = schnorrkel::Signature::from_bytes(sig.as_ref()) else { return false };
258		let Ok(public) = PublicKey::from_bytes(pubkey.as_ref()) else { return false };
259		public.verify_simple(SIGNING_CTX, message.as_ref(), &signature).is_ok()
260	}
261
262	fn to_raw_vec(&self) -> Vec<u8> {
263		self.0.secret.to_bytes().to_vec()
264	}
265}
266
267#[cfg(not(substrate_runtime))]
268impl Pair {
269	/// Verify a signature on a message. Returns `true` if the signature is good.
270	/// Supports old 0.1.1 deprecated signatures and should be used only for backward
271	/// compatibility.
272	pub fn verify_deprecated<M: AsRef<[u8]>>(sig: &Signature, message: M, pubkey: &Public) -> bool {
273		// Match both schnorrkel 0.1.1 and 0.8.0+ signatures, supporting both wallets
274		// that have not been upgraded and those that have.
275		match PublicKey::from_bytes(pubkey.as_ref()) {
276			Ok(pk) => pk
277				.verify_simple_preaudit_deprecated(SIGNING_CTX, message.as_ref(), &sig.0[..])
278				.is_ok(),
279			Err(_) => false,
280		}
281	}
282}
283
284impl CryptoType for Public {
285	type Pair = Pair;
286}
287
288impl CryptoType for Signature {
289	type Pair = Pair;
290}
291
292impl CryptoType for Pair {
293	type Pair = Pair;
294}
295
296impl NonAggregatable for Pair {}
297
298/// Schnorrkel VRF related types and operations.
299pub mod vrf {
300	use super::*;
301	#[cfg(feature = "full_crypto")]
302	use crate::core::crypto::VrfSecret;
303	use crate::core::crypto::{VrfCrypto, VrfPublic};
304	use schnorrkel::{
305		errors::MultiSignatureStage,
306		vrf::{VRF_PREOUT_LENGTH, VRF_PROOF_LENGTH},
307		SignatureError,
308	};
309
310	const DEFAULT_EXTRA_DATA_LABEL: &[u8] = b"VRF";
311
312	/// Transcript ready to be used for VRF related operations.
313	#[derive(Clone)]
314	pub struct VrfTranscript(pub merlin::Transcript);
315
316	impl VrfTranscript {
317		/// Build a new transcript instance.
318		///
319		/// Each `data` element is a tuple `(domain, message)` used to build the transcript.
320		pub fn new(label: &'static [u8], data: &[(&'static [u8], &[u8])]) -> Self {
321			let mut transcript = merlin::Transcript::new(label);
322			data.iter().for_each(|(l, b)| transcript.append_message(l, b));
323			VrfTranscript(transcript)
324		}
325
326		/// Map transcript to `VrfSignData`.
327		pub fn into_sign_data(self) -> VrfSignData {
328			self.into()
329		}
330	}
331
332	/// VRF input.
333	///
334	/// Technically a transcript used by the Fiat-Shamir transform.
335	pub type VrfInput = VrfTranscript;
336
337	/// VRF input ready to be used for VRF sign and verify operations.
338	#[derive(Clone)]
339	pub struct VrfSignData {
340		/// Transcript data contributing to VRF output.
341		pub(super) transcript: VrfTranscript,
342		/// Extra transcript data to be signed by the VRF.
343		pub(super) extra: Option<VrfTranscript>,
344	}
345
346	impl From<VrfInput> for VrfSignData {
347		fn from(transcript: VrfInput) -> Self {
348			VrfSignData { transcript, extra: None }
349		}
350	}
351
352	// Get a reference to the inner VRF input.
353	impl AsRef<VrfInput> for VrfSignData {
354		fn as_ref(&self) -> &VrfInput {
355			&self.transcript
356		}
357	}
358
359	impl VrfSignData {
360		/// Build a new instance ready to be used for VRF signer and verifier.
361		///
362		/// `input` will contribute to the VRF output bytes.
363		pub fn new(input: VrfTranscript) -> Self {
364			input.into()
365		}
366
367		/// Add some extra data to be signed.
368		///
369		/// `extra` will not contribute to the VRF output bytes.
370		pub fn with_extra(mut self, extra: VrfTranscript) -> Self {
371			self.extra = Some(extra);
372			self
373		}
374	}
375
376	/// VRF signature data
377	#[derive(Clone, Debug, PartialEq, Eq, Encode, Decode, MaxEncodedLen, TypeInfo)]
378	pub struct VrfSignature {
379		/// VRF pre-output.
380		pub pre_output: VrfPreOutput,
381		/// VRF proof.
382		pub proof: VrfProof,
383	}
384
385	/// VRF pre-output type suitable for schnorrkel operations.
386	#[derive(Clone, Debug, PartialEq, Eq)]
387	pub struct VrfPreOutput(pub schnorrkel::vrf::VRFPreOut);
388
389	impl Encode for VrfPreOutput {
390		fn encode(&self) -> Vec<u8> {
391			self.0.as_bytes().encode()
392		}
393	}
394
395	impl Decode for VrfPreOutput {
396		fn decode<R: codec::Input>(i: &mut R) -> Result<Self, codec::Error> {
397			let decoded = <[u8; VRF_PREOUT_LENGTH]>::decode(i)?;
398			Ok(Self(schnorrkel::vrf::VRFPreOut::from_bytes(&decoded).map_err(convert_error)?))
399		}
400	}
401
402	impl MaxEncodedLen for VrfPreOutput {
403		fn max_encoded_len() -> usize {
404			<[u8; VRF_PREOUT_LENGTH]>::max_encoded_len()
405		}
406	}
407
408	impl TypeInfo for VrfPreOutput {
409		type Identity = [u8; VRF_PREOUT_LENGTH];
410
411		fn type_info() -> scale_info::Type {
412			Self::Identity::type_info()
413		}
414	}
415
416	/// VRF proof type suitable for schnorrkel operations.
417	#[derive(Clone, Debug, PartialEq, Eq)]
418	pub struct VrfProof(pub schnorrkel::vrf::VRFProof);
419
420	impl Encode for VrfProof {
421		fn encode(&self) -> Vec<u8> {
422			self.0.to_bytes().encode()
423		}
424	}
425
426	impl Decode for VrfProof {
427		fn decode<R: codec::Input>(i: &mut R) -> Result<Self, codec::Error> {
428			let decoded = <[u8; VRF_PROOF_LENGTH]>::decode(i)?;
429			Ok(Self(schnorrkel::vrf::VRFProof::from_bytes(&decoded).map_err(convert_error)?))
430		}
431	}
432
433	impl MaxEncodedLen for VrfProof {
434		fn max_encoded_len() -> usize {
435			<[u8; VRF_PROOF_LENGTH]>::max_encoded_len()
436		}
437	}
438
439	impl TypeInfo for VrfProof {
440		type Identity = [u8; VRF_PROOF_LENGTH];
441
442		fn type_info() -> scale_info::Type {
443			Self::Identity::type_info()
444		}
445	}
446
447	#[cfg(feature = "full_crypto")]
448	impl VrfCrypto for Pair {
449		type VrfInput = VrfTranscript;
450		type VrfPreOutput = VrfPreOutput;
451		type VrfSignData = VrfSignData;
452		type VrfSignature = VrfSignature;
453	}
454
455	#[cfg(feature = "full_crypto")]
456	impl VrfSecret for Pair {
457		fn vrf_sign(&self, data: &Self::VrfSignData) -> Self::VrfSignature {
458			let inout = self.0.vrf_create_hash(data.transcript.0.clone());
459
460			let extra = data
461				.extra
462				.as_ref()
463				.map(|e| e.0.clone())
464				.unwrap_or_else(|| merlin::Transcript::new(DEFAULT_EXTRA_DATA_LABEL));
465
466			let proof = self.0.dleq_proove(extra, &inout, true).0;
467
468			VrfSignature { pre_output: VrfPreOutput(inout.to_preout()), proof: VrfProof(proof) }
469		}
470
471		fn vrf_pre_output(&self, input: &Self::VrfInput) -> Self::VrfPreOutput {
472			let pre_output = self.0.vrf_create_hash(input.0.clone()).to_preout();
473			VrfPreOutput(pre_output)
474		}
475	}
476
477	impl VrfCrypto for Public {
478		type VrfInput = VrfTranscript;
479		type VrfPreOutput = VrfPreOutput;
480		type VrfSignData = VrfSignData;
481		type VrfSignature = VrfSignature;
482	}
483
484	impl VrfPublic for Public {
485		fn vrf_verify(&self, data: &Self::VrfSignData, signature: &Self::VrfSignature) -> bool {
486			let do_verify = || {
487				let public = schnorrkel::PublicKey::from_bytes(&self.0)?;
488
489				let inout =
490					signature.pre_output.0.attach_input_hash(&public, data.transcript.0.clone())?;
491
492				let extra = data
493					.extra
494					.as_ref()
495					.map(|e| e.0.clone())
496					.unwrap_or_else(|| merlin::Transcript::new(DEFAULT_EXTRA_DATA_LABEL));
497
498				public.dleq_verify(extra, &inout, &signature.proof.0, true)
499			};
500			do_verify().is_ok()
501		}
502	}
503
504	fn convert_error(e: SignatureError) -> codec::Error {
505		use MultiSignatureStage::*;
506		use SignatureError::*;
507		match e {
508			EquationFalse => "Signature error: `EquationFalse`".into(),
509			PointDecompressionError => "Signature error: `PointDecompressionError`".into(),
510			ScalarFormatError => "Signature error: `ScalarFormatError`".into(),
511			NotMarkedSchnorrkel => "Signature error: `NotMarkedSchnorrkel`".into(),
512			BytesLengthError { .. } => "Signature error: `BytesLengthError`".into(),
513			InvalidKey => "Signature error: `InvalidKey`".into(),
514			MuSigAbsent { musig_stage: Commitment } => {
515				"Signature error: `MuSigAbsent` at stage `Commitment`".into()
516			},
517			MuSigAbsent { musig_stage: Reveal } => {
518				"Signature error: `MuSigAbsent` at stage `Reveal`".into()
519			},
520			MuSigAbsent { musig_stage: Cosignature } => {
521				"Signature error: `MuSigAbsent` at stage `Commitment`".into()
522			},
523			MuSigInconsistent { musig_stage: Commitment, duplicate: true } => {
524				"Signature error: `MuSigInconsistent` at stage `Commitment` on duplicate".into()
525			},
526			MuSigInconsistent { musig_stage: Commitment, duplicate: false } => {
527				"Signature error: `MuSigInconsistent` at stage `Commitment` on not duplicate".into()
528			},
529			MuSigInconsistent { musig_stage: Reveal, duplicate: true } => {
530				"Signature error: `MuSigInconsistent` at stage `Reveal` on duplicate".into()
531			},
532			MuSigInconsistent { musig_stage: Reveal, duplicate: false } => {
533				"Signature error: `MuSigInconsistent` at stage `Reveal` on not duplicate".into()
534			},
535			MuSigInconsistent { musig_stage: Cosignature, duplicate: true } => {
536				"Signature error: `MuSigInconsistent` at stage `Cosignature` on duplicate".into()
537			},
538			MuSigInconsistent { musig_stage: Cosignature, duplicate: false } => {
539				"Signature error: `MuSigInconsistent` at stage `Cosignature` on not duplicate"
540					.into()
541			},
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::core::{
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}