bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 43쪽
</div>
<div>
<svg>
<path />
</svg>
</div>
</div>
<div>
<div>
<div>
<h1>
<span>
<div>WELCOME TO THE NEW</div>
<div>STARKNET DOCS</div>
</span>
</h1>
</div>
<p>
The Starknet Docs is the unified home for Starknet's technical documentation
aimed to help you unlock the full potential of Ethereum and Bitcoin
</p>
<div>
<div>
## Explore the docs
</div>
<div>
<a href="/build/quickstart/environment-setup">
<div />
<div>
### Build
<p>
Find everything you need to build Starknet's next killer app
</p>
</div>
</a>
<a href="/secure/quickstart/overview">
<div />
<div>
### Secure
<p>
Help secure Starknet by running a node and becoming a validator
</p>
</div>
</a>
<a href="/learn/protocol/intro">
<div />
<div>
### Learn
<p>
Dive into Starknet's protocol, the S-two prover, and more
</p>
</div>
</a>
</div>
</div>
</div>
</div>
<div>
<div>
<div>
## Join the community
</div>
<div>
<a href="https://community.starknet.io/">
<div />
<div>
### Forum
<p>
Stay updated on the latest news from the Starknet team
</p>
</div>
</a>
<a href="https://t.me/sncorestars">
<div />
<div>
### Telegram
<p>
Get help from core contributors and help out yourself
</p>
</div>
</a>
<a href="https://discord.gg/starknet-community">
<div />
<div>
### Discord
<p>
Connect other developers and community members
</p>
</div>
</a>
</div>
</div>
</div>
</div>
# Additional Examples
Source: https://docs.starknet.io/learn/S-two-book/air-development/additional-examples/index
Here, we introduce some additional AIRs that may help in designing more complex AIRs.
## Selectors
A selector is a column of 0s and 1s that selectively enables or disables a constraint. One example of a selector is the `IsFirst` column which has a value of 1 only on the first row. This can be used when constraints are defined over both the current and previous rows but we need to make an exception for the first row.
For example, as seen in [Figure 1](#figure-1), when we want to track the cumulative sum of a column, i.e. $b_2 = a_1 + a_2$, the previous row of the first row points to the last row, creating an incorrect constraint $a_1 = b_4 + b_1$. Thus, we need to disable the constraint for the first row and enable a separate constraint $a_1 = b_1$. This can be achieved by using a selector column that has a value of 1 on the first row and 0 on the other rows and multiplying the constraint by the selector column:
$$
(1 - \text{IsFirst(X)}) \cdot (A(\omega \cdot X) - B(X) - B(\omega \cdot X)) + \text{IsFirst(X)} \cdot (A(X) - B(X)) = 0
$$
where $X$ refers to the previous value of $\omega\cdot X$ in the multiplicative subgroup of the finite field.
<div>
<img alt="" />
*Figure 1: IsFirst selector*
</div>
## IsZero
Checking that a certain field element is zero is a common use case when writing AIRs. To do this efficiently, we can use the property of finite fields that a non-zero field element always has a multiplicative inverse.
For example, in [Figure 2](#figure-2), we want to check whether a field element in $\mathbb{F}_5$ is zero. We create a new column that contains the multiplicative inverse of each field element $a_i$. We then use the multiplication of the two columns and check whether the result is 0 or 1. Note that if the existing column has a zero element, we can insert any value in the new column since the multiplication will always be zero.
This way, we can create a constraint that uses the `IsZero` condition as part of the constraint, e.g. $(1 - (A(X) \cdot Inv(X))) \cdot (\text{constraint\_1}) + (A(X) \cdot Inv(X)) \cdot (\text{constraint\_2}) = 0$, which checks $\text{constraint\_1}$ if $A(X)$ is 0 and $\text{constraint\_2}$ if $A(X)$ is not 0.
<div>
<img alt="" />
*Figure 2: IsZero over a prime field 5*
</div>
## Public Inputs
When writing AIRs, we may want to expose some values in the trace to the verifier to check in the open. For example, when running an AIR for a Cairo program, we may want to check that the program that was executed is the correct one.
In S-two, we can achieve this by adding the public input portion of the trace as a LogUp column as negative multiplicity. As shown in [Figure 3](#figure-3), the public inputs $a_1, a_2$ are added as LogUp values with negative multiplicity $\frac{-1}{X - a_1}$ and $\frac{-1}{X - a_2}$. The public inputs are given to the verifier as part of the proof and the verifier can directly compute the LogUp values with positive multiplicity $\frac{1}{X - a_1}$ and $\frac{1}{X - a_2}$ and add it to the LogUp sum and check that the total sum is 0.
<div>
<img alt="" />
*Figure 3: Public inputs*
</div>
One important thing to note is that the public inputs must be added to the Fiat-Shamir channel before drawing random elements for the interaction trace. We refer the reader to this [example implementation](https://github.com/starknet-io/starknet-docs/blob/main/learn/S-two-book/stwo-examples/examples/public_input.rs) for reference.
## XOR
We can also handle XOR operations as part of the AIR. First, as we did in the [Components](../components/index) section, we create a computing component and a scheduling component. Then, we connect the two components using lookups: the computing component sets the LogUp value as a negative multiplicity and the scheduling component sets the same value as a positive multiplicity.
For example, [Figure 4](#figure-4) shows the XOR operation for 4-bit integers. To accommodate the entire combination of inputs, the size of the trace for the computing component is $2^8=256$ rows. Note that the size of the trace for the scheduling component does not have to be the same as the computing component.
<div>
<img alt="" />
*Figure 4: XOR operations for 4-bit integers*
</div>
Note that for larger integers, we may need to decompose into smaller limbs to avoid creating large tables. Also note that the M31 field does not fully support XOR operations for 31-bit integers since we cannot use $2^{31} -1$, although this is not feasible as it would require a table of size of around $2^{31} \times 2^{31}$.
# Components
Source: https://docs.starknet.io/learn/S-two-book/air-development/components/index
So now that we know how to create a self-contained AIR, the inevitable question arises: How do we make this modular?
Fortunately, S-two provides an abstraction called **components** that allows us to create independent AIRs and compose them together. In other proving frontends, this is also commonly referred to as a *chip*, but the idea is the same.
One of the most common use cases of components is to separate frequently used functions (e.g. a hash function) from the main component into a separate component and reuse it, avoiding trace column bloat. Even if the function is not frequently used, it can be useful to separate it into a component to avoid the degree of the constraints becoming too high. This second point is possible because when we create a new component and connect it to the old component, we do it by using lookups, which means that the constraints of the new component are not added to the degree of the old component.
## Hash Function Example
To illustrate how to use components, we will create two components where the main component calls a hash function component. For simplicity, instead of an actual hash function, the second component will compute $x^5 + 1$ from an input $x$. This component will have, in total, three columns: \[input, intermediate, output], which will correspond to the values $[x, x^3, x^5 + 1]$. Our main component, on the other hand, will have two columns, \[input, output], which corresponds to the values $[x, x^5 + 1]$.
We'll refer to the main component as the **scheduling component** and the hash function component as the **computing component**, since the main component is essentially *scheduling* the hash function component to run its function with a given input and the hash function component *computes* on the provided input. As can be seen in [Figure 1](#figure-1), the input and output of each component are connected by lookups.
<div>
<img alt="" />
*Figure 1: Scheduling and Computing components*
</div>
### Design
<div>
<img alt="" />
*Figure 2: Traces of each component*
</div>
When we implement this in S-two, the traces of each component will look like [Figure 2](#figure-2) above. Each component has its own original and LogUp traces, and the inputs and outputs of each component are connected by lookups. Since the scheduling component sets the LogUp value as a positive multiplicity and the computing component sets the same value as a negative multiplicity, the verifier can simply check that the sum of the two LogUp columns is zero. Note that we combine the input and output randomly as
$$
\frac{1}{Z - x \cdot \alpha^0 - (x^5+1) \cdot \alpha^1}
$$
to form a single lookup. This is because we want to ensure that each input is paired with the correct output. If we add the input and output as separate lookups as
$$
\frac{1}{Z - x} + \frac{1}{Z - (x^5+1)}
$$
A malicious prover can switch the output with a different row and still come up with a valid proof. For example, the following scheduling component
| Input | Output |
| - | - |
| x | y^5 + 1 |
| y | x^5 + 1 |
And the following computing component
| Input | Intermediate | Output |
| - | - | - |
| x | x^3 + 1 | x^5 + 1 |
| y | y^3 + 1 | y^5 + 1 |
would be valid.
## Implementation
Let's move on to the implementation.
```rust theme={null}
fn main() {
// --snip--
// Create trace columns
let scheduling_trace = gen_scheduling_trace(log_size);
let computing_trace = gen_computing_trace(log_size, &scheduling_trace[0], &scheduling_trace[1]);
// Statement 0
let statement0 = ComponentsStatement0 { log_size };
statement0.mix_into(channel);
// Commit to the trace columns
let mut tree_builder = commitment_scheme.tree_builder();
tree_builder.extend_evals([scheduling_trace.clone(), computing_trace.clone()].concat());
tree_builder.commit(channel);
// Draw random elements to use when creating the random linear combination of lookup values in the LogUp columns
let lookup_elements = ComputationLookupElements::draw(channel);
// Create LogUp columns
let (scheduling_logup_cols, scheduling_claimed_sum) = gen_scheduling_logup_trace(
log_size,
&scheduling_trace[0],
&scheduling_trace[1],
&lookup_elements,
);
let (computing_logup_cols, computing_claimed_sum) = gen_computing_logup_trace(
log_size,
&computing_trace[0],
&computing_trace[2],
&lookup_elements,
);
// Statement 1
let statement1 = ComponentsStatement1 {
scheduling_claimed_sum,
computing_claimed_sum,
};
statement1.mix_into(channel);
// Commit to the LogUp columns
let mut tree_builder = commitment_scheme.tree_builder();
tree_builder.extend_evals([scheduling_logup_cols, computing_logup_cols].concat());
tree_builder.commit(channel);
let components = Components::new(&statement0, &lookup_elements, &statement1);
let stark_proof = prove(&components.component_provers(), channel, commitment_scheme).unwrap();
let proof = ComponentsProof {
statement0,
statement1,
stark_proof,
};
// --snip--
}
```
The code above for proving the components should look pretty familiar by now. Since we need to do everything twice as many times, we create structs like `ComponentsStatement0`, `ComponentsStatement1`, `Components`, and `ComponentsProof`, but the main logic is the same.
Let's take a closer look at how the LogUp columns are generated.
```rust theme={null}
fn gen_scheduling_logup_trace(
log_size: u32,
scheduling_col_1: &CircleEvaluation<SimdBackend, M31, BitReversedOrder>,
scheduling_col_2: &CircleEvaluation<SimdBackend, M31, BitReversedOrder>,
lookup_elements: &ComputationLookupElements,
) -> (
Vec<CircleEvaluation<SimdBackend, M31, BitReversedOrder>>,
SecureField,
) {
// --snip--
let scheduling_input_output: PackedSecureField =
lookup_elements.combine(&[scheduling_col_1.data[row], scheduling_col_2.data[row]]);
col_gen.write_frac(row, PackedSecureField::one(), scheduling_input_output);
// --snip--
fn gen_computing_logup_trace(
log_size: u32,
computing_col_1: &CircleEvaluation<SimdBackend, M31, BitReversedOrder>,
computing_col_3: &CircleEvaluation<SimdBackend, M31, BitReversedOrder>,
lookup_elements: &ComputationLookupElements,
) -> (
Vec<CircleEvaluation<SimdBackend, M31, BitReversedOrder>>,
SecureField,
) {
// --snip--
let computing_input_output: PackedSecureField =
lookup_elements.combine(&[computing_col_1.data[row], computing_col_3.data[row]]);
col_gen.write_frac(row, -PackedSecureField::one(), computing_input_output);
// --snip--
}
```
As you can see, the LogUp values of the input and output columns of both the scheduling and computing components are batched together, but in the scheduling component, the output LogUp value is subtracted from the input LogUp value, while in the computing component, the input LogUp value is subtracted from the output LogUp value. This means that when the LogUp sums from both components are added together, they should cancel out to zero.
Next, let's check how the constraints are created.
```rust theme={null}
impl FrameworkEval for SchedulingEval {
// --snip--
fn evaluate<E: EvalAtRow>(&self, mut eval: E) -> E {
let input_col = eval.next_trace_mask();
let output_col = eval.next_trace_mask();
eval.add_to_relation(RelationEntry::new(
&self.lookup_elements,
E::EF::one(),
&[input_col, output_col],
));
eval.finalize_logup();
eval
}
}
impl FrameworkEval for ComputingEval {
// --snip--
fn evaluate<E: EvalAtRow>(&self, mut eval: E) -> E {
let input_col = eval.next_trace_mask();
let intermediate_col = eval.next_trace_mask();
let output_col = eval.next_trace_mask();
eval.add_constraint(
intermediate_col.clone() - input_col.clone() * input_col.clone() * input_col.clone(),
);
eval.add_constraint(
output_col.clone()
- intermediate_col.clone() * input_col.clone() * input_col.clone()
- E::F::one(),
);
eval.add_to_relation(RelationEntry::new(
&self.lookup_elements,
-E::EF::one(),
&[input_col, output_col],
));
eval.finalize_logup();
eval
}
}
```
As you can see, we define the LogUp constraints for each component, and we also add two constraints that make sure the computations $x^3$ and $x^5 + 1$ are correct.
```rust theme={null}
fn main() {
// --snip--
// Verify claimed sums
assert_eq!(
scheduling_claimed_sum + computing_claimed_sum,
SecureField::zero()
);
// Unpack proof
let statement0 = proof.statement0;
let statement1 = proof.statement1;
let stark_proof = proof.stark_proof;
// Create channel and commitment scheme
let channel = &mut Blake2sChannel::default();
let commitment_scheme = &mut CommitmentSchemeVerifier::<Blake2sMerkleChannel>::new(config);
let log_sizes = statement0.log_sizes();
// Preprocessed columns.
commitment_scheme.commit(stark_proof.commitments[0], &log_sizes[0], channel);
// Commit to statement 0
statement0.mix_into(channel);
// Trace columns.
commitment_scheme.commit(stark_proof.commitments[1], &log_sizes[1], channel);
// Draw lookup element.
let lookup_elements = ComputationLookupElements::draw(channel);
// Commit to statement 1
statement1.mix_into(channel);
// Interaction columns.
commitment_scheme.commit(stark_proof.commitments[2], &log_sizes[2], channel);
// Create components
let components = Components::new(&statement0, &lookup_elements, &statement1);
verify(
&components.components(),
channel,
commitment_scheme,
stark_proof,
)
.unwrap();
```
Finally, we verify the components!
# Dynamic Lookups
Source: https://docs.starknet.io/learn/S-two-book/air-development/dynamic-lookups/index
In the last section, we implemented a static lookup. A dynamic lookup is the same as a static lookup except that the values that are being looked up are not known before the proving process (i.e. they are not preprocessed columns but trace columns).
In this section, we will implement one of the simplest dynamic lookups: a permutation check.
A permutation check simply checks that two sets of values have the same elements, but not necessarily in the same order. For example, the values $[1, 2, 3]$ and $[3, 1, 2]$ are a permutation of each other, but $[1, 2, 3]$ and $[1, 2]$ are not.
If you went through the previous section, you should have a good intuition for how to implement this. First, create two original trace columns that each contain a random permutation of the same set of values. Then, create a LogUp column where the first original trace column is added as a fraction with multiplicity $1$ and the second original trace column is added as a fraction with multiplicity $-1$. Then, check that the `claimed_sum`, or the sum of the fractions in the two LogUp columns, is $0$.
<div>
<img alt="" />
*Figure 1: Permutation check*
</div>
Let's move on to the implementation.
```rust theme={null}
fn gen_trace(log_size: u32) -> Vec<CircleEvaluation<SimdBackend, M31, BitReversedOrder>> {
let mut rng = rand::thread_rng();
let values = (0..(1 << log_size)).map(|i| i).collect::<Vec<_>>();
// Create a random permutation of the values
let mut random_values = values.clone();
random_values.shuffle(&mut rng);
let random_col_1 = BaseColumn::from_iter(random_values.iter().map(|v| M31::from(*v)));
// Create another random permutation of the values
let mut random_values = random_values.clone();
random_values.shuffle(&mut rng);
let random_col_2 = BaseColumn::from_iter(random_values.iter().map(|v| M31::from(*v)));
// Convert table to trace polynomials
let domain = CanonicCoset::new(log_size).circle_domain();
vec![random_col_1, random_col_2]
.into_iter()
.map(|col| CircleEvaluation::new(domain, col))
.collect()
}
fn gen_logup_trace(
log_size: u32,
random_col_1: &BaseColumn,
random_col_2: &BaseColumn,
lookup_elements: &LookupElements,
) -> (
Vec<CircleEvaluation<SimdBackend, M31, BitReversedOrder>>,
SecureField,
) {
let mut logup_gen = LogupTraceGenerator::new(log_size);
let mut col_gen = logup_gen.new_col();
for row in 0..(1 << (log_size - LOG_N_LANES)) {
// 1 / random - 1 / ordered = (ordered - random) / (random * ordered)
let random_val: PackedSecureField = lookup_elements.combine(&[random_col_1.data[row]]);
let ordered_val: PackedSecureField = lookup_elements.combine(&[random_col_2.data[row]]);
col_gen.write_frac(row, ordered_val - random_val, random_val * ordered_val);
}
col_gen.finalize_col();
logup_gen.finalize_last()
}
fn main() {
...
// Create and commit to the trace columns
let trace = gen_trace(log_size);
let mut tree_builder = commitment_scheme.tree_builder();
tree_builder.extend_evals(trace.clone());
tree_builder.commit(channel);
// Draw random elements to use when creating the random linear combination of lookup values in the LogUp columns
let lookup_elements = LookupElements::draw(channel);
// Create and commit to the LogUp columns
let (logup_cols, claimed_sum) =
gen_logup_trace(log_size, &trace[0], &trace[1], &lookup_elements);
let mut tree_builder = commitment_scheme.tree_builder();
tree_builder.extend_evals(logup_cols);
tree_builder.commit(channel);
...
}
```
Looking at the code above, we can see that it looks very similar to the implementation in the previous section. Instead of creating a preprocessed column, we create two columns where the first column is a random permutation of values `[0, 1 << log_size)` and the second column contains the values in order. Note that this is equivalent to "looking up" all values in the first trace column once. And since all the values are looked up exactly once, we do not need a separate multiplicity column.
Then, we create a LogUp column that contains the values $\frac{1}{original} - \frac{1}{permuted}$.
```rust theme={null}
struct TestEval {
log_size: u32,
lookup_elements: LookupElements,
}
impl FrameworkEval for TestEval {
fn log_size(&self) -> u32 {
self.log_size
}
fn max_constraint_log_deg프로젝트로 돌아가기