keypair.rs 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. use std::{convert::TryFrom, io};
  2. use halo2_gadgets::ecc::chip::FixedPoint;
  3. use pasta_curves::{
  4. group::{
  5. ff::{Field, PrimeField},
  6. Group, GroupEncoding,
  7. },
  8. pallas,
  9. };
  10. use rand::RngCore;
  11. use crate::{
  12. crypto::{address::Address, constants::NullifierK, util::mod_r_p},
  13. util::serial::{Decodable, Encodable, ReadExt, WriteExt},
  14. Error, Result,
  15. };
  16. #[derive(Copy, Clone, PartialEq, Debug)]
  17. #[cfg(feature = "serde")]
  18. #[derive(serde::Deserialize, serde::Serialize)]
  19. pub struct Keypair {
  20. pub secret: SecretKey,
  21. pub public: PublicKey,
  22. }
  23. impl Keypair {
  24. pub fn new(secret: SecretKey) -> Self {
  25. let public = PublicKey::from_secret(secret);
  26. Self { secret, public }
  27. }
  28. pub fn random(mut rng: impl RngCore) -> Self {
  29. let secret = SecretKey::random(&mut rng);
  30. Self::new(secret)
  31. }
  32. }
  33. #[derive(Copy, Clone, PartialEq, Debug)]
  34. pub struct SecretKey(pub pallas::Base);
  35. impl SecretKey {
  36. pub fn random(mut rng: impl RngCore) -> Self {
  37. let x = pallas::Base::random(&mut rng);
  38. Self(x)
  39. }
  40. pub fn to_bytes(self) -> [u8; 32] {
  41. self.0.to_repr()
  42. }
  43. pub fn from_bytes(bytes: [u8; 32]) -> Result<Self> {
  44. match pallas::Base::from_repr(bytes).into() {
  45. Some(k) => Ok(Self(k)),
  46. None => Err(Error::SecretKeyFromBytes),
  47. }
  48. }
  49. }
  50. #[derive(Copy, Clone, PartialEq, Debug)]
  51. pub struct PublicKey(pub pallas::Point);
  52. impl PublicKey {
  53. pub fn random(mut rng: impl RngCore) -> Self {
  54. let p = pallas::Point::random(&mut rng);
  55. Self(p)
  56. }
  57. pub fn from_secret(s: SecretKey) -> Self {
  58. let nfk = NullifierK;
  59. let p = nfk.generator() * mod_r_p(s.0);
  60. Self(p)
  61. }
  62. pub fn to_bytes(self) -> [u8; 32] {
  63. self.0.to_bytes()
  64. }
  65. pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self> {
  66. match pallas::Point::from_bytes(bytes).into() {
  67. Some(k) => Ok(Self(k)),
  68. None => Err(Error::PublicKeyFromBytes),
  69. }
  70. }
  71. }
  72. impl TryFrom<Address> for PublicKey {
  73. type Error = Error;
  74. fn try_from(address: Address) -> Result<Self> {
  75. let mut bytes = [0u8; 32];
  76. bytes.copy_from_slice(&address.0[1..33]);
  77. Self::from_bytes(&bytes)
  78. }
  79. }
  80. impl Encodable for pallas::Base {
  81. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  82. s.write_slice(&self.to_repr()[..])?;
  83. Ok(32)
  84. }
  85. }
  86. impl Decodable for pallas::Base {
  87. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  88. let mut bytes = [0u8; 32];
  89. d.read_slice(&mut bytes)?;
  90. let result = pallas::Base::from_repr(bytes);
  91. if result.is_some().into() {
  92. Ok(result.unwrap())
  93. } else {
  94. Err(Error::BadOperationType)
  95. }
  96. }
  97. }
  98. impl Encodable for pallas::Scalar {
  99. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  100. s.write_slice(&self.to_repr()[..])?;
  101. Ok(32)
  102. }
  103. }
  104. impl Decodable for pallas::Scalar {
  105. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  106. let mut bytes = [0u8; 32];
  107. d.read_slice(&mut bytes)?;
  108. let result = pallas::Scalar::from_repr(bytes);
  109. if result.is_some().into() {
  110. Ok(result.unwrap())
  111. } else {
  112. Err(Error::BadOperationType)
  113. }
  114. }
  115. }
  116. impl Encodable for pallas::Point {
  117. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  118. s.write_slice(&self.to_bytes()[..])?;
  119. Ok(32)
  120. }
  121. }
  122. impl Decodable for pallas::Point {
  123. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  124. let mut bytes = [0u8; 32];
  125. d.read_slice(&mut bytes)?;
  126. let result = Self::from_bytes(&bytes);
  127. if result.is_some().into() {
  128. Ok(result.unwrap())
  129. } else {
  130. Err(Error::BadOperationType)
  131. }
  132. }
  133. }
  134. impl Encodable for SecretKey {
  135. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  136. s.write_slice(&self.0.to_repr()[..])?;
  137. Ok(32)
  138. }
  139. }
  140. impl Decodable for SecretKey {
  141. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  142. let mut bytes = [0u8; 32];
  143. d.read_slice(&mut bytes)?;
  144. let result = pallas::Base::from_repr(bytes);
  145. if result.is_some().into() {
  146. Ok(SecretKey(result.unwrap()))
  147. } else {
  148. Err(Error::BadOperationType)
  149. }
  150. }
  151. }
  152. impl Encodable for PublicKey {
  153. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  154. s.write_slice(&self.0.to_bytes()[..])?;
  155. Ok(32)
  156. }
  157. }
  158. impl Decodable for PublicKey {
  159. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  160. let mut bytes = [0u8; 32];
  161. d.read_slice(&mut bytes)?;
  162. let result = pallas::Point::from_bytes(&bytes);
  163. if result.is_some().into() {
  164. Ok(PublicKey(result.unwrap()))
  165. } else {
  166. Err(Error::BadOperationType)
  167. }
  168. }
  169. }
  170. #[cfg(feature = "serde")]
  171. impl serde::Serialize for SecretKey {
  172. fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
  173. where
  174. S: serde::Serializer,
  175. {
  176. let mut bytes = vec![];
  177. self.encode(&mut bytes).unwrap();
  178. let hex_repr = hex::encode(&bytes);
  179. serializer.serialize_str(&hex_repr)
  180. }
  181. }
  182. #[cfg(feature = "serde")]
  183. struct SecretKeyVisitor;
  184. #[cfg(feature = "serde")]
  185. impl<'de> serde::de::Visitor<'de> for SecretKeyVisitor {
  186. type Value = SecretKey;
  187. fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
  188. formatter.write_str("hex string")
  189. }
  190. fn visit_str<E>(self, value: &str) -> std::result::Result<SecretKey, E>
  191. where
  192. E: serde::de::Error,
  193. {
  194. let bytes = hex::decode(value).unwrap();
  195. let mut r = std::io::Cursor::new(bytes);
  196. let decoded: SecretKey = SecretKey::decode(&mut r).unwrap();
  197. Ok(decoded)
  198. }
  199. }
  200. #[cfg(feature = "serde")]
  201. impl<'de> serde::Deserialize<'de> for SecretKey {
  202. fn deserialize<D>(deserializer: D) -> std::result::Result<SecretKey, D::Error>
  203. where
  204. D: serde::Deserializer<'de>,
  205. {
  206. let bytes = deserializer.deserialize_str(SecretKeyVisitor).unwrap();
  207. Ok(bytes)
  208. }
  209. }
  210. #[cfg(feature = "serde")]
  211. impl serde::Serialize for PublicKey {
  212. fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
  213. where
  214. S: serde::Serializer,
  215. {
  216. let mut bytes = vec![];
  217. self.encode(&mut bytes).unwrap();
  218. let hex_repr = hex::encode(&bytes);
  219. serializer.serialize_str(&hex_repr)
  220. }
  221. }
  222. #[cfg(feature = "serde")]
  223. struct PublicKeyVisitor;
  224. #[cfg(feature = "serde")]
  225. impl<'de> serde::de::Visitor<'de> for PublicKeyVisitor {
  226. type Value = PublicKey;
  227. fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
  228. formatter.write_str("hex string")
  229. }
  230. fn visit_str<E>(self, value: &str) -> std::result::Result<PublicKey, E>
  231. where
  232. E: serde::de::Error,
  233. {
  234. let bytes = hex::decode(value).unwrap();
  235. let mut r = std::io::Cursor::new(bytes);
  236. let decoded: PublicKey = PublicKey::decode(&mut r).unwrap();
  237. Ok(decoded)
  238. }
  239. }
  240. #[cfg(feature = "serde")]
  241. impl<'de> serde::Deserialize<'de> for PublicKey {
  242. fn deserialize<D>(deserializer: D) -> std::result::Result<PublicKey, D::Error>
  243. where
  244. D: serde::Deserializer<'de>,
  245. {
  246. let bytes = deserializer.deserialize_str(PublicKeyVisitor).unwrap();
  247. Ok(bytes)
  248. }
  249. }
  250. #[cfg(test)]
  251. mod tests {
  252. use super::*;
  253. use crate::{
  254. crypto::util::pedersen_commitment_scalar,
  255. util::serial::{deserialize, serialize},
  256. };
  257. #[test]
  258. fn test_pasta_serialization() -> Result<()> {
  259. let fifty_five = pallas::Base::from(55);
  260. let serialized = serialize(&fifty_five);
  261. assert_eq!(
  262. serialized,
  263. vec![
  264. 55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  265. 0, 0, 0, 0, 0
  266. ]
  267. );
  268. assert_eq!(deserialize(&serialized).ok(), Some(fifty_five));
  269. let fourtwenty = pallas::Scalar::from(42069);
  270. let serialized = serialize(&fourtwenty);
  271. assert_eq!(
  272. serialized,
  273. vec![
  274. 85, 164, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  275. 0, 0, 0, 0, 0
  276. ]
  277. );
  278. assert_eq!(deserialize(&serialized).ok(), Some(fourtwenty));
  279. let a = pallas::Scalar::from(420);
  280. let b = pallas::Scalar::from(69);
  281. let pc: pallas::Point = pedersen_commitment_scalar(a, b);
  282. let serialized = serialize(&pc);
  283. assert_eq!(
  284. serialized,
  285. vec![
  286. 55, 48, 126, 42, 114, 27, 18, 55, 155, 141, 83, 75, 44, 50, 244, 223, 254, 216, 22,
  287. 167, 208, 59, 212, 201, 150, 149, 96, 207, 216, 74, 60, 131
  288. ]
  289. );
  290. assert_eq!(deserialize(&serialized).ok(), Some(pc));
  291. Ok(())
  292. }
  293. }