penumbra_sdk_txhash/
effect_hash.rs

1use penumbra_sdk_proto::{penumbra::core::txhash::v1 as pb, DomainType, Message, Name};
2
3/// A hash of a transaction's _effecting data_, describing its effects on the
4/// chain state.
5///
6/// This includes, e.g., the commitments to new output notes created by the
7/// transaction, or nullifiers spent by the transaction, but does not include
8/// _authorizing data_ such as signatures or zk proofs.
9#[derive(Clone, Copy, Eq, PartialEq)]
10pub struct EffectHash(pub [u8; 64]);
11
12/// A helper function to create a BLAKE2b `State` instance given a variable-length personalization string.
13fn create_personalized_state(personalization: &str) -> blake2b_simd::State {
14    let mut state = blake2b_simd::State::new();
15
16    // The `TypeUrl` provided as a personalization string is variable length,
17    // so we first include the length in bytes as a fixed-length prefix.
18    let length = personalization.len() as u64;
19    state.update(&length.to_le_bytes());
20    state.update(personalization.as_bytes());
21
22    state
23}
24
25impl EffectHash {
26    pub fn as_bytes(&self) -> &[u8; 64] {
27        &self.0
28    }
29
30    /// A helper function to hash the data of a proto-encoded message, using
31    /// the variable-length `TypeUrl` of the corresponding domain type as a
32    /// personalization string.
33    pub fn from_proto_effecting_data<M: Message + Name>(message: &M) -> EffectHash {
34        let mut state = create_personalized_state(&M::type_url());
35        state.update(&message.encode_to_vec());
36
37        EffectHash(*state.finalize().as_array())
38    }
39}
40
41impl Default for EffectHash {
42    fn default() -> Self {
43        Self([0u8; 64])
44    }
45}
46
47impl std::fmt::Debug for EffectHash {
48    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
49        f.debug_tuple("EffectHash")
50            .field(&hex::encode(self.0))
51            .finish()
52    }
53}
54
55impl DomainType for EffectHash {
56    type Proto = pb::EffectHash;
57}
58
59impl From<EffectHash> for pb::EffectHash {
60    fn from(msg: EffectHash) -> Self {
61        Self {
62            inner: msg.0.to_vec(),
63        }
64    }
65}
66
67impl TryFrom<pb::EffectHash> for EffectHash {
68    type Error = anyhow::Error;
69    fn try_from(value: pb::EffectHash) -> Result<Self, Self::Error> {
70        Ok(Self(value.inner.try_into().map_err(|_| {
71            anyhow::anyhow!("incorrect length for effect hash")
72        })?))
73    }
74}
75
76impl AsRef<[u8]> for EffectHash {
77    fn as_ref(&self) -> &[u8] {
78        &self.0
79    }
80}