pezsp_core/
sr25519.rs

1// This file is part of Bizinikiwi.
2
3// Copyright (C) Parity Technologies (UK) Ltd. and Dijital Kurdistan Tech Institute
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"bizinikiwi";
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(bizinikiwi_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			},
526			MuSigAbsent { musig_stage: Reveal } => {
527				"Signature error: `MuSigAbsent` at stage `Reveal`".into()
528			},
529			MuSigAbsent { musig_stage: Cosignature } => {
530				"Signature error: `MuSigAbsent` at stage `Commitment`".into()
531			},
532			MuSigInconsistent { musig_stage: Commitment, duplicate: true } => {
533				"Signature error: `MuSigInconsistent` at stage `Commitment` on duplicate".into()
534			},
535			MuSigInconsistent { musig_stage: Commitment, duplicate: false } => {
536				"Signature error: `MuSigInconsistent` at stage `Commitment` on not duplicate".into()
537			},
538			MuSigInconsistent { musig_stage: Reveal, duplicate: true } => {
539				"Signature error: `MuSigInconsistent` at stage `Reveal` on duplicate".into()
540			},
541			MuSigInconsistent { musig_stage: Reveal, duplicate: false } => {
542				"Signature error: `MuSigInconsistent` at stage `Reveal` on not duplicate".into()
543			},
544			MuSigInconsistent { musig_stage: Cosignature, duplicate: true } => {
545				"Signature error: `MuSigInconsistent` at stage `Cosignature` on duplicate".into()
546			},
547			MuSigInconsistent { musig_stage: Cosignature, duplicate: false } => {
548				"Signature error: `MuSigInconsistent` at stage `Cosignature` on not duplicate"
549					.into()
550			},
551		}
552	}
553
554	#[cfg(feature = "full_crypto")]
555	impl Pair {
556		/// Generate output bytes from the given VRF configuration.
557		pub fn make_bytes<const N: usize>(&self, context: &[u8], input: &VrfInput) -> [u8; N]
558		where
559			[u8; N]: Default,
560		{
561			let inout = self.0.vrf_create_hash(input.0.clone());
562			inout.make_bytes::<[u8; N]>(context)
563		}
564	}
565
566	impl Public {
567		/// Generate output bytes from the given VRF configuration.
568		pub fn make_bytes<const N: usize>(
569			&self,
570			context: &[u8],
571			input: &VrfInput,
572			pre_output: &VrfPreOutput,
573		) -> Result<[u8; N], codec::Error>
574		where
575			[u8; N]: Default,
576		{
577			let pubkey = schnorrkel::PublicKey::from_bytes(&self.0).map_err(convert_error)?;
578			let inout = pre_output
579				.0
580				.attach_input_hash(&pubkey, input.0.clone())
581				.map_err(convert_error)?;
582			Ok(inout.make_bytes::<[u8; N]>(context))
583		}
584	}
585
586	impl VrfPreOutput {
587		/// Generate output bytes from the given VRF configuration.
588		pub fn make_bytes<const N: usize>(
589			&self,
590			context: &[u8],
591			input: &VrfInput,
592			public: &Public,
593		) -> Result<[u8; N], codec::Error>
594		where
595			[u8; N]: Default,
596		{
597			public.make_bytes(context, input, self)
598		}
599	}
600}
601
602#[cfg(test)]
603mod tests {
604	use super::{vrf::*, *};
605	use crate::{
606		crypto::{Ss58Codec, VrfPublic, VrfSecret, DEV_ADDRESS, DEV_PHRASE},
607		proof_of_possession::{ProofOfPossessionGenerator, ProofOfPossessionVerifier},
608		ByteArray as _,
609	};
610	use serde_json;
611
612	#[test]
613	fn derive_soft_known_pair_should_work() {
614		let pair = Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None).unwrap();
615		// known address of DEV_PHRASE with 1.1
616		let known = array_bytes::hex2bytes_unchecked(
617			"d6c71059dbbe9ad2b0ed3f289738b800836eb425544ce694825285b958ca755e",
618		);
619		assert_eq!(pair.public().to_raw_vec(), known);
620	}
621
622	#[test]
623	fn derive_hard_known_pair_should_work() {
624		let pair = Pair::from_string(&format!("{}//Alice", DEV_PHRASE), None).unwrap();
625		// known address of DEV_PHRASE with 1.1
626		let known = array_bytes::hex2bytes_unchecked(
627			"d43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d",
628		);
629		assert_eq!(pair.public().to_raw_vec(), known);
630	}
631
632	#[test]
633	fn verify_known_old_message_should_work() {
634		let public = Public::from_raw(array_bytes::hex2array_unchecked(
635			"b4bfa1f7a5166695eb75299fd1c4c03ea212871c342f2c5dfea0902b2c246918",
636		));
637		// signature generated by the 1.1 version with the same ^^ public key.
638		let signature = Signature::from_raw(array_bytes::hex2array_unchecked(
639			"5a9755f069939f45d96aaf125cf5ce7ba1db998686f87f2fb3cbdea922078741a73891ba265f70c31436e18a9acd14d189d73c12317ab6c313285cd938453202"
640		));
641		let message = b"Verifying that I am the owner of 5G9hQLdsKQswNPgB499DeA5PkFBbgkLPJWkkS6FAM6xGQ8xD. Hash: 221455a3\n";
642		assert!(Pair::verify_deprecated(&signature, &message[..], &public));
643		assert!(!Pair::verify(&signature, &message[..], &public));
644	}
645
646	#[test]
647	fn default_phrase_should_be_used() {
648		assert_eq!(
649			Pair::from_string("//Alice///password", None).unwrap().public(),
650			Pair::from_string(&format!("{}//Alice", DEV_PHRASE), Some("password"))
651				.unwrap()
652				.public(),
653		);
654		assert_eq!(
655			Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None)
656				.as_ref()
657				.map(Pair::public),
658			Pair::from_string("/Alice", None).as_ref().map(Pair::public)
659		);
660	}
661
662	#[test]
663	fn default_address_should_be_used() {
664		assert_eq!(
665			Public::from_string(&format!("{}/Alice", DEV_ADDRESS)),
666			Public::from_string("/Alice")
667		);
668	}
669
670	#[test]
671	fn default_phrase_should_correspond_to_default_address() {
672		assert_eq!(
673			Pair::from_string(&format!("{}/Alice", DEV_PHRASE), None).unwrap().public(),
674			Public::from_string(&format!("{}/Alice", DEV_ADDRESS)).unwrap(),
675		);
676		assert_eq!(
677			Pair::from_string("/Alice", None).unwrap().public(),
678			Public::from_string("/Alice").unwrap()
679		);
680	}
681
682	#[test]
683	fn derive_soft_should_work() {
684		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
685			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
686		));
687		let derive_1 = pair.derive(Some(DeriveJunction::soft(1)).into_iter(), None).unwrap().0;
688		let derive_1b = pair.derive(Some(DeriveJunction::soft(1)).into_iter(), None).unwrap().0;
689		let derive_2 = pair.derive(Some(DeriveJunction::soft(2)).into_iter(), None).unwrap().0;
690		assert_eq!(derive_1.public(), derive_1b.public());
691		assert_ne!(derive_1.public(), derive_2.public());
692	}
693
694	#[test]
695	fn derive_hard_should_work() {
696		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
697			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
698		));
699		let derive_1 = pair.derive(Some(DeriveJunction::hard(1)).into_iter(), None).unwrap().0;
700		let derive_1b = pair.derive(Some(DeriveJunction::hard(1)).into_iter(), None).unwrap().0;
701		let derive_2 = pair.derive(Some(DeriveJunction::hard(2)).into_iter(), None).unwrap().0;
702		assert_eq!(derive_1.public(), derive_1b.public());
703		assert_ne!(derive_1.public(), derive_2.public());
704	}
705
706	#[test]
707	fn derive_soft_public_should_work() {
708		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
709			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
710		));
711		let path = Some(DeriveJunction::soft(1));
712		let pair_1 = pair.derive(path.into_iter(), None).unwrap().0;
713		let public_1 = pair.public().derive(path.into_iter()).unwrap();
714		assert_eq!(pair_1.public(), public_1);
715	}
716
717	#[test]
718	fn derive_hard_public_should_fail() {
719		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
720			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
721		));
722		let path = Some(DeriveJunction::hard(1));
723		assert!(pair.public().derive(path.into_iter()).is_none());
724	}
725
726	#[test]
727	fn sr_test_vector_should_work() {
728		let pair = Pair::from_seed(&array_bytes::hex2array_unchecked(
729			"9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60",
730		));
731		let public = pair.public();
732		assert_eq!(
733			public,
734			Public::from_raw(array_bytes::hex2array_unchecked(
735				"44a996beb1eef7bdcab976ab6d2ca26104834164ecf28fb375600576fcc6eb0f"
736			))
737		);
738		let message = b"";
739		let signature = pair.sign(message);
740		assert!(Pair::verify(&signature, &message[..], &public));
741	}
742
743	#[test]
744	fn generate_with_phrase_should_be_recoverable_with_from_string() {
745		let (pair, phrase, seed) = Pair::generate_with_phrase(None);
746		let repair_seed = Pair::from_seed_slice(seed.as_ref()).expect("seed slice is valid");
747		assert_eq!(pair.public(), repair_seed.public());
748		assert_eq!(pair.to_raw_vec(), repair_seed.to_raw_vec());
749		let (repair_phrase, reseed) =
750			Pair::from_phrase(phrase.as_ref(), None).expect("seed slice is valid");
751		assert_eq!(seed, reseed);
752		assert_eq!(pair.public(), repair_phrase.public());
753		assert_eq!(pair.to_raw_vec(), repair_seed.to_raw_vec());
754		let repair_string = Pair::from_string(phrase.as_str(), None).expect("seed slice is valid");
755		assert_eq!(pair.public(), repair_string.public());
756		assert_eq!(pair.to_raw_vec(), repair_seed.to_raw_vec());
757	}
758
759	#[test]
760	fn generated_pair_should_work() {
761		let (pair, _) = Pair::generate();
762		let public = pair.public();
763		let message = b"Something important";
764		let signature = pair.sign(&message[..]);
765		assert!(Pair::verify(&signature, &message[..], &public));
766	}
767
768	#[test]
769	fn messed_signature_should_not_work() {
770		let (pair, _) = Pair::generate();
771		let public = pair.public();
772		let message = b"Signed payload";
773		let mut signature = pair.sign(&message[..]);
774		let bytes = &mut signature.0;
775		bytes[0] = !bytes[0];
776		bytes[2] = !bytes[2];
777		assert!(!Pair::verify(&signature, &message[..], &public));
778	}
779
780	#[test]
781	fn messed_message_should_not_work() {
782		let (pair, _) = Pair::generate();
783		let public = pair.public();
784		let message = b"Something important";
785		let signature = pair.sign(&message[..]);
786		assert!(!Pair::verify(&signature, &b"Something unimportant", &public));
787	}
788
789	#[test]
790	fn seeded_pair_should_work() {
791		let pair = Pair::from_seed(b"12345678901234567890123456789012");
792		let public = pair.public();
793		assert_eq!(
794			public,
795			Public::from_raw(array_bytes::hex2array_unchecked(
796				"741c08a06f41c596608f6774259bd9043304adfa5d3eea62760bd9be97634d63"
797			))
798		);
799		let message = array_bytes::hex2bytes_unchecked("2f8c6129d816cf51c374bc7f08c3e63ed156cf78aefb4a6550d97b87997977ee00000000000000000200d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a4500000000000000");
800		let signature = pair.sign(&message[..]);
801		assert!(Pair::verify(&signature, &message[..], &public));
802	}
803
804	#[test]
805	fn ss58check_roundtrip_works() {
806		let (pair, _) = Pair::generate();
807		let public = pair.public();
808		let s = public.to_ss58check();
809		println!("Correct: {}", s);
810		let cmp = Public::from_ss58check(&s).unwrap();
811		assert_eq!(cmp, public);
812	}
813
814	#[test]
815	fn verify_from_old_wasm_works() {
816		// The values in this test case are compared to the output of `node-test.js` in
817		// schnorrkel-js.
818		//
819		// This is to make sure that the wasm library is compatible.
820		let pk = Pair::from_seed(&array_bytes::hex2array_unchecked(
821			"0000000000000000000000000000000000000000000000000000000000000000",
822		));
823		let public = pk.public();
824		let js_signature = Signature::from_raw(array_bytes::hex2array_unchecked(
825			"28a854d54903e056f89581c691c1f7d2ff39f8f896c9e9c22475e60902cc2b3547199e0e91fa32902028f2ca2355e8cdd16cfe19ba5e8b658c94aa80f3b81a00"
826		));
827		assert!(Pair::verify_deprecated(&js_signature, b"BIZINIKIWI", &public));
828		assert!(!Pair::verify(&js_signature, b"BIZINIKIWI", &public));
829	}
830
831	#[test]
832	fn signature_serialization_works() {
833		let pair = Pair::from_seed(b"12345678901234567890123456789012");
834		let message = b"Something important";
835		let signature = pair.sign(&message[..]);
836		let serialized_signature = serde_json::to_string(&signature).unwrap();
837		// Signature is 64 bytes, so 128 chars + 2 quote chars
838		assert_eq!(serialized_signature.len(), 130);
839		let signature = serde_json::from_str(&serialized_signature).unwrap();
840		assert!(Pair::verify(&signature, &message[..], &pair.public()));
841	}
842
843	#[test]
844	fn signature_serialization_doesnt_panic() {
845		fn deserialize_signature(text: &str) -> Result<Signature, serde_json::error::Error> {
846			serde_json::from_str(text)
847		}
848		assert!(deserialize_signature("Not valid json.").is_err());
849		assert!(deserialize_signature("\"Not an actual signature.\"").is_err());
850		// Poorly-sized
851		assert!(deserialize_signature("\"abc123\"").is_err());
852	}
853
854	#[test]
855	fn vrf_sign_verify() {
856		let pair = Pair::from_seed(b"12345678901234567890123456789012");
857		let public = pair.public();
858
859		let data = VrfTranscript::new(b"label", &[(b"domain1", b"data1")]).into();
860
861		let signature = pair.vrf_sign(&data);
862
863		assert!(public.vrf_verify(&data, &signature));
864	}
865
866	#[test]
867	fn vrf_sign_verify_with_extra() {
868		let pair = Pair::from_seed(b"12345678901234567890123456789012");
869		let public = pair.public();
870
871		let extra = VrfTranscript::new(b"extra", &[(b"domain2", b"data2")]);
872		let data = VrfTranscript::new(b"label", &[(b"domain1", b"data1")])
873			.into_sign_data()
874			.with_extra(extra);
875
876		let signature = pair.vrf_sign(&data);
877
878		assert!(public.vrf_verify(&data, &signature));
879	}
880
881	#[test]
882	fn vrf_make_bytes_matches() {
883		let pair = Pair::from_seed(b"12345678901234567890123456789012");
884		let public = pair.public();
885		let ctx = b"vrfbytes";
886
887		let input = VrfTranscript::new(b"label", &[(b"domain1", b"data1")]);
888
889		let pre_output = pair.vrf_pre_output(&input);
890
891		let out1 = pair.make_bytes::<32>(ctx, &input);
892		let out2 = pre_output.make_bytes::<32>(ctx, &input, &public).unwrap();
893		assert_eq!(out1, out2);
894
895		let extra = VrfTranscript::new(b"extra", &[(b"domain2", b"data2")]);
896		let data = input.clone().into_sign_data().with_extra(extra);
897		let signature = pair.vrf_sign(&data);
898		assert!(public.vrf_verify(&data, &signature));
899
900		let out3 = public.make_bytes::<32>(ctx, &input, &signature.pre_output).unwrap();
901		assert_eq!(out2, out3);
902	}
903
904	#[test]
905	fn vrf_backend_compat() {
906		let pair = Pair::from_seed(b"12345678901234567890123456789012");
907		let public = pair.public();
908		let ctx = b"vrfbytes";
909
910		let input = VrfInput::new(b"label", &[(b"domain1", b"data1")]);
911		let extra = VrfTranscript::new(b"extra", &[(b"domain2", b"data2")]);
912
913		let data = input.clone().into_sign_data().with_extra(extra.clone());
914		let signature = pair.vrf_sign(&data);
915		assert!(public.vrf_verify(&data, &signature));
916
917		let out1 = pair.make_bytes::<32>(ctx, &input);
918		let out2 = public.make_bytes::<32>(ctx, &input, &signature.pre_output).unwrap();
919		assert_eq!(out1, out2);
920
921		// Direct call to backend version of sign after check with extra params
922		let (inout, proof, _) = pair
923			.0
924			.vrf_sign_extra_after_check(input.0.clone(), |inout| {
925				let out3 = inout.make_bytes::<[u8; 32]>(ctx);
926				assert_eq!(out2, out3);
927				Some(extra.0.clone())
928			})
929			.unwrap();
930		let signature2 =
931			VrfSignature { pre_output: VrfPreOutput(inout.to_preout()), proof: VrfProof(proof) };
932
933		assert!(public.vrf_verify(&data, &signature2));
934		assert_eq!(signature.pre_output, signature2.pre_output);
935	}
936
937	#[test]
938	fn good_proof_of_possession_should_work_bad_proof_of_possession_should_fail() {
939		let owner = b"owner";
940		let not_owner = b"not owner";
941
942		let mut pair = Pair::from_seed(b"12345678901234567890123456789012");
943		let other_pair = Pair::from_seed(b"23456789012345678901234567890123");
944		let proof_of_possession = pair.generate_proof_of_possession(owner);
945		assert!(Pair::verify_proof_of_possession(owner, &proof_of_possession, &pair.public()));
946		assert_eq!(
947			Pair::verify_proof_of_possession(owner, &proof_of_possession, &other_pair.public()),
948			false
949		);
950		assert!(!Pair::verify_proof_of_possession(not_owner, &proof_of_possession, &pair.public()));
951	}
952}