binius_core/fiat_shamir/
hasher_challenger.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
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
// Copyright 2024 Irreducible Inc.

use super::Challenger;
use bytes::{buf::UninitSlice, Buf, BufMut};
use digest::{
	core_api::{Block, BlockSizeUser},
	Digest, FixedOutputReset, Output,
};
use std::{cmp::min, mem};

/// Challenger type which implements `[Buf]` that has similar functionality as `[CanSample]`
#[derive(Debug, Default)]
pub struct HasherSampler<H: Digest> {
	index: usize,
	buffer: Output<H>,
	hasher: H,
}

/// Challenger type which implements `[BufMut]` that has similar functionality as `[CanObserve]`
#[derive(Debug, Default)]
pub struct HasherObserver<H: Digest + BlockSizeUser> {
	index: usize,
	buffer: Block<H>,
	hasher: H,
}

/// Challenger interface over hashes that implement `[Digest]` trait,
///
/// This challenger works over bytes instead of Field elements
#[derive(Debug)]
pub enum HasherChallenger<H: Digest + BlockSizeUser> {
	Observer(HasherObserver<H>),
	Sampler(HasherSampler<H>),
}

impl<H> Default for HasherChallenger<H>
where
	H: Digest + BlockSizeUser,
{
	fn default() -> Self {
		Self::Observer(HasherObserver {
			hasher: H::new(),
			index: 0,
			buffer: Block::<H>::default(),
		})
	}
}

impl<H: Digest + BlockSizeUser + FixedOutputReset + Default> Challenger for HasherChallenger<H> {
	/// This returns the inner challenger which implements `[BufMut]`
	fn observer(&mut self) -> &mut impl BufMut {
		match self {
			Self::Observer(observer) => observer,
			Self::Sampler(sampler) => {
				*self = Self::Observer(mem::take(sampler).into_observer());
				match self {
					Self::Observer(observer) => observer,
					_ => unreachable!(),
				}
			}
		}
	}

	/// This returns the inner challenger which implements `[Buf]`
	fn sampler(&mut self) -> &mut impl Buf {
		match self {
			Self::Sampler(sampler) => sampler,
			Self::Observer(observer) => {
				*self = Self::Sampler(mem::take(observer).into_sampler());
				match self {
					Self::Sampler(sampler) => sampler,
					_ => unreachable!(),
				}
			}
		}
	}
}

impl<H> HasherSampler<H>
where
	H: Digest + Default + BlockSizeUser,
{
	fn into_observer(mut self) -> HasherObserver<H> {
		Digest::update(&mut self.hasher, self.index.to_le_bytes());

		HasherObserver {
			hasher: self.hasher,
			index: 0,
			buffer: Block::<H>::default(),
		}
	}
}

impl<H> HasherSampler<H>
where
	H: Digest + FixedOutputReset,
{
	fn fill_buffer(&mut self) {
		let digest = self.hasher.finalize_reset();

		// feed forward to the empty state
		Digest::update(&mut self.hasher, &digest);

		self.buffer = digest;
		self.index = 0
	}
}

impl<H> HasherObserver<H>
where
	H: Digest + BlockSizeUser + Default,
{
	fn into_sampler(mut self) -> HasherSampler<H> {
		self.flush();
		HasherSampler {
			hasher: self.hasher,
			index: <H as Digest>::output_size(),
			buffer: Output::<H>::default(),
		}
	}
}

impl<H> HasherObserver<H>
where
	H: Digest + BlockSizeUser,
{
	fn flush(&mut self) {
		self.hasher.update(&self.buffer[..self.index]);
		self.index = 0
	}
}

impl<H> Buf for HasherSampler<H>
where
	H: Digest + FixedOutputReset + Default,
{
	fn remaining(&self) -> usize {
		usize::MAX
	}

	fn chunk(&self) -> &[u8] {
		&self.buffer[self.index..]
	}

	fn advance(&mut self, mut cnt: usize) {
		if self.index == <H as Digest>::output_size() {
			self.fill_buffer();
		}

		while cnt > 0 {
			let remaining = min(<H as Digest>::output_size() - self.index, cnt);
			if remaining == 0 {
				self.fill_buffer();
				continue;
			}
			cnt -= remaining;
			self.index += remaining;
		}
	}
}

unsafe impl<H> BufMut for HasherObserver<H>
where
	H: Digest + BlockSizeUser,
{
	fn remaining_mut(&self) -> usize {
		usize::MAX
	}

	unsafe fn advance_mut(&mut self, mut cnt: usize) {
		if self.index == <H as BlockSizeUser>::block_size() {
			self.flush();
		}

		while cnt > 0 {
			let remaining = min(<H as BlockSizeUser>::block_size() - self.index, cnt);
			cnt -= remaining;
			self.index += remaining;
			if remaining == <H as BlockSizeUser>::block_size() {
				self.flush();
			}
		}
	}

	fn chunk_mut(&mut self) -> &mut UninitSlice {
		let buffer = &mut self.buffer[self.index..];
		buffer.into()
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use groestl_crypto::Groestl256;
	use rand::{thread_rng, RngCore};

	#[test]
	fn test_starting_sampler() {
		let mut hasher = Groestl256::default();
		let mut challenger = HasherChallenger::<Groestl256>::default();
		let mut out = [0u8; 8];
		challenger.sampler().copy_to_slice(&mut out);

		let first_hash_out = hasher.finalize_reset();
		hasher.update(first_hash_out);

		assert_eq!(first_hash_out[0..8], out);

		let mut out = [0u8; 24];
		challenger.sampler().copy_to_slice(&mut out);
		assert_eq!(first_hash_out[8..], out);

		challenger.observer().put_slice(&[0x48, 0x55]);
		hasher.update([32, 0, 0, 0, 0, 0, 0, 0]);
		hasher.update([0x48, 0x55]);

		let mut out_after_observe = [0u8; 2];
		challenger.sampler().copy_to_slice(&mut out_after_observe);

		let second_hash_out = hasher.finalize_reset();

		assert_eq!(out_after_observe, second_hash_out[..2]);
	}

	#[test]
	fn test_starting_observer() {
		let mut hasher = Groestl256::default();
		let mut challenger = HasherChallenger::<Groestl256>::default();
		let mut observable = [0u8; 1019];
		thread_rng().fill_bytes(&mut observable);
		challenger.observer().put_slice(&observable[..39]);
		challenger.observer().put_slice(&observable[39..300]);
		challenger.observer().put_slice(&observable[300..987]);
		challenger.observer().put_slice(&observable[987..]);
		hasher.update(observable);

		let mut out = [0u8; 7];
		challenger.sampler().copy_to_slice(&mut out);

		let first_hash_out = hasher.finalize_reset();
		hasher.update(first_hash_out);

		assert_eq!(first_hash_out[..7], out);

		thread_rng().fill_bytes(&mut observable);
		challenger.observer().put_slice(&observable[..128]);
		// updated with index of sampler first
		hasher.update([7, 0, 0, 0, 0, 0, 0, 0]);

		hasher.update(&observable[..128]);

		let mut out = [0u8; 32];
		challenger.sampler().copy_to_slice(&mut out);

		let second_hasher_out = hasher.finalize_reset();
		hasher.update(second_hasher_out);

		assert_eq!(second_hasher_out[..], out);

		challenger.observer().put_slice(&observable[128..]);
		hasher.update([32, 0, 0, 0, 0, 0, 0, 0]);
		hasher.update(&observable[128..]);

		let mut out_again = [0u8; 7];
		challenger.sampler().copy_to_slice(&mut out_again);

		let final_hasher_out = hasher.finalize_reset();
		assert_eq!(final_hasher_out[..7], out_again);
	}
}