keypair.rs 8.8 KB

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