sinsemilla.rs 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280
  1. //! The Sinsemilla hash function and commitment scheme.
  2. use group::Wnaf;
  3. use halo2::arithmetic::{CurveAffine, CurveExt};
  4. use pasta_curves::pallas;
  5. use subtle::CtOption;
  6. use crate::spec::{extract_p_bottom, i2lebsp};
  7. mod addition;
  8. use self::addition::IncompletePoint;
  9. mod constants;
  10. mod sinsemilla_s;
  11. pub use constants::*;
  12. pub(crate) use sinsemilla_s::*;
  13. pub(crate) fn lebs2ip_k(bits: &[bool]) -> u32 {
  14. assert!(bits.len() == K);
  15. bits.iter()
  16. .enumerate()
  17. .fold(0u32, |acc, (i, b)| acc + if *b { 1 << i } else { 0 })
  18. }
  19. /// The sequence of K bits in little-endian order representing an integer
  20. /// up to `2^K` - 1.
  21. pub(crate) fn i2lebsp_k(int: usize) -> [bool; K] {
  22. assert!(int < (1 << K));
  23. i2lebsp(int as u64)
  24. }
  25. /// Pads the given iterator (which MUST have length $\leq K * C$) with zero-bits to a
  26. /// multiple of $K$ bits.
  27. struct Pad<I: Iterator<Item = bool>> {
  28. /// The iterator we are padding.
  29. inner: I,
  30. /// The measured length of the inner iterator.
  31. ///
  32. /// This starts as a lower bound, and will be accurate once `padding_left.is_some()`.
  33. len: usize,
  34. /// The amount of padding that remains to be emitted.
  35. padding_left: Option<usize>,
  36. }
  37. impl<I: Iterator<Item = bool>> Pad<I> {
  38. fn new(inner: I) -> Self {
  39. Pad {
  40. inner,
  41. len: 0,
  42. padding_left: None,
  43. }
  44. }
  45. }
  46. impl<I: Iterator<Item = bool>> Iterator for Pad<I> {
  47. type Item = bool;
  48. fn next(&mut self) -> Option<Self::Item> {
  49. loop {
  50. // If we have identified the required padding, the inner iterator has ended,
  51. // and we will never poll it again.
  52. if let Some(n) = self.padding_left.as_mut() {
  53. if *n == 0 {
  54. // Either we already emitted all necessary padding, or there was no
  55. // padding required.
  56. break None;
  57. } else {
  58. // Emit the next padding bit.
  59. *n -= 1;
  60. break Some(false);
  61. }
  62. } else if let Some(ret) = self.inner.next() {
  63. // We haven't reached the end of the inner iterator yet.
  64. self.len += 1;
  65. assert!(self.len <= K * C);
  66. break Some(ret);
  67. } else {
  68. // Inner iterator just ended, so we now know its length.
  69. let rem = self.len % K;
  70. if rem > 0 {
  71. // The inner iterator requires padding in the range [1,K).
  72. self.padding_left = Some(K - rem);
  73. } else {
  74. // No padding required.
  75. self.padding_left = Some(0);
  76. }
  77. }
  78. }
  79. }
  80. }
  81. /// A domain in which $\mathsf{SinsemillaHashToPoint}$ and $\mathsf{SinsemillaHash}$ can
  82. /// be used.
  83. #[derive(Debug, Clone)]
  84. #[allow(non_snake_case)]
  85. pub struct HashDomain {
  86. Q: pallas::Point,
  87. }
  88. impl HashDomain {
  89. /// Constructs a new `HashDomain` with a specific prefix string.
  90. pub fn new(domain: &str) -> Self {
  91. HashDomain {
  92. Q: pallas::Point::hash_to_curve(Q_PERSONALIZATION)(domain.as_bytes()),
  93. }
  94. }
  95. /// $\mathsf{SinsemillaHashToPoint}$ from [§ 5.4.1.9][concretesinsemillahash].
  96. ///
  97. /// [concretesinsemillahash]: https://zips.z.cash/protocol/nu5.pdf#concretesinsemillahash
  98. pub fn hash_to_point(&self, msg: impl Iterator<Item = bool>) -> CtOption<pallas::Point> {
  99. self.hash_to_point_inner(msg).into()
  100. }
  101. #[allow(non_snake_case)]
  102. fn hash_to_point_inner(&self, msg: impl Iterator<Item = bool>) -> IncompletePoint {
  103. let padded: Vec<_> = Pad::new(msg).collect();
  104. padded
  105. .chunks(K)
  106. .fold(IncompletePoint::from(self.Q), |acc, chunk| {
  107. let (S_x, S_y) = SINSEMILLA_S[lebs2ip_k(chunk) as usize];
  108. let S_chunk = pallas::Affine::from_xy(S_x, S_y).unwrap();
  109. (acc + S_chunk) + acc
  110. })
  111. }
  112. /// $\mathsf{SinsemillaHash}$ from [§ 5.4.1.9][concretesinsemillahash].
  113. ///
  114. /// [concretesinsemillahash]: https://zips.z.cash/protocol/nu5.pdf#concretesinsemillahash
  115. ///
  116. /// # Panics
  117. ///
  118. /// This panics if the message length is greater than [`K`] * [`C`]
  119. pub fn hash(&self, msg: impl Iterator<Item = bool>) -> CtOption<pallas::Base> {
  120. extract_p_bottom(self.hash_to_point(msg))
  121. }
  122. /// Returns the Sinsemilla $Q$ constant for this domain.
  123. #[cfg(test)]
  124. #[allow(non_snake_case)]
  125. pub(crate) fn Q(&self) -> pallas::Point {
  126. self.Q
  127. }
  128. }
  129. /// A domain in which $\mathsf{SinsemillaCommit}$ and $\mathsf{SinsemillaShortCommit}$ can
  130. /// be used.
  131. #[derive(Debug)]
  132. #[allow(non_snake_case)]
  133. pub struct CommitDomain {
  134. M: HashDomain,
  135. R: pallas::Point,
  136. }
  137. impl CommitDomain {
  138. /// Constructs a new `CommitDomain` with a specific prefix string.
  139. pub fn new(domain: &str) -> Self {
  140. let m_prefix = format!("{}-M", domain);
  141. let r_prefix = format!("{}-r", domain);
  142. let hasher_r = pallas::Point::hash_to_curve(&r_prefix);
  143. CommitDomain {
  144. M: HashDomain::new(&m_prefix),
  145. R: hasher_r(&[]),
  146. }
  147. }
  148. /// $\mathsf{SinsemillaCommit}$ from [§ 5.4.8.4][concretesinsemillacommit].
  149. ///
  150. /// [concretesinsemillacommit]: https://zips.z.cash/protocol/nu5.pdf#concretesinsemillacommit
  151. #[allow(non_snake_case)]
  152. pub fn commit(
  153. &self,
  154. msg: impl Iterator<Item = bool>,
  155. r: &pallas::Scalar,
  156. ) -> CtOption<pallas::Point> {
  157. (self.M.hash_to_point_inner(msg) + Wnaf::new().scalar(r).base(self.R)).into()
  158. }
  159. /// $\mathsf{SinsemillaShortCommit}$ from [§ 5.4.8.4][concretesinsemillacommit].
  160. ///
  161. /// [concretesinsemillacommit]: https://zips.z.cash/protocol/nu5.pdf#concretesinsemillacommit
  162. pub fn short_commit(
  163. &self,
  164. msg: impl Iterator<Item = bool>,
  165. r: &pallas::Scalar,
  166. ) -> CtOption<pallas::Base> {
  167. extract_p_bottom(self.commit(msg, r))
  168. }
  169. /// Returns the Sinsemilla $R$ constant for this domain.
  170. #[cfg(test)]
  171. #[allow(non_snake_case)]
  172. pub(crate) fn R(&self) -> pallas::Point {
  173. self.R
  174. }
  175. }
  176. #[cfg(test)]
  177. mod tests {
  178. use super::{i2lebsp_k, lebs2ip_k, Pad, K};
  179. use rand::{self, rngs::OsRng, Rng};
  180. #[test]
  181. fn pad() {
  182. assert_eq!(Pad::new([].iter().cloned()).collect::<Vec<_>>(), vec![]);
  183. assert_eq!(
  184. Pad::new([true].iter().cloned()).collect::<Vec<_>>(),
  185. vec![true, false, false, false, false, false, false, false, false, false]
  186. );
  187. assert_eq!(
  188. Pad::new([true, true].iter().cloned()).collect::<Vec<_>>(),
  189. vec![true, true, false, false, false, false, false, false, false, false]
  190. );
  191. assert_eq!(
  192. Pad::new([true, true, true].iter().cloned()).collect::<Vec<_>>(),
  193. vec![true, true, true, false, false, false, false, false, false, false]
  194. );
  195. assert_eq!(
  196. Pad::new(
  197. [true, true, false, true, false, true, false, true, false, true]
  198. .iter()
  199. .cloned()
  200. )
  201. .collect::<Vec<_>>(),
  202. vec![true, true, false, true, false, true, false, true, false, true]
  203. );
  204. assert_eq!(
  205. Pad::new(
  206. [true, true, false, true, false, true, false, true, false, true, true]
  207. .iter()
  208. .cloned()
  209. )
  210. .collect::<Vec<_>>(),
  211. vec![
  212. true, true, false, true, false, true, false, true, false, true, true, false, false,
  213. false, false, false, false, false, false, false
  214. ]
  215. );
  216. }
  217. #[test]
  218. fn lebs2ip_k_round_trip() {
  219. let mut rng = OsRng;
  220. {
  221. let int = rng.gen_range(0..(1 << K));
  222. assert_eq!(lebs2ip_k(&i2lebsp_k(int)) as usize, int);
  223. }
  224. assert_eq!(lebs2ip_k(&i2lebsp_k(0)) as usize, 0);
  225. assert_eq!(lebs2ip_k(&i2lebsp_k((1 << K) - 1)) as usize, (1 << K) - 1);
  226. }
  227. #[test]
  228. fn i2lebsp_k_round_trip() {
  229. {
  230. let bitstring = (0..K).map(|_| rand::random()).collect::<Vec<_>>();
  231. assert_eq!(
  232. i2lebsp_k(lebs2ip_k(&bitstring) as usize).to_vec(),
  233. bitstring
  234. );
  235. }
  236. {
  237. let bitstring = [false; K];
  238. assert_eq!(
  239. i2lebsp_k(lebs2ip_k(&bitstring) as usize).to_vec(),
  240. bitstring
  241. );
  242. }
  243. {
  244. let bitstring = [true; K];
  245. assert_eq!(
  246. i2lebsp_k(lebs2ip_k(&bitstring) as usize).to_vec(),
  247. bitstring
  248. );
  249. }
  250. }
  251. }