ep_core/
bip340.rs

1use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode, MaxEncodedLen};
2use scale_info::TypeInfo;
3use sp_core::{
4	crypto::{AccountId32, ByteArray},
5	ed25519, sr25519,
6};
7
8/// An opaque 32-byte cryptographic identifier.
9///
10/// Very similar to the `AccountId32`, but it is purposely different
11/// as it does not implement the SS58 codec.
12#[derive(
13	Clone,
14	Eq,
15	PartialEq,
16	Ord,
17	PartialOrd,
18	Encode,
19	Decode,
20	DecodeWithMemTracking,
21	MaxEncodedLen,
22	TypeInfo,
23)]
24pub struct Bip340([u8; 32]);
25
26impl Bip340 {
27	/// Create a new instance from its raw inner byte value.
28	///
29	/// Equivalent to this types `From<[u8; 32]>` implementation. For the lack of const
30	/// support in traits we have this constructor.
31	pub const fn new(inner: [u8; 32]) -> Self {
32		Self(inner)
33	}
34}
35
36impl ByteArray for Bip340 {
37	const LEN: usize = 32;
38}
39
40impl AsRef<[u8]> for Bip340 {
41	fn as_ref(&self) -> &[u8] {
42		&self.0[..]
43	}
44}
45
46impl AsMut<[u8]> for Bip340 {
47	fn as_mut(&mut self) -> &mut [u8] {
48		&mut self.0[..]
49	}
50}
51
52impl AsRef<[u8; 32]> for Bip340 {
53	fn as_ref(&self) -> &[u8; 32] {
54		&self.0
55	}
56}
57
58impl AsMut<[u8; 32]> for Bip340 {
59	fn as_mut(&mut self) -> &mut [u8; 32] {
60		&mut self.0
61	}
62}
63
64impl From<[u8; 32]> for Bip340 {
65	fn from(x: [u8; 32]) -> Self {
66		Self::new(x)
67	}
68}
69
70impl<'a> TryFrom<&'a [u8]> for Bip340 {
71	type Error = ();
72	fn try_from(x: &'a [u8]) -> Result<Bip340, ()> {
73		if x.len() == 32 {
74			let mut data = [0; 32];
75			data.copy_from_slice(x);
76			Ok(Bip340(data))
77		} else {
78			Err(())
79		}
80	}
81}
82
83impl From<Bip340> for [u8; 32] {
84	fn from(x: Bip340) -> [u8; 32] {
85		x.0
86	}
87}
88
89impl From<Bip340> for AccountId32 {
90	fn from(x: Bip340) -> AccountId32 {
91		x.0.into()
92	}
93}
94
95impl From<sr25519::Public> for Bip340 {
96	fn from(k: sr25519::Public) -> Self {
97		k.0.into()
98	}
99}
100
101impl From<ed25519::Public> for Bip340 {
102	fn from(k: ed25519::Public) -> Self {
103		k.0.into()
104	}
105}
106
107impl core::fmt::Display for Bip340 {
108	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
109		write!(f, "0x{}", sp_core::hexdisplay::HexDisplay::from(&self.0))
110	}
111}
112
113impl core::fmt::Debug for Bip340 {
114	fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
115		write!(f, "0x{}", sp_core::hexdisplay::HexDisplay::from(&self.0))
116	}
117}
118
119#[cfg(feature = "serde_derive")]
120impl serde::Serialize for Bip340 {
121	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
122	where
123		S: serde::Serializer,
124	{
125		#[cfg(not(feature = "std"))]
126		use parity_scale_codec::alloc::string::ToString;
127		serializer.serialize_str(&self.to_string())
128	}
129}
130
131#[cfg(feature = "serde_derive")]
132impl<'de> serde::Deserialize<'de> for Bip340 {
133	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
134	where
135		D: serde::Deserializer<'de>,
136	{
137		#[cfg(not(feature = "std"))]
138		use parity_scale_codec::alloc::string::String;
139		sp_std::str::FromStr::from_str(&String::deserialize(deserializer)?)
140			.map_err(serde::de::Error::custom)
141	}
142}
143
144impl sp_std::str::FromStr for Bip340 {
145	type Err = &'static str;
146
147	fn from_str(s: &str) -> Result<Self, Self::Err> {
148		array_bytes::hex_n_into(s.trim_start_matches("0x")).map_err(|_| "invalid hex address.")
149	}
150}
151
152#[cfg(test)]
153mod tests {
154	use crate::bip340::Bip340;
155	use sp_core::{sr25519, Pair};
156	use std::str::FromStr;
157
158	#[test]
159	pub fn bip340_to_string_works() {
160		let zero_key = Bip340::new([0u8; 32]);
161		let zero_key_str = zero_key.to_string();
162
163		assert_eq!(zero_key_str.len(), 66);
164		assert_eq!(
165			zero_key_str,
166			"0x0000000000000000000000000000000000000000000000000000000000000000"
167		);
168	}
169
170	#[test]
171	pub fn bip340_from_str_works() {
172		let zero_key_str = "0x0000000000000000000000000000000000000000000000000000000000000000";
173		let zero_key: Bip340 = Bip340::from_str(zero_key_str).unwrap();
174		assert_eq!(zero_key, Bip340::new([0u8; 32]));
175	}
176
177	#[test]
178	pub fn bip340_serialize_works() {
179		let zero_key = Bip340::new([0u8; 32]);
180		let zero_key_str = serde_json::to_string(&zero_key).unwrap();
181
182		// contains leading and trailing ".
183		assert_eq!(zero_key_str.len(), 68);
184		assert_eq!(
185			zero_key_str,
186			"\"0x0000000000000000000000000000000000000000000000000000000000000000\""
187		);
188	}
189
190	#[test]
191	pub fn bip340_deserialize_works() {
192		let zero_key_str = "\"0x0000000000000000000000000000000000000000000000000000000000000000\"";
193		let zero_key: Bip340 = serde_json::from_str(zero_key_str).unwrap();
194		assert_eq!(zero_key, Bip340::new([0u8; 32]));
195	}
196
197	#[test]
198	pub fn bip340_deserialize_without_prefix_works() {
199		let zero_key_str = "\"0000000000000000000000000000000000000000000000000000000000000000\"";
200		let zero_key: Bip340 = serde_json::from_str(zero_key_str).unwrap();
201		assert_eq!(zero_key, Bip340::new([0u8; 32]));
202	}
203
204	#[test]
205	pub fn bip340_deserialize_alice_works() {
206		let alice_str = "\"0xd43593c715fdd31c61141abd04a99fd6822c8558854ccde39a5684e7a56da27d\"";
207		let alice: Bip340 = serde_json::from_str(alice_str).unwrap();
208		assert_eq!(
209			alice,
210			Bip340::from(sr25519::Pair::from_string_with_seed("//Alice", None).unwrap().0.public())
211		);
212	}
213}