bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 44쪽
ree_bound(&self) -> u32 {
self.log_size + LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR
}
fn evaluate<E: EvalAtRow>(&self, mut eval: E) -> E {
let random_col = eval.next_trace_mask();
let ordered_col = eval.next_trace_mask();
eval.add_to_relation(RelationEntry::new(
&self.lookup_elements,
E::EF::one(),
&[random_col],
));
eval.add_to_relation(RelationEntry::new(
&self.lookup_elements,
-E::EF::one(),
&[ordered_col],
));
eval.finalize_logup_in_pairs();
eval
}
}
```
The `TestEval` struct is also very similar to the one in the previous section. The only difference is that we call `add_to_relation` twice and add them together by calling `finalize_logup_in_pairs()` on the `TestEval` instance. This is equivalent to calling the `finalize_logup_batched` function with `&vec![0, 0]`.
# Introduction
Source: https://docs.starknet.io/learn/S-two-book/air-development/index
> This section is intended for developers who want to create custom proofs using S-two (proofs of custom VMs, ML inference, etc.). It assumes that the reader is familiar with Rust and has some background knowledge of cryptography (e.g. finite fields). It also assumes that the reader is familiar with the concept of proof systems and knows what they want to create proofs for, but it does not assume any prior experience with creating them.
<Note>
All the code that appears throughout this section is available [here](https://github.com/starknet-io/starknet-docs/tree/main/learn/S-two-book/stwo-examples/examples).
</Note>
# Local Row Constraints
Source: https://docs.starknet.io/learn/S-two-book/air-development/local-row-constraints/index
Until now, we have only considered constraints that apply over values in a single row. But what if we want to express constraints over multiple adjacent rows? For example, we may want to ensure that the difference between the values in two adjacent rows is always the same.
Turns out we can implement this as an AIR constraint, as long as the same constraints are applied to all rows. We will build upon the example in the previous section, where we created two columns and proved that they are permutations of each other by asserting that the second column looks up all values in the first column exactly once.
Here, we will create two columns and prove that not only are they permutations of each other, but also that the second column is a sorted version of the first column. Since the sorted column will contain in order the values $[0,num\_rows)$, this is equivalent to asserting that **the difference between every current row and the previous row is $1$**.
We will implement this in three iterations, fixing a different issue in each iteration.
## First Try
```rust theme={null}
fn evaluate<E: EvalAtRow>(&self, mut eval: E) -> E {
let unsorted_col = eval.next_trace_mask();
let [sorted_col_prev_row, sorted_col_curr_row] =
eval.next_interaction_mask(ORIGINAL_TRACE_IDX, [-1, 0]);
// New constraint
eval.add_constraint(
E::F::one() - (sorted_col_curr_row.clone() - sorted_col_prev_row.clone()),
);
eval.add_to_relation(RelationEntry::new(
&self.lookup_elements,
E::EF::one(),
&[unsorted_col],
));
eval.add_to_relation(RelationEntry::new(
&self.lookup_elements,
-E::EF::one(),
&[sorted_col_curr_row],
));
eval.finalize_logup_in_pairs();
eval
}
```
The logic for creating the trace and LogUp columns is basically the same as in the previous section (except that one of the columns is now sorted), so we omit them for brevity.
Another change is in the `evaluate` function, where we call `eval.next_interaction_mask(ORIGINAL_TRACE_IDX, [-1, 0])` instead of `eval.next_trace_mask()`. The function `next_trace_mask()` is a wrapper for `next_interaction_mask(ORIGINAL_TRACE_IDX, [0])`, where the first parameter specifies which part of the trace to retrieve values from (see [this figure](../static-lookups/index#figure-1) for an example of the different parts of a trace). Since we want to retrieve values from the original trace, we set the value of the first parameter to `ORIGINAL_TRACE_IDX`. Next, the second parameter indicates the row offset of the value we want to retrieve. Since we want to retrieve both the previous and current row values for the sorted column, we set the value of the second parameter to `[-1, 0]`.
Once we have these values, we can now assert that the difference between the current and previous row is always one with the constraint: `E::F::one() - (sorted_col_curr_row.clone() - sorted_col_prev_row.clone())`.
<Danger>
But this will fail with a `ConstraintsNotSatisfied` error, can you see why? (You can try running it yourself [here](https://github.com/starknet-io/starknet-docs/blob/main/learn/S-two-book/stwo-examples/examples/local_row_constraints_fails_1.rs))
</Danger>
## Second Try
The issue was that when calling `evaluate` on the first row of our trace, the previous row value wraps around to the last row because there are no negative indices.
This means that in our example, we are expecting the `0 - 15 = 1` constraint to hold, which is clearly not true.
To fix this, we can use the `IsFirstColumn` preprocessed column that we created in the [Preprocessed Trace](../preprocessed-trace/index) section. So we will copy over the same code for creating the preprocessed column and modify our new constraint as follows:
```rust theme={null}
let is_first_col = eval.get_preprocessed_column(self.is_first_id.clone());
eval.add_constraint(
(E::F::one() - is_first_col.clone())
* (E::F::one() - (sorted_col_curr_row.clone() - sorted_col_prev_row.clone())),
);
```
Now, we have a constraint that is disabled for the first row, which is exactly what we want.
<Danger>
Still, however, this will fail with the same `ConstraintsNotSatisfied` error. (You can run it [here](https://github.com/starknet-io/starknet-docs/blob/main/learn/S-two-book/stwo-examples/examples/local_row_constraints_fails_2.rs))
</Danger>
## Third Try
So when we were creating `CircleEvaluation` instances from our `BaseColumn` instances, the order of the elements that we were creating it with was actually not the order that S-two understands it to be. Instead, it assumes that the values are in the bit-reversed, circle domain order. It's not important to understand what this order is, specifically, but this does mean that when S-two tries to find the `-1` offset when calling `evaluate`, it will find the previous value assuming that it's in a different order. This means that when we create a `CircleEvaluation` instance, we need to convert it to a bit-reversed circle domain order.
Thus, every time we create a `CircleEvaluation` instance, we need to convert the order of the values in the `BaseColumn` beforehand.
```rust theme={null}
impl IsFirstColumn {
...
impl IsFirstColumn {
...
}
fn gen_trace(log_size: u32) -> Vec<CircleEvaluation<SimdBackend, M31, BitReversedOrder>> {
// Create a table with random values
let mut rng = rand::thread_rng();
let sorted_values = (0..(1 << log_size)).map(|i| i).collect::<Vec<_>>();
let mut unsorted_values = sorted_values.clone();
unsorted_values.shuffle(&mut rng);
let mut unsorted_col = BaseColumn::from_iter(unsorted_values.iter().map(|v| M31::from(*v)));
let mut sorted_col = BaseColumn::from_iter(sorted_values.iter().map(|v| M31::from(*v)));
// Convert table to trace polynomials
let domain = CanonicCoset::new(log_size).circle_domain();
////////////////////////////////////////////////////////////////////
// Convert the columns to bit-reversed circle domain order
bit_reverse_coset_to_circle_domain_order(unsorted_col.as_mut_slice());
bit_reverse_coset_to_circle_domain_order(sorted_col.as_mut_slice());
////////////////////////////////////////////////////////////////////
vec![unsorted_col, sorted_col]
.into_iter()
.map(|col| CircleEvaluation::new(domain, col))
.collect()
}
```
Voilà, we have successfully implemented the constraint. You can run it [here](https://github.com/starknet-io/starknet-docs/blob/main/learn/S-two-book/stwo-examples/examples/local_row_constraints.rs).
<Tip>
Things to consider when implementing constraints over multiple rows:
1. Change the order of elements in `BaseColumn` in-place via `bit_reverse_coset_to_circle_domain_order` before creating a `CircleEvaluation` instance. This is required because S-two assumes that the values are in the bit-reversed, circle domain order.
2. For the first row, the 'previous' row is the last row of the trace, so you may need to disable the constraint for the first row. This is typically done by using a preprocessed column.
</Tip>
# Preprocessed Trace
Source: https://docs.starknet.io/learn/S-two-book/air-development/preprocessed-trace/index
> This section and the following sections are intended for developers who have completed the [First Breath of AIR](../writing-a-simple-air/index) section or are already familiar with the workflow of creating an AIR. If you have not gone through the previous section, we recommend doing so first as the following sections gloss over a lot of boilerplate code.
For those of you who have completed the [First Breath of AIR](../writing-a-simple-air/index) tutorial, you should now be familiar with the concept of a trace as a table of integers that are filled in by the prover (we will now refer to this as the **original trace**).
In addition to the original trace, S-two also has a concept of a **preprocessed trace**, which is a table whose values are fixed and therefore cannot be arbitrarily chosen by the prover. In other words, these are columns whose values are known in advance of creating a proof and essentially agreed upon by both the prover and the verifier.
One of the use cases of the preprocessed trace is as *a selector for different constraints*. Remember that in an AIR, the same constraints are applied to every row of the trace? If we go back to the spreadsheet analogy, this means that we can't create a spreadsheet that runs different computations for different rows. To get around this, note that if we multiply a constraint with a "selector" that is zero, the constraint will be trivially satisfied. Building on this, we can create a selector column of 0s and 1s, and multiply the constraint with the selector column. For example, let's say we want to create a constraint that runs different computations for the first 2 rows and the next 2 rows. We can do this by creating a selector column that has value 0 for the first 2 rows and 1 for the next 2 rows and combining it with the constraints as follows:
$$
(1 - \text{selector}) \cdot \text{constraint}_1 + \text{selector} \cdot \text{constraint}_2 = 0
$$
<div>
<img alt="" />
*Figure 1: Preprocessed trace as a selector*
</div>
Another use case is to use the preprocessed trace to *express constant values used in constraints*. For example, when creating a hash function in an AIR, we often need to use round constants, which the verifier needs to be able to verify or the resulting hash may be invalid. We can also "look up" the constant values as an optimization technique, which we will discuss in more detail in the next section.
In this section, we will explore how to implement a preprocessed trace as a selector, and we will implement the simplest form: a single `IsFirst` column, where the value is 1 for the first row and 0 for all other rows.
<Note>
Boilerplate code is omitted for brevity. Please refer to the [full example code](https://github.com/starknet-io/starknet-docs/blob/main/learn/S-two-book/stwo-examples/examples/preprocessed_trace.rs) for the full implementation.
</Note>
```rust theme={null}
struct IsFirstColumn {
pub log_size: u32,
}
#[allow(dead_code)]
impl IsFirstColumn {
pub fn new(log_size: u32) -> Self {
Self { log_size }
}
pub fn gen_column(&self) -> CircleEvaluation<SimdBackend, M31, BitReversedOrder> {
let mut col = BaseColumn::zeros(1 << self.log_size);
col.set(0, M31::from(1));
CircleEvaluation::new(CanonicCoset::new(self.log_size).circle_domain(), col)
}
pub fn id(&self) -> PreProcessedColumnId {
PreProcessedColumnId {
id: format!("is_first_{}", self.log_size),
}
}
}
```
First, we need to define an `IsFirstColumn` struct that will be used as a preprocessed trace. We will use the `gen_column()` function to generate a `CircleEvaluation` struct that is 1 for the first row and 0 for all other rows. The `id()` function is needed to identify this column when evaluating the constraints.
```rust theme={null}
fn main() {
...
// Create and commit to the preprocessed trace
let is_first_column = IsFirstColumn::new(log_size);
let mut tree_builder = commitment_scheme.tree_builder();
tree_builder.extend_evals(vec![is_first_column.gen_column()]);
tree_builder.commit(channel);
// Commit to the size of the trace
channel.mix_u64(log_size as u64);
// Create and commit to the original trace
let trace = gen_trace(log_size);
let mut tree_builder = commitment_scheme.tree_builder();
tree_builder.extend_evals(trace);
tree_builder.commit(channel);
...
}
```
Then, in our main function, we will create and commit to the preprocessed and original traces. For those of you who are curious about why we need to commit to the trace, please refer to the [Committing to the Trace Polynomials](../writing-a-simple-air/committing-to-the-trace-polynomials) section.
```rust theme={null}
struct TestEval {
is_first_id: PreProcessedColumnId,
log_size: u32,
}
impl FrameworkEval for TestEval {
fn log_size(&self) -> u32 {
self.log_size
}
fn max_constraint_log_degree_bound(&self) -> u32 {
self.log_size + LOG_CONSTRAINT_EVAL_BLOWUP_FACTOR
}
fn evaluate<E: EvalAtRow>(&self, mut eval: E) -> E {
let is_first = eval.get_preprocessed_column(self.is_first_id.clone());
let col_1 = eval.next_trace_mask();
let col_2 = eval.next_trace_mask();
let col_3 = eval.next_trace_mask();
// If is_first is 1, then the constraint is col_1 * col_2 - col_3 = 0
// If is_first is 0, then the constraint is col_1 * col_2 + col_1 - col_3 = 0
eval.add_constraint(
is_first.clone() * (col_1.clone() * col_2.clone() - col_3.clone())
+ (E::F::from(M31::from(1)) - is_first.clone())
* (col_1.clone() * col_2.clone() + col_1.clone() - col_3.clone()),
);
eval
}
}
```
Now that we have the traces, we need to create a struct that contains the logic for evaluating the constraints. As mentioned before, we need to use the `is_first_id` field to retrieve the row value of the `IsFirstColumn` struct. Then, we compose two constraints using the `IsFirstColumn` row value as a selector and adding them together.
If you're unfamiliar with how `max_constraint_log_degree_bound(&self)` should be implemented, please refer to [this note](../writing-a-simple-air/constraints-over-trace-polynomials.mdx#max_constraint_log_degree_bound).
```rust theme={null}
fn main() {
...
// Create a component
let component = FrameworkComponent::<TestEval>::new(
&mut TraceLocationAllocator::default(),
TestEval {
is_first_id: is_first_column.id(),
log_size,
},
QM31::zero(),
);
// Prove
let proof = prove(&[&component], channel, commitment_scheme).unwrap();
// Verify
let channel = &mut Blake2sChannel::default();
let commitment_scheme = &mut CommitmentSchemeVerifier::<Blake2sMerkleChannel>::new(config);
let sizes = component.trace_log_degree_bounds();
commitment_scheme.commit(proof.commitments[0], &sizes[0], channel);
channel.mix_u64(log_size as u64);
commitment_scheme.commit(proof.commitments[1], &sizes[1], channel);
verify(&[&component], channel, commitment_scheme, proof).unwrap();
}
```
Finally, we can create a `FrameworkComponent` using the `TestEval` struct and then prove and verify the component.
# Static Lookups
Source: https://docs.starknet.io/learn/S-two-book/air-development/static-lookups/index
In the previous section, we showed how to create a preprocessed trace. In this section, we will introduce the concept of an interaction trace, and use it with the preprocessed trace to implement **static lookups**.
Let's start with a brief introduction to lookups. A lookup is a way to connect values from one part of the table to another part of the table. A simple example is when we want to copy values across parts of the table. At first glance, this seems feasible using a constraint. For example, we can copy $col_1$ values to $col_2$ by creating a constraint that $col_1 - col_2$ is equal to $0$. The limitation with this approach, however, is that the same constraint needs to be satisfied over every row in the columns. In other words, we can only check that $col_2$ is an exact copy of $col_1$:
$$
col_1[i] = col_2[i] \quad \forall\, i
$$
But what if we want to check that $col_2$ is a copy of $col_1$ regardless of the order of the values? This can be done by comparing that the grand product of the random linear combinations of all values in $col_1$ is equal to the grand product of the random linear combinations of all values in $col_2$:
$$
\prod_{i=0}^{n-1} (X - col_1[i]) = \prod_{i=0}^{n-1} (X - col_2[i])
$$
where $X$ is a random value from the verifier.
By taking the logarithmic derivative of each side of the equation, we can rewrite it:
$$
\sum_{i=0}^{n-1} \frac{1}{X-col_1[i]} = \sum_{i=0}^{n-1} \frac{1}{X-col_2[i]}
$$
We can go further and allow each of the original values to be copied a different number of times. This is supported by modifying the check to the following:
$$
\sum_{i=0}^{n-1} \frac{1}{X-col_1[i]} = \sum_{i=0}^{n-1} \frac{m_i}{X-col_2[i]}
$$
Where $m_i$ represents the multiplicity, or the number of times $col_1[i]$ appears in $col_2$.
In S-two, these fractions (which we will hereafter refer to as *LogUp fractions*) are stored in a special type of trace called an *interaction trace*. An interaction trace is used to contain values that involve interaction between the prover and the verifier. As mentioned above, a LogUp fraction requires a random value $X$ from the verifier, which is why it is stored in an interaction trace.
## Range-check AIR
We will now walk through the implementation of a static lookup, which is a lookup where the values that are being looked up are static, i.e. part of the preprocessed trace. Specifically, we will implement a **range-check AIR**, which checks that a certain value is within a given range. This is especially useful for frameworks like S-two that use finite fields because it allows checking for underflow and overflow.
A range-check checks that all values in a column are within a certain range. For example, as in [Figure 1](#figure-1), we can check that all values in the range-checked columns are between 0 and 3. We do this by first creating a multiplicity column that counts the number of times each value in the preprocessed trace appears in the range-checked columns.
Then, we create two LogUp columns as part of the interaction trace. The first column contains in each row a fraction with numerator equal to the multiplicity and denominator equal to the random linear combination of the value in the range column. For example, for row 1, the fraction should be $\frac{2}{X-0}$, where $X$ is a random value. The second column contains batches of fractions where the denominator of each fraction is the random linear combination of the value in the range-checked column. Note that the numerator of each fraction is always -1, i.e. we apply a negation, because we want the sum of the first column to be equal to the sum of the second column.
<div>
<img alt="" />
*Figure 1: Range-check lookup*
</div>
If we add all the fractions in the two columns together, we get 0. This means that the verifier will be convinced with high probability that the values in the range-checked columns are a subset of the values in the range column.
## Implementation
Now let's move on to the implementation where we create a 4-bit range-check AIR. We do this by creating a preprocessed trace column with the integers $[0, 16)$, then using a lookup to force the values in the original trace columns to lie in the values of the preprocessed프로젝트로 돌아가기