Skip to main content

bee_crypto/ternary/sponge/
mod.rs

1// Copyright 2020-2021 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4//! Ternary sponge constructions.
5
6mod curlp;
7mod kerl;
8mod kind;
9
10use super::HASH_LENGTH;
11
12pub use curlp::{BatchHasher, CurlP, CurlP27, CurlP81, CurlPRounds, UnrolledCurlP81, BATCH_SIZE};
13pub use kerl::Kerl;
14pub use kind::SpongeKind;
15
16use bee_ternary::{TritBuf, Trits};
17
18use std::ops::DerefMut;
19
20/// The common interface of ternary cryptographic hash functions that follow the sponge construction.
21pub trait Sponge {
22    /// An error indicating that a failure has occured during a sponge operation.
23    type Error;
24
25    /// Reset the inner state of the sponge.
26    fn reset(&mut self);
27
28    /// Absorb `input` into the sponge.
29    fn absorb(&mut self, input: &Trits) -> Result<(), Self::Error>;
30
31    /// Squeeze the sponge into `buf`.
32    fn squeeze_into(&mut self, buf: &mut Trits) -> Result<(), Self::Error>;
33
34    /// Convenience function using `Sponge::squeeze_into` to return an owned output.
35    fn squeeze(&mut self) -> Result<TritBuf, Self::Error> {
36        let mut output = TritBuf::zeros(HASH_LENGTH);
37        self.squeeze_into(&mut output)?;
38        Ok(output)
39    }
40
41    /// Convenience function to absorb `input`, squeeze the sponge into `buf`, and reset the sponge.
42    fn digest_into(&mut self, input: &Trits, buf: &mut Trits) -> Result<(), Self::Error> {
43        self.absorb(input)?;
44        self.squeeze_into(buf)?;
45        self.reset();
46        Ok(())
47    }
48
49    /// Convenience function to absorb `input`, squeeze the sponge, reset the sponge and return an owned output.
50    fn digest(&mut self, input: &Trits) -> Result<TritBuf, Self::Error> {
51        self.absorb(input)?;
52        let output = self.squeeze()?;
53        self.reset();
54        Ok(output)
55    }
56}
57
58impl<T: Sponge, U: DerefMut<Target = T>> Sponge for U {
59    type Error = T::Error;
60
61    fn reset(&mut self) {
62        T::reset(self)
63    }
64
65    fn absorb(&mut self, input: &Trits) -> Result<(), Self::Error> {
66        T::absorb(self, input)
67    }
68
69    fn squeeze_into(&mut self, buf: &mut Trits) -> Result<(), Self::Error> {
70        T::squeeze_into(self, buf)
71    }
72}