tasm_lib/hashing/
hash_from_stack.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use triton_vm::prelude::*;
use twenty_first::prelude::*;

use crate::prelude::*;

#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct HashFromStack {
    ty: DataType,
    ty_len: usize,
}

impl HashFromStack {
    /// # Panics
    ///
    /// Panics if the argument does not have statically-known length, or if that
    /// length is larger than or equal to [`Tip5::RATE`].
    pub fn new(ty: DataType) -> Self {
        let ty_len = ty
            .static_length()
            .expect("data type to hash should have static length");
        assert!(ty_len < Tip5::RATE, "type length should be small");

        Self { ty, ty_len }
    }
}

impl BasicSnippet for HashFromStack {
    fn inputs(&self) -> Vec<(DataType, String)> {
        vec![(self.ty.clone(), "preimage".to_string())]
    }
    fn outputs(&self) -> Vec<(DataType, String)> {
        vec![(DataType::Digest, "digest".to_string())]
    }

    fn entrypoint(&self) -> String {
        format!(
            "tasmlib_hashing_hash_from_stack___{}",
            self.ty.label_friendly_name()
        )
    }

    fn code(&self, _: &mut Library) -> Vec<LabelledInstruction> {
        let pad_single_zero = triton_asm!(
            push 0
            place {self.ty_len}
        );

        let num_zeros_in_pad = Tip5::RATE - self.ty_len - 1;
        let pad_zeros = vec![pad_single_zero; num_zeros_in_pad].concat();

        let entrypoint = self.entrypoint();
        triton_asm!(
            {entrypoint}:

                {&pad_zeros}
                // _ [0, …, 0] [preimage]

                push 1
                place {self.ty_len}
                // _ [0, …, 0] 1 [preimage]
                // _ [padded-preimage]

                sponge_init
                sponge_absorb
                sponge_squeeze

                pick 9
                pick 9
                pick 9
                pick 9
                pick 9
                pop 5

                return
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_prelude::*;

    impl Closure for HashFromStack {
        type Args = Vec<BFieldElement>;

        fn rust_shadow(&self, stack: &mut Vec<BFieldElement>) {
            let mut preimage = vec![];
            for _ in 0..self.ty_len {
                preimage.push(stack.pop().unwrap());
            }

            push_encodable(stack, &Tip5::hash_varlen(&preimage));
        }

        fn pseudorandom_args(&self, seed: [u8; 32], _: Option<BenchmarkCase>) -> Self::Args {
            self.ty.seeded_random_element(&mut StdRng::from_seed(seed))
        }

        fn set_up_test_stack(&self, args: Self::Args) -> Vec<BFieldElement> {
            let mut stack = self.init_stack_for_isolated_run();
            stack.extend(args.into_iter().rev());

            stack
        }
    }

    #[test]
    fn unit() {
        let types = [
            DataType::Bool,
            DataType::U32,
            DataType::U64,
            DataType::U128,
            DataType::Bfe,
            DataType::Xfe,
            DataType::Digest,
        ];
        for data_type in types {
            ShadowedClosure::new(HashFromStack::new(data_type)).test();
        }
    }
}

#[cfg(test)]
mod benches {
    use super::*;
    use crate::test_prelude::*;

    #[test]
    fn benchmark() {
        let types = [DataType::Bfe, DataType::Digest];
        for data_type in types {
            ShadowedClosure::new(HashFromStack::new(data_type)).bench();
        }
    }
}