bee_block/output/
inputs_commitment.rs

1// Copyright 2022 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use crypto::hashes::{blake2b::Blake2b256, Digest};
5use derive_more::{Deref, From};
6use packable::PackableExt;
7
8use crate::output::Output;
9
10/// Represents a commitment to transaction inputs.
11#[derive(Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, From, Deref, packable::Packable)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13pub struct InputsCommitment([u8; Self::LENGTH]);
14
15impl InputsCommitment {
16    /// The length of an [`InputsCommitment`].
17    pub const LENGTH: usize = 32;
18
19    /// Creates a new [`InputsCommitment`] from a sequence of [`Output`]s.
20    pub fn new<'a>(inputs: impl Iterator<Item = &'a Output>) -> Self {
21        let mut hasher = Blake2b256::new();
22
23        inputs.for_each(|output| hasher.update(Blake2b256::digest(&output.pack_to_vec())));
24
25        Self(hasher.finalize().into())
26    }
27}
28
29impl core::str::FromStr for InputsCommitment {
30    type Err = crate::Error;
31
32    fn from_str(s: &str) -> Result<Self, Self::Err> {
33        Ok(InputsCommitment::from(
34            prefix_hex::decode::<[u8; 32]>(s).map_err(crate::Error::HexError)?,
35        ))
36    }
37}
38
39impl core::fmt::Display for InputsCommitment {
40    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
41        write!(f, "{}", prefix_hex::encode(self.0))
42    }
43}
44
45impl core::fmt::Debug for InputsCommitment {
46    fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
47        write!(f, "InputsCommitment({})", self)
48    }
49}