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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Copyright 2023 RISC Zero, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! A Blake2b HashSuite.
use alloc::{boxed::Box, rc::Rc, vec::Vec};
use core::marker::PhantomData;

use blake2::{
    digest::{Update, VariableOutput},
    Blake2bVar,
};
use rand_core::{impls, Error, RngCore};
use risc0_core::field::{
    baby_bear::{BabyBear, BabyBearElem, BabyBearExtElem},
    Elem, ExtElem,
};

use super::{HashFn, HashSuite, Rng, RngFactory};
use crate::core::digest::Digest;

/// Hash function trait.
pub trait Blake2b: Send + Sync {
    /// A function producing a hash from a list of u8.
    fn blake2b<T: AsRef<[u8]>>(data: T) -> [u8; 32];
}

/// Implementation of blake2b using CPU.
pub struct Blake2bCpuImpl;

/// Type alias for Blake2b HashSuite using CPU.
pub type Blake2bCpuHashSuite = Blake2bHashSuite<Blake2bCpuImpl>;

impl Blake2b for Blake2bCpuImpl {
    fn blake2b<T: AsRef<[u8]>>(data: T) -> [u8; 32] {
        let mut result = [0; 32];
        let mut hasher = Blake2bVar::new(32).expect("Initializing Blake2bVar failed");

        hasher.update(data.as_ref());
        hasher
            .finalize_variable(&mut result)
            .expect("Finalizing Blake2bVar failed");
        result
    }
}

struct Blake2bRngFactory<T: Blake2b> {
    phantom: PhantomData<T>,
}

impl<T: Blake2b> Blake2bRngFactory<T> {
    fn new() -> Self {
        Self {
            phantom: PhantomData,
        }
    }
}

impl<T: Blake2b + 'static> RngFactory<BabyBear> for Blake2bRngFactory<T> {
    fn new_rng(&self) -> Box<dyn Rng<BabyBear>> {
        let rng: Blake2bRng<T> = Blake2bRng::new();
        Box::new(rng)
    }
}

/// Blake2b HashSuite.
/// We are using a generic hasher to allow different implementations.
pub struct Blake2bHashSuite<T: Blake2b> {
    phantom: PhantomData<T>,
}

impl<T: Blake2b + 'static> Blake2bHashSuite<T> {
    /// Create a new HashSuite
    pub fn new_suite() -> HashSuite<BabyBear> {
        HashSuite {
            name: "blake2b".into(),
            hashfn: Rc::new(Blake2bHashFn::<T>::new()),
            rng: Rc::new(Blake2bRngFactory::<T>::new()),
        }
    }
}

/// Blake2b HashFn.
struct Blake2bHashFn<T: Blake2b> {
    phantom: PhantomData<T>,
}

impl<T: Blake2b> Blake2bHashFn<T> {
    fn new() -> Self {
        Self {
            phantom: PhantomData,
        }
    }
}

impl<T: Blake2b> HashFn<BabyBear> for Blake2bHashFn<T> {
    fn hash_pair(&self, a: &Digest, b: &Digest) -> Box<Digest> {
        let concat = [a.as_bytes(), b.as_bytes()].concat();
        Box::new(Digest::from(T::blake2b(concat)))
    }

    fn hash_elem_slice(&self, slice: &[BabyBearElem]) -> Box<Digest> {
        let mut data = Vec::<u8>::new();
        for el in slice {
            data.extend_from_slice(el.as_u32_montgomery().to_be_bytes().as_slice());
        }
        Box::new(Digest::from(T::blake2b(data)))
    }

    fn hash_ext_elem_slice(&self, slice: &[BabyBearExtElem]) -> Box<Digest> {
        let mut data = Vec::<u8>::new();
        for ext_el in slice {
            for el in ext_el.subelems() {
                data.extend_from_slice(el.as_u32_montgomery().to_be_bytes().as_slice());
            }
        }
        Box::new(Digest::from(T::blake2b(data)))
    }
}

/// Blake2b-based random number generator.
pub struct Blake2bRng<T: Blake2b> {
    current: [u8; 32],
    hasher: PhantomData<T>,
}

impl<T: Blake2b> Blake2bRng<T> {
    fn new() -> Self {
        Self {
            current: [0; 32],
            hasher: Default::default(),
        }
    }
}

impl<T: Blake2b> Rng<BabyBear> for Blake2bRng<T> {
    fn mix(&mut self, val: &Digest) {
        let concat = [self.current.as_ref(), val.as_bytes()].concat();
        self.current = T::blake2b(concat);
    }

    fn random_bits(&mut self, bits: usize) -> u32 {
        ((1 << bits) - 1) & self.next_u32()
    }

    fn random_elem(&mut self) -> BabyBearElem {
        BabyBearElem::random(self)
    }

    fn random_ext_elem(&mut self) -> BabyBearExtElem {
        BabyBearExtElem::random(self)
    }
}

impl<T: Blake2b> RngCore for Blake2bRng<T> {
    fn next_u32(&mut self) -> u32 {
        let next = T::blake2b(self.current);
        self.current = next;
        ((next[0] as u32) << 24)
            + ((next[1] as u32) << 16)
            + ((next[2] as u32) << 8)
            + (next[3] as u32)
    }

    fn next_u64(&mut self) -> u64 {
        impls::next_u64_via_u32(self)
    }

    fn fill_bytes(&mut self, dest: &mut [u8]) {
        impls::fill_bytes_via_next(self, dest);
    }

    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
        self.fill_bytes(dest);
        Ok(())
    }
}