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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
// Copyright 2024 Ulvetanna Inc.

use super::{
	common::{
		calculate_fold_chunk_start_rounds, calculate_fold_commit_rounds, calculate_folding_arities,
		FinalMessage,
	},
	error::Error,
};
use crate::{
	linear_code::{LinearCode, LinearCodeWithExtensionEncoding},
	merkle_tree::VectorCommitScheme,
	protocols::fri::common::{fold_chunk, QueryProof, QueryRoundProof},
	reed_solomon::reed_solomon::ReedSolomonCode,
};
use binius_field::{BinaryField, ExtensionField, PackedExtension, PackedFieldIndexable};
use binius_ntt::AdditiveNTT;
use binius_utils::bail;
use itertools::izip;
use rayon::prelude::*;
use tracing::instrument;

fn fold_codeword<F, FS>(
	rs_code: &ReedSolomonCode<FS>,
	codeword: &[F],
	round: usize,
	folding_challenges: &[F],
) -> Vec<F>
where
	F: BinaryField + ExtensionField<FS>,
	FS: BinaryField,
{
	// Preconditions
	assert!(codeword.len() % (1 << folding_challenges.len()) == 0);
	assert!(round + 1 >= folding_challenges.len());
	assert!(round < rs_code.log_dim());
	assert!(!folding_challenges.is_empty());

	let start_round = round + 1 - folding_challenges.len();
	let chunk_size = 1 << folding_challenges.len();

	// For each chunk of size 2^folding_challenges.len() in the codeword, fold it with the folding challenges
	codeword
		.par_chunks(chunk_size)
		.enumerate()
		.map_init(
			|| vec![F::default(); chunk_size],
			|scratch_buffer, (chunk_index, chunk)| {
				fold_chunk(
					rs_code,
					start_round,
					chunk_index,
					chunk,
					folding_challenges,
					scratch_buffer,
				)
			},
		)
		.collect()
}

#[derive(Debug)]
pub struct CommitOutput<P, VCSCommitment, VCSCommitted> {
	pub commitment: VCSCommitment,
	pub committed: VCSCommitted,
	pub codeword: Vec<P>,
}

/// Encodes and commits the input message.
pub fn commit_message<F, FA, P, PA, VCS>(
	rs_code: &ReedSolomonCode<PA>,
	vcs: &VCS,
	message: &[P],
) -> Result<CommitOutput<P, VCS::Commitment, VCS::Committed>, Error>
where
	F: BinaryField + ExtensionField<FA>,
	FA: BinaryField,
	P: PackedFieldIndexable<Scalar = F> + PackedExtension<FA, PackedSubfield = PA>,
	PA: PackedFieldIndexable<Scalar = FA>,
	VCS: VectorCommitScheme<F>,
{
	if message.len() * P::WIDTH != rs_code.dim() {
		bail!(Error::InvalidArgs("message length does not match code dimension".to_string()));
	}
	if vcs.vector_len() != rs_code.len() {
		bail!(Error::InvalidArgs("code length does not vector commitment length".to_string(),));
	}

	let mut encoded = vec![P::zero(); message.len() << rs_code.log_inv_rate()];
	encoded[..message.len()].copy_from_slice(message);
	rs_code.encode_extension_inplace(&mut encoded)?;

	let (commitment, vcs_committed) = vcs
		.commit_batch(&[P::unpack_scalars(&encoded)])
		.map_err(|err| Error::VectorCommit(Box::new(err)))?;

	Ok(CommitOutput {
		commitment,
		committed: vcs_committed,
		codeword: encoded,
	})
}

pub enum FoldRoundOutput<VCSCommitment> {
	NoCommitment,
	Commitment(VCSCommitment),
}

/// A stateful prover for the FRI fold phase.
pub struct FRIFolder<'a, F, FA, VCS>
where
	FA: BinaryField,
	F: BinaryField,
	VCS: VectorCommitScheme<F>,
{
	committed_rs_code: &'a ReedSolomonCode<FA>,
	final_rs_code: &'a ReedSolomonCode<F>,
	codeword: &'a [F],
	codeword_vcs: &'a VCS,
	round_vcss: &'a [VCS],
	codeword_committed: &'a VCS::Committed,
	round_committed: Vec<(Vec<F>, VCS::Committed)>,
	curr_round: usize,
	unprocessed_challenges: Vec<F>,
	commitment_fold_rounds: Vec<usize>,
}

impl<'a, F, FA, VCS> FRIFolder<'a, F, FA, VCS>
where
	F: BinaryField + ExtensionField<FA>,
	FA: BinaryField,
	VCS: VectorCommitScheme<F> + Sync,
	VCS::Committed: Send + Sync,
{
	/// Constructs a new folder.
	pub fn new(
		committed_rs_code: &'a ReedSolomonCode<FA>,
		final_rs_code: &'a ReedSolomonCode<F>,
		committed_codeword: &'a [F],
		committed_codeword_vcs: &'a VCS,
		round_vcss: &'a [VCS],
		committed: &'a VCS::Committed,
	) -> Result<Self, Error> {
		if committed_rs_code.len() != committed_codeword.len() {
			bail!(Error::InvalidArgs(
				"Reed–Solomon code length must match codeword length".to_string(),
			));
		}

		let commitment_fold_rounds = calculate_fold_commit_rounds(
			committed_rs_code,
			final_rs_code,
			committed_codeword_vcs,
			round_vcss,
		)?;

		Ok(Self {
			committed_rs_code,
			codeword: committed_codeword,
			codeword_vcs: committed_codeword_vcs,
			round_vcss,
			codeword_committed: committed,
			round_committed: Vec::with_capacity(round_vcss.len()),
			curr_round: 0,
			unprocessed_challenges: Vec::with_capacity(committed_rs_code.log_dim()),
			commitment_fold_rounds,
			final_rs_code,
		})
	}

	/// Number of fold rounds, including the final fold.
	pub fn n_rounds(&self) -> usize {
		self.committed_rs_code.log_dim()
	}

	/// Number of times `execute_fold_round` has been called
	pub fn curr_round(&self) -> usize {
		self.curr_round
	}

	fn prev_codeword(&self) -> &[F] {
		self.round_committed
			.last()
			.map(|(codeword, _)| codeword.as_slice())
			.unwrap_or(self.codeword)
	}

	fn is_commitment_round(&self) -> bool {
		let n_commitments = self.round_committed.len();
		n_commitments < self.round_vcss.len()
			&& self.commitment_fold_rounds[n_commitments] == self.curr_round
	}

	/// Executes the next fold round and returns the folded codeword commitment.
	///
	/// As a memory efficient optimization, this method may not actually do the folding, but instead accumulate the
	/// folding challenge for processing at a later time. This saves us from storing intermediate folded codewords.
	#[instrument(skip_all, name = "fri::FRIFolder::execute_fold_round")]
	pub fn execute_fold_round(
		&mut self,
		challenge: F,
	) -> Result<FoldRoundOutput<VCS::Commitment>, Error> {
		self.unprocessed_challenges.push(challenge);
		if !self.is_commitment_round() {
			self.curr_round += 1;
			return Ok(FoldRoundOutput::NoCommitment);
		}

		// Fold the last codeword with the accumulated folding challenges.
		let folded_codeword = fold_codeword(
			self.committed_rs_code,
			self.prev_codeword(),
			self.curr_round,
			&self.unprocessed_challenges,
		);
		self.unprocessed_challenges.clear();

		let round_vcs = self
			.round_vcss
			.get(self.round_committed.len())
			.ok_or_else(|| Error::TooManyFoldExecutions {
				max_folds: self.round_vcss.len() - 1,
			})?;

		let (commitment, committed) = round_vcs
			.commit_batch(&[&folded_codeword])
			.map_err(|err| Error::VectorCommit(Box::new(err)))?;
		self.round_committed.push((folded_codeword, committed));

		self.curr_round += 1;
		Ok(FoldRoundOutput::Commitment(commitment))
	}

	/// Finalizes the FRI folding process.
	///
	/// This step will process any unprocessed folding challenges to produce the
	/// final folded codeword. Then it will decode this final folded codeword
	/// to get the final message. The result is the final message and a query prover instance.
	///
	/// This returns the final message and a query prover instance.
	#[instrument(skip_all, name = "fri::FRIFolder::finalize")]
	pub fn finalize(mut self) -> Result<(FinalMessage<F>, FRIQueryProver<'a, F, VCS>), Error> {
		if self.curr_round != self.n_rounds() {
			bail!(Error::EarlyProverFinish);
		}

		// NB: The idea behind the following is that we should do the minimal amount of work necessary to
		// get the final message. Specifically, we do not need a final codeword with rate lower than 1.
		let mut final_codeword = if self.unprocessed_challenges.is_empty() {
			// In this case, final_codeword is interpreted as taking a prefix of the previous codeword and claiming
			// this is a codeword for an RS code with rate 1 and dimension FINAL_MESSAGE_DIM.
			self.prev_codeword()[..1 << self.final_rs_code.log_dim()].to_vec()
		} else {
			// In this case, unfolded_codeword is interpreted as taking a prefix of the previous codeword and claiming
			// this is a codeword for an RS code with dimension FINAL_MESSAGE_DIM + unprocessed_challenges.len()
			// and rate 1.
			let unfolded_codeword_len =
				1 << (self.unprocessed_challenges.len() + self.final_rs_code.log_dim());
			let unfolded_codeword = &self.prev_codeword()[..unfolded_codeword_len];
			// We then fold this codeword with the unprocessed challenges to get a final codeword
			// for an RS code with rate 1 and dimension FINAL_MESSAGE_DIM.
			fold_codeword(
				self.committed_rs_code,
				unfolded_codeword,
				self.curr_round - 1,
				&self.unprocessed_challenges,
			)
		};

		// We decode this final codeword to get the final message.
		self.final_rs_code
			.get_ntt()
			.inverse_transform(&mut final_codeword, 0, 0)?;
		let final_message = final_codeword;

		self.unprocessed_challenges.clear();

		let Self {
			codeword,
			codeword_vcs,
			round_vcss,
			codeword_committed,
			round_committed,
			commitment_fold_rounds,
			committed_rs_code,
			..
		} = self;

		let query_prover = FRIQueryProver {
			codeword,
			codeword_vcs,
			round_vcss,
			codeword_committed,
			round_committed,
			commitment_fold_rounds,
			n_fold_rounds: committed_rs_code.log_dim(),
		};
		Ok((final_message, query_prover))
	}
}

/// A prover for the FRI query phase.
pub struct FRIQueryProver<'a, F: BinaryField, VCS: VectorCommitScheme<F>> {
	codeword: &'a [F],
	codeword_vcs: &'a VCS,
	round_vcss: &'a [VCS],
	codeword_committed: &'a VCS::Committed,
	round_committed: Vec<(Vec<F>, VCS::Committed)>,
	commitment_fold_rounds: Vec<usize>,
	n_fold_rounds: usize,
}

impl<'a, F: BinaryField, VCS: VectorCommitScheme<F>> FRIQueryProver<'a, F, VCS> {
	/// Number of fold rounds, including the final fold.
	pub fn n_rounds(&self) -> usize {
		self.round_vcss.len() + 1
	}

	/// Proves a FRI challenge query.
	///
	/// ## Arguments
	///
	/// * `index` - an index into the original codeword domain
	#[instrument(skip_all, name = "fri::FRIQueryProver::prove_query")]
	pub fn prove_query(&self, index: usize) -> Result<QueryProof<F, VCS::Proof>, Error> {
		let mut round_proofs = Vec::with_capacity(self.n_rounds());
		let fold_chunk_start_rounds =
			calculate_fold_chunk_start_rounds(&self.commitment_fold_rounds);
		let folding_arities =
			calculate_folding_arities(self.n_fold_rounds, &fold_chunk_start_rounds);

		let mut coset_index = index >> folding_arities[0];
		round_proofs.push(prove_coset_opening(
			self.codeword_vcs,
			self.codeword,
			self.codeword_committed,
			coset_index,
			folding_arities[0],
		)?);

		for (query_rd, vcs, (codeword, committed)) in
			izip!((1..=self.round_vcss.len()), self.round_vcss.iter(), self.round_committed.iter())
		{
			coset_index >>= folding_arities[query_rd];
			round_proofs.push(prove_coset_opening(
				vcs,
				codeword,
				committed,
				coset_index,
				folding_arities[query_rd],
			)?);
		}

		Ok(round_proofs)
	}
}

fn prove_coset_opening<F: BinaryField, VCS: VectorCommitScheme<F>>(
	vcs: &VCS,
	codeword: &[F],
	committed: &VCS::Committed,
	coset_index: usize,
	log_coset_size: usize,
) -> Result<QueryRoundProof<F, VCS::Proof>, Error> {
	let start_index = coset_index << log_coset_size;

	let range = start_index..start_index + (1 << log_coset_size);

	let vcs_proof = vcs
		.prove_range_batch_opening(committed, range.clone())
		.map_err(|err| Error::VectorCommit(Box::new(err)))?;

	Ok(QueryRoundProof {
		values: codeword[range].to_vec(),
		vcs_proof,
	})
}