schnorr.rs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128
  1. use std::io;
  2. use halo2_gadgets::ecc::chip::FixedPoint;
  3. use pasta_curves::{
  4. group::{ff::Field, GroupEncoding},
  5. pallas,
  6. };
  7. use rand::rngs::OsRng;
  8. use crate::{
  9. crypto::{
  10. constants::{NullifierK, DRK_SCHNORR_DOMAIN},
  11. keypair::{PublicKey, SecretKey},
  12. util::{hash_to_scalar, mod_r_p},
  13. },
  14. util::serial::{Decodable, Encodable},
  15. Result,
  16. };
  17. #[derive(Debug, Clone, PartialEq)]
  18. pub struct Signature {
  19. commit: pallas::Point,
  20. response: pallas::Scalar,
  21. }
  22. pub trait SchnorrSecret {
  23. fn sign(&self, message: &[u8]) -> Signature;
  24. }
  25. pub trait SchnorrPublic {
  26. fn verify(&self, message: &[u8], signature: &Signature) -> bool;
  27. }
  28. impl SchnorrSecret for SecretKey {
  29. fn sign(&self, message: &[u8]) -> Signature {
  30. let mask = pallas::Scalar::random(&mut OsRng);
  31. let nfk = NullifierK;
  32. let commit = nfk.generator() * mask;
  33. let challenge = hash_to_scalar(DRK_SCHNORR_DOMAIN, &commit.to_bytes(), message);
  34. let response = mask + challenge * mod_r_p(self.0);
  35. Signature { commit, response }
  36. }
  37. }
  38. impl SchnorrPublic for PublicKey {
  39. fn verify(&self, message: &[u8], signature: &Signature) -> bool {
  40. let challenge = hash_to_scalar(DRK_SCHNORR_DOMAIN, &signature.commit.to_bytes(), message);
  41. let nfk = NullifierK;
  42. nfk.generator() * signature.response - self.0 * challenge == signature.commit
  43. }
  44. }
  45. impl Encodable for Signature {
  46. fn encode<S: io::Write>(&self, mut s: S) -> Result<usize> {
  47. let mut len = 0;
  48. len += self.commit.encode(&mut s)?;
  49. len += self.response.encode(s)?;
  50. Ok(len)
  51. }
  52. }
  53. impl Decodable for Signature {
  54. fn decode<D: io::Read>(mut d: D) -> Result<Self> {
  55. Ok(Self { commit: Decodable::decode(&mut d)?, response: Decodable::decode(d)? })
  56. }
  57. }
  58. #[cfg(feature = "serde")]
  59. impl serde::Serialize for Signature {
  60. fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
  61. where
  62. S: serde::Serializer,
  63. {
  64. let mut bytes = vec![];
  65. self.encode(&mut bytes).unwrap();
  66. let hex_repr = hex::encode(&bytes);
  67. serializer.serialize_str(&hex_repr)
  68. }
  69. }
  70. #[cfg(feature = "serde")]
  71. struct SignatureVisitor;
  72. #[cfg(feature = "serde")]
  73. impl<'de> serde::de::Visitor<'de> for SignatureVisitor {
  74. type Value = Signature;
  75. fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
  76. formatter.write_str("hex string")
  77. }
  78. fn visit_str<E>(self, value: &str) -> std::result::Result<Signature, E>
  79. where
  80. E: serde::de::Error,
  81. {
  82. let bytes = hex::decode(value).unwrap();
  83. let mut r = std::io::Cursor::new(bytes);
  84. let decoded: Signature = Signature::decode(&mut r).unwrap();
  85. Ok(decoded)
  86. }
  87. }
  88. #[cfg(feature = "serde")]
  89. impl<'de> serde::Deserialize<'de> for Signature {
  90. fn deserialize<D>(deserializer: D) -> std::result::Result<Signature, D::Error>
  91. where
  92. D: serde::Deserializer<'de>,
  93. {
  94. let bytes = deserializer.deserialize_str(SignatureVisitor).unwrap();
  95. Ok(bytes)
  96. }
  97. }
  98. #[cfg(test)]
  99. mod tests {
  100. use super::*;
  101. #[test]
  102. fn test_schnorr() {
  103. let secret = SecretKey::random(&mut OsRng);
  104. let message = b"Foo bar";
  105. let signature = secret.sign(&message[..]);
  106. let public = PublicKey::from_secret(secret);
  107. assert!(public.verify(&message[..], &signature));
  108. }
  109. }