keypair.rs 6.3 KB

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