keypair.rs 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  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. pub struct Keypair {
  18. pub secret: SecretKey,
  19. pub public: PublicKey,
  20. }
  21. impl Keypair {
  22. pub fn new(secret: SecretKey) -> Self {
  23. let public = PublicKey::from_secret(secret);
  24. Self { secret, public }
  25. }
  26. pub fn random(mut rng: impl RngCore) -> Self {
  27. let secret = SecretKey::random(&mut rng);
  28. Self::new(secret)
  29. }
  30. }
  31. #[derive(Copy, Clone, PartialEq, Debug)]
  32. pub struct SecretKey(pub pallas::Base);
  33. impl SecretKey {
  34. pub fn random(mut rng: impl RngCore) -> Self {
  35. let x = pallas::Base::random(&mut rng);
  36. Self(x)
  37. }
  38. pub fn to_bytes(self) -> [u8; 32] {
  39. self.0.to_repr()
  40. }
  41. pub fn from_bytes(bytes: [u8; 32]) -> Result<Self> {
  42. match pallas::Base::from_repr(bytes).into() {
  43. Some(k) => Ok(Self(k)),
  44. None => Err(Error::SecretKeyFromBytes),
  45. }
  46. }
  47. }
  48. #[derive(Copy, Clone, PartialEq, Debug)]
  49. pub struct PublicKey(pub pallas::Point);
  50. impl PublicKey {
  51. pub fn random(mut rng: impl RngCore) -> Self {
  52. let p = pallas::Point::random(&mut rng);
  53. Self(p)
  54. }
  55. pub fn from_secret(s: SecretKey) -> Self {
  56. let nfk = NullifierK;
  57. let p = nfk.generator() * mod_r_p(s.0);
  58. Self(p)
  59. }
  60. pub fn to_bytes(self) -> [u8; 32] {
  61. self.0.to_bytes()
  62. }
  63. pub fn from_bytes(bytes: &[u8; 32]) -> Result<Self> {
  64. match pallas::Point::from_bytes(bytes).into() {
  65. Some(k) => Ok(Self(k)),
  66. None => Err(Error::PublicKeyFromBytes),
  67. }
  68. }
  69. }
  70. impl TryFrom<Address> for PublicKey {
  71. type Error = Error;
  72. fn try_from(address: Address) -> Result<Self> {
  73. let mut bytes = [0u8; 32];
  74. bytes.copy_from_slice(&address.0[1..33]);
  75. Self::from_bytes(&bytes)
  76. }
  77. }
  78. impl Encodable for pallas::Base {
  79. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  80. s.write_slice(&self.to_repr()[..])?;
  81. Ok(32)
  82. }
  83. }
  84. impl Decodable for pallas::Base {
  85. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  86. let mut bytes = [0u8; 32];
  87. d.read_slice(&mut bytes)?;
  88. let result = pallas::Base::from_repr(bytes);
  89. if result.is_some().into() {
  90. Ok(result.unwrap())
  91. } else {
  92. Err(Error::BadOperationType)
  93. }
  94. }
  95. }
  96. impl Encodable for pallas::Scalar {
  97. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  98. s.write_slice(&self.to_repr()[..])?;
  99. Ok(32)
  100. }
  101. }
  102. impl Decodable for pallas::Scalar {
  103. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  104. let mut bytes = [0u8; 32];
  105. d.read_slice(&mut bytes)?;
  106. let result = pallas::Scalar::from_repr(bytes);
  107. if result.is_some().into() {
  108. Ok(result.unwrap())
  109. } else {
  110. Err(Error::BadOperationType)
  111. }
  112. }
  113. }
  114. impl Encodable for pallas::Point {
  115. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  116. s.write_slice(&self.to_bytes()[..])?;
  117. Ok(32)
  118. }
  119. }
  120. impl Decodable for pallas::Point {
  121. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  122. let mut bytes = [0u8; 32];
  123. d.read_slice(&mut bytes)?;
  124. let result = Self::from_bytes(&bytes);
  125. if result.is_some().into() {
  126. Ok(result.unwrap())
  127. } else {
  128. Err(Error::BadOperationType)
  129. }
  130. }
  131. }
  132. impl Encodable for SecretKey {
  133. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  134. s.write_slice(&self.0.to_repr()[..])?;
  135. Ok(32)
  136. }
  137. }
  138. impl Decodable for SecretKey {
  139. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  140. let mut bytes = [0u8; 32];
  141. d.read_slice(&mut bytes)?;
  142. let result = pallas::Base::from_repr(bytes);
  143. if result.is_some().into() {
  144. Ok(SecretKey(result.unwrap()))
  145. } else {
  146. Err(Error::BadOperationType)
  147. }
  148. }
  149. }
  150. impl Encodable for PublicKey {
  151. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  152. s.write_slice(&self.0.to_bytes()[..])?;
  153. Ok(32)
  154. }
  155. }
  156. impl Decodable for PublicKey {
  157. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  158. let mut bytes = [0u8; 32];
  159. d.read_slice(&mut bytes)?;
  160. let result = pallas::Point::from_bytes(&bytes);
  161. if result.is_some().into() {
  162. Ok(PublicKey(result.unwrap()))
  163. } else {
  164. Err(Error::BadOperationType)
  165. }
  166. }
  167. }
  168. #[cfg(test)]
  169. mod tests {
  170. use super::*;
  171. use crate::{
  172. crypto::util::pedersen_commitment_scalar,
  173. util::serial::{deserialize, serialize},
  174. };
  175. #[test]
  176. fn test_pasta_serialization() -> Result<()> {
  177. let fifty_five = pallas::Base::from(55);
  178. let serialized = serialize(&fifty_five);
  179. assert_eq!(
  180. serialized,
  181. vec![
  182. 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,
  183. 0, 0, 0, 0, 0
  184. ]
  185. );
  186. assert_eq!(deserialize(&serialized).ok(), Some(fifty_five));
  187. let fourtwenty = pallas::Scalar::from(42069);
  188. let serialized = serialize(&fourtwenty);
  189. assert_eq!(
  190. serialized,
  191. vec![
  192. 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,
  193. 0, 0, 0, 0, 0
  194. ]
  195. );
  196. assert_eq!(deserialize(&serialized).ok(), Some(fourtwenty));
  197. let a = pallas::Scalar::from(420);
  198. let b = pallas::Scalar::from(69);
  199. let pc: pallas::Point = pedersen_commitment_scalar(a, b);
  200. let serialized = serialize(&pc);
  201. assert_eq!(
  202. serialized,
  203. vec![
  204. 55, 48, 126, 42, 114, 27, 18, 55, 155, 141, 83, 75, 44, 50, 244, 223, 254, 216, 22,
  205. 167, 208, 59, 212, 201, 150, 149, 96, 207, 216, 74, 60, 131
  206. ]
  207. );
  208. assert_eq!(deserialize(&serialized).ok(), Some(pc));
  209. Ok(())
  210. }
  211. }