group_serde.rs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. //! serde adaptors for Group + GroupEncoding and for PrimeField
  2. //!
  3. //! Adapted from [elliptic_curve_tools](https://crates.io/crates/elliptic-curve-tool)
  4. //! v0.1.2 by Michael Lodder.
  5. //! Lodder's original can be adapted under the terms of the MIT license:
  6. //!
  7. //! [No explicit copyright line was present in that package's
  8. //! LICENSE-MIT file.]
  9. //!
  10. //! Permission is hereby granted, free of charge, to any
  11. //! person obtaining a copy of this software and associated
  12. //! documentation files (the "Software"), to deal in the
  13. //! Software without restriction, including without
  14. //! limitation the rights to use, copy, modify, merge,
  15. //! publish, distribute, sublicense, and/or sell copies of
  16. //! the Software, and to permit persons to whom the Software
  17. //! is furnished to do so, subject to the following
  18. //! conditions:
  19. //!
  20. //! The above copyright notice and this permission notice
  21. //! shall be included in all copies or substantial portions
  22. //! of the Software.
  23. //!
  24. //! THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
  25. //! ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
  26. //! TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
  27. //! PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
  28. //! SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  29. //! CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. //! OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
  31. //! IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  32. //! DEALINGS IN THE SOFTWARE.
  33. use core::{
  34. fmt::{self, Formatter},
  35. marker::PhantomData,
  36. };
  37. use ff::PrimeField;
  38. use group::{Group, GroupEncoding};
  39. use serde::{
  40. self,
  41. de::{Error as DError, Visitor},
  42. Deserializer, Serializer,
  43. };
  44. /// Serialize a group element.
  45. pub fn serialize_point<G, S>(g: &G, s: S) -> Result<S::Ok, S::Error>
  46. where
  47. S: Serializer,
  48. G: Group + GroupEncoding,
  49. {
  50. serialize_(g.to_bytes(), s)
  51. }
  52. /// Deserialize a group element.
  53. pub fn deserialize_point<'de, G, D>(d: D) -> Result<G, D::Error>
  54. where
  55. D: Deserializer<'de>,
  56. G: Group + GroupEncoding,
  57. {
  58. let bytes = deserialize_(d)?;
  59. Option::from(G::from_bytes(&bytes)).ok_or(DError::custom("invalid group element"))
  60. }
  61. /// Serialize a prime field element.
  62. pub fn serialize_scalar<F, S>(f: &F, s: S) -> Result<S::Ok, S::Error>
  63. where
  64. S: Serializer,
  65. F: PrimeField,
  66. {
  67. serialize_(f.to_repr(), s)
  68. }
  69. /// Deserialize a prime field element.
  70. pub fn deserialize_scalar<'de, F, D>(d: D) -> Result<F, D::Error>
  71. where
  72. D: Deserializer<'de>,
  73. F: PrimeField,
  74. {
  75. let repr = deserialize_(d)?;
  76. Option::from(F::from_repr(repr)).ok_or(DError::custom("invalid prime field element"))
  77. }
  78. fn serialize_<B, S>(bytes: B, s: S) -> Result<S::Ok, S::Error>
  79. where
  80. S: Serializer,
  81. B: AsRef<[u8]> + AsMut<[u8]> + Default,
  82. {
  83. if s.is_human_readable() {
  84. s.serialize_str(&hex::encode(bytes.as_ref()))
  85. } else {
  86. s.serialize_bytes(bytes.as_ref())
  87. }
  88. }
  89. fn deserialize_<'de, B: AsRef<[u8]> + AsMut<[u8]> + Default, D: Deserializer<'de>>(
  90. d: D,
  91. ) -> Result<B, D::Error> {
  92. if d.is_human_readable() {
  93. struct StrVisitor<B: AsRef<[u8]> + AsMut<[u8]> + Default>(PhantomData<B>);
  94. impl<'de, B> Visitor<'de> for StrVisitor<B>
  95. where
  96. B: AsRef<[u8]> + AsMut<[u8]> + Default,
  97. {
  98. type Value = B;
  99. fn expecting(&self, f: &mut Formatter) -> fmt::Result {
  100. write!(f, "a {} length hex string", B::default().as_ref().len() * 2)
  101. }
  102. fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
  103. where
  104. E: DError,
  105. {
  106. let mut repr = B::default();
  107. let length = repr.as_ref().len();
  108. if v.len() != length * 2 {
  109. return Err(DError::custom("invalid length"));
  110. }
  111. hex::decode_to_slice(v, repr.as_mut())
  112. .map_err(|_| DError::custom("invalid input"))?;
  113. Ok(repr)
  114. }
  115. }
  116. d.deserialize_str(StrVisitor(PhantomData))
  117. } else {
  118. struct ByteVisitor<B: AsRef<[u8]> + AsMut<[u8]> + Default>(PhantomData<B>);
  119. impl<'de, B> Visitor<'de> for ByteVisitor<B>
  120. where
  121. B: AsRef<[u8]> + AsMut<[u8]> + Default,
  122. {
  123. type Value = B;
  124. fn expecting(&self, f: &mut Formatter) -> fmt::Result {
  125. write!(f, "a {} byte", B::default().as_ref().len())
  126. }
  127. fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
  128. where
  129. E: serde::de::Error,
  130. {
  131. let mut repr = B::default();
  132. if v.len() != repr.as_ref().len() {
  133. return Err(serde::de::Error::custom("invalid length"));
  134. }
  135. repr.as_mut().copy_from_slice(v);
  136. Ok(repr)
  137. }
  138. }
  139. d.deserialize_bytes(ByteVisitor(PhantomData))
  140. }
  141. }