bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 19쪽
se keys are essential for the prover to create proofs and for the verifier to validate them.
#### Phase 1: "Powers of Tau" Ceremony
<Info>
A trusted setup ceremony is a collaborative process where multiple participants contribute randomness to create the cryptographic parameters for a proof system (the proving and verification keys), with the goal to provide additional security. You can provide additional contributions if you wish to do so.
</Info>
* Initialize powers of tau ceremony:
```bash [Terminal] theme={null}
mkdir target/ptau && cd target/ptau
snarkjs powersoftau new bn128 12 pot12_0000.ptau -v
```
```bash [Terminal] theme={null}
snarkjs powersoftau contribute pot12_0000.ptau pot12.ptau --name="My contribution to part 1" -v -e="some random text for the contribution to part 1"
```
#### Phase 2: Circuit Dependent
* Finalize ptau file:
```bash [Terminal] theme={null}
snarkjs powersoftau prepare phase2 pot12.ptau pot12_final.ptau -v
```
* Generate a zkey file:
```bash [Terminal] theme={null}
cd ..
snarkjs groth16 setup circuit.r1cs ptau/pot12_final.ptau circuit_0000.zkey
```
* Contribute to Phase 2:
```bash [Terminal] theme={null}
snarkjs zkey contribute circuit_0000.zkey circuit_0001.zkey --name="My contribution to part 2" -v -e="some random text for the contribution to part 2"
```
We now have our proving key (`circuit_0001.zkey{:md}`) that we will use, along with the compiled circuit and the input to the circuit, to generate proofs.
* Export verification key:
```bash [Terminal] theme={null}
snarkjs zkey export verificationkey circuit_0001.zkey circuit_verification_key.json
```
We have our verification key (`circuit_verification_key.json{:md}`) that we will use, along with the generated proof and its outputs, to verify proofs.
### 4. Proof Generation
#### Generate witness
The **witness** refers to the private input and intermediate values that the prover knows and uses to generate the proof. The intermediate values correspond to the values computed during the circuit execution. These are also part of the witness and are necessary for proving the correctness of the computation. In short, the witness is a complete set of values that satisfies the constraints defined by the zk-SNARK circuit.
```bash [Terminal] theme={null}
node circuit_js/generate_witness.js circuit_js/circuit.wasm ../src/circuit/input.json witness.wtns
```
#### Generate proof
```bash [Terminal] theme={null}
snarkjs groth16 prove circuit_0001.zkey witness.wtns proof.json public.json
```
<Note>
To generate a proof, 3 information are needed:
* compiled circuit
* circuit inputs
* proving key
To verify a proof, 3 information are also needed:
* proof
* circuit outputs (obtained when generating proof)
* verification key
</Note>
### 5. Generate verifier contract
```bash [Terminal] theme={null}
garaga gen --system groth16 --vk circuit_verification_key.json
```
This above command will generate a cairo project with the verifier contract, with the main endpoint `verify_groth16_proof_[curve_name]{:md}`.
<Info>
Garaga also provides some command utilities to deploy it on-chain. Else, you can deploy it like any other contract (using starkli or sncast for example).
</Info>
Here is the generated starknet contract:
```rust theme={null}
use super::groth16_verifier_constants::{N_PUBLIC_INPUTS, vk, ic, precomputed_lines};
#[starknet::interface]
trait IGroth16VerifierBN254<TContractState> {
fn verify_groth16_proof_bn254(
self: @TContractState, full_proof_with_hints: Span<felt252>,
) -> Option<Span<u256>>;
}
#[starknet::contract]
mod Groth16VerifierBN254 {
use starknet::SyscallResultTrait;
use garaga::definitions::{G1Point, G1G2Pair};
use garaga::groth16::{multi_pairing_check_bn254_3P_2F_with_extra_miller_loop_result};
use garaga::ec_ops::{G1PointTrait, ec_safe_add};
use garaga::ec_ops_g2::{G2PointTrait};
use garaga::utils::calldata::{deserialize_full_proof_with_hints_bn254};
use super::{N_PUBLIC_INPUTS, vk, ic, precomputed_lines};
const ECIP_OPS_CLASS_HASH: felt252 =
0x70c1d1c709c75e3cf51d79d19cf7c84a0d4521f3a2b8bf7bff5cb45ee0dd289;
use starknet::ContractAddress;
#[storage]
struct Storage {}
#[abi(embed_v0)]
impl IGroth16VerifierBN254 of super::IGroth16VerifierBN254<ContractState> {
fn verify_groth16_proof_bn254(
self: @ContractState, full_proof_with_hints: Span<felt252>,
) -> Option<Span<u256>> {
// DO NOT EDIT THIS FUNCTION UNLESS YOU KNOW WHAT YOU ARE DOING.
// This function returns an Option for the public inputs if the proof is valid.
// If the proof is invalid, the execution will either fail or return None.
// Read the documentation to learn how to generate the full_proof_with_hints array given
// a proof and a verifying key.
let fph = deserialize_full_proof_with_hints_bn254(full_proof_with_hints);
let groth16_proof = fph.groth16_proof;
let mpcheck_hint = fph.mpcheck_hint;
let small_Q = fph.small_Q;
let msm_hint = fph.msm_hint;
groth16_proof.a.assert_on_curve(0);
groth16_proof.b.assert_on_curve(0);
groth16_proof.c.assert_on_curve(0);
let ic = ic.span();
let vk_x: G1Point = match ic.len() {
0 => panic!("Malformed VK"),
1 => *ic.at(0),
_ => {
// Start serialization with the hint array directly to avoid copying it.
let mut msm_calldata: Array<felt252> = msm_hint;
// Add the points from VK and public inputs to the proof.
Serde::serialize(@ic.slice(1, N_PUBLIC_INPUTS), ref msm_calldata);
Serde::serialize(@groth16_proof.public_inputs, ref msm_calldata);
// Complete with the curve identifier (0 for BN254):
msm_calldata.append(0);
// Call the multi scalar multiplication endpoint on the Garaga ECIP ops contract
// to obtain vk_x.
let mut _vx_x_serialized = core::starknet::syscalls::library_call_syscall(
ECIP_OPS_CLASS_HASH.try_into().unwrap(),
selector!("msm_g1"),
msm_calldata.span(),
)
.unwrap_syscall();
ec_safe_add(
Serde::<G1Point>::deserialize(ref _vx_x_serialized).unwrap(), *ic.at(0), 0,
)
},
};
// Perform the pairing check.
let check = multi_pairing_check_bn254_3P_2F_with_extra_miller_loop_result(
G1G2Pair { p: vk_x, q: vk.gamma_g2 },
G1G2Pair { p: groth16_proof.c, q: vk.delta_g2 },
G1G2Pair { p: groth16_proof.a.negate(0), q: groth16_proof.b },
vk.alpha_beta_miller_loop_result,
precomputed_lines.span(),
mpcheck_hint,
small_Q,
);
if check == true {
return Option::Some(groth16_proof.public_inputs);
} else {
return Option::None;
}
}
}
}
```
### 6. Generate calldata & call on-chain verifier contract
This step is useful for generating calldata from the proof & circuit execution outputs, which can then be sent to the verifier contract to verify the proof on-chain. In this example, there is an intermediary contract, `ZkERC20Token`, which will itself call the verifier contract (more about it below).
```bash [Terminal] theme={null}
garaga calldata --system groth16 --vk circuit_verification_key.json --proof proof.json --public-inputs public.json --format starkli | xargs starkli invoke --account ~/.starkli-wallets/deployer/account.json --keystore ~/.starkli-wallets/deployer/keystore.json --network sepolia --watch 0x00375cf5081763e1f2a7ed5e28d4253c6135243385f432492dda00861ec5e58f mint_with_proof
```
<Info>
Garaga also provides some command utilities to call the verifier contract directly abstracting the calldata generation part, simplifying the above command.
</Info>
### 7. `ZkERC20Token` contract
This contract allows anyone to mint free tokens if they know a secret password (`2468`). You can submit your proof calldata to this contract, which will itself call the generated verifier contract. If the proof verification passes and the proof is indeed unique to you (ie, you generated it yourself), you can receive the free tokens. Otherwise, the endpoint execution will revert. You can mint free tokens only once per user.
Contract Address (Sepolia testnet): `0x00375cf5081763e1f2a7ed5e28d4253c6135243385f432492dda00861ec5e58f{:md}`
```rust theme={null}
use starknet::ContractAddress;
#[starknet::interface]
trait IZkERC20Token<TContractState> {
fn mint_with_proof(ref self: TContractState, full_proof: Span<felt252>);
fn has_user_minted(self: @TContractState, address: ContractAddress) -> bool;
}
#[starknet::interface]
trait IGroth16VerifierBN254<TContractState> {
fn verify_groth16_proof_bn254(
self: @TContractState, full_proof_with_hints: Span<felt252>,
) -> Option<Span<u256>>;
}
mod errors {
pub const ALREADY_MINTED: felt252 = "User has already minted tokens";
pub const PROOF_NOT_VERIFIED: felt252 = "Proof is not correct";
pub const PROOF_ALREADY_USED: felt252 = "Generate a proof unique to you";
}
#[starknet::contract]
pub mod ZkERC20Token {
use openzeppelin_token::erc20::{ERC20Component, ERC20HooksEmptyImpl};
use starknet::{ContractAddress, get_caller_address};
use super::{errors, IGroth16VerifierBN254Dispatcher, IGroth16VerifierBN254DispatcherTrait};
use starknet::storage::{
Map, StoragePointerReadAccess, StoragePointerWriteAccess, StoragePathEntry,
};
component!(path: ERC20Component, storage: erc20, event: ERC20Event);
#[abi(embed_v0)]
impl ERC20MixinImpl = ERC20Component::ERC20MixinImpl<ContractState>;
impl ERC20InternalImpl = ERC20Component::InternalImpl<ContractState>;
const MINT_WITH_PROOF_TOKEN_REWARD: u8 = 100;
// used in the front end to generate the proof
const PASSWORD_HASH: u256 =
16260938803047823847354854419633652218467975114284208787981985448019235110758;
#[storage]
struct Storage {
#[substorage(v0)]
erc20: ERC20Component::Storage,
verifier_contract: IGroth16VerifierBN254Dispatcher,
users_who_minted: Map<ContractAddress, bool>,
}
#[event]
#[derive(Drop, starknet::Event)]
enum Event {
#[flat]
ERC20Event: ERC20Component::Event,
}
#[constructor]
fn constructor(
ref self: ContractState,
initial_supply: u256,
recipient: ContractAddress,
name: ByteArray,
symbol: ByteArray,
proof_verifier_address: ContractAddress,
) {
self.erc20.initializer(name, symbol);
self.erc20.mint(recipient, initial_supply);
self
.verifier_contract
.write(IGroth16VerifierBN254Dispatcher { contract_address: proof_verifier_address });
}
#[abi(embed_v0)]
impl ZkERC20TokenImpl of super::IZkERC20Token<ContractState> {
fn mint_with_proof(ref self: ContractState, full_proof: Span<felt252>) {
let caller = get_caller_address();
// Prevent a user from receiving tokens twice
assert(!self.users_who_minted.entry(caller).read(), errors::ALREADY_MINTED);
// Verify the correctness of the proof by calling the verifier contract
// If incorrect, execution of the verifier will fail or return an Option::None
let proof_public_inputs = self
.verifier_contract
.read()
.verify_groth16_proof_bn254(full_proof);
assert(
proof_public_inputs.is_some() && proof_public_inputs.unwrap().len() == 3,
errors::PROOF_NOT_VERIFIED,
);
// Verify the proof has been generated by the user calling this smart contract
let user_address_dec: u256 = *proof_public_inputs.unwrap().at(1);
let address_felt252: felt252 = caller.into();
assert(address_felt252.into() == user_address_dec, errors::PROOF_ALREADY_USED);
// Mint tokens only if the proof is valid and has been generated by the user
self.erc20.mint(caller, MINT_WITH_PROOF_TOKEN_REWARD.into());
self.users_who_minted.entry(caller).write(true);
}
fn has_user_minted(self: @TContractState, address: ContractAddress) -> bool {
self.users_who_minted.entry(address).read()
}
}
}
```
<Info>
For more detailed information about the technologies used, refer to:
* [Circom Documentation](https://docs.circom.io/)
* [Snarkjs GitHub](https://github.com/iden3/snarkjs)
* [Garaga Documentation](https://garaga.gitbook.io/garaga)
</Info>
# Writing to any storage slot
Source: https://docs.starknet.io/build/starknet-by-example/advanced/write-to-any-slot
On Starknet, a contract's storage is a map with $( 2^{251} )$ slots, where each slot is a `felt252` which is initialized to 0.
The address of storage variables is computed at compile time using the formula:
$$
storage\_variable\_address~\text{:=}~\text{pedersen}(\text{keccak}(variable\_name),~keys)
$$
Interactions with storage variables are commonly performed using the `self.var.read()` and `self.var.write()` functions.
Nevertheless, we can use the `storage_write_syscall` and `storage_read_syscall` syscalls, to write to and read from any storage slot.
This is useful when writing to storage variables that are not known at compile time, or to ensure that even if the contract is upgraded and the computation method of storage variable addresses changes, they remain accessible.
In the following example, we use the Poseidon hash function to compute the address of a storage variable. Poseidon is a ZK-friendly hash function that is cheaper and faster than Pedersen, making it an excellent choice for onchain computations. Once the address is computed, we use the storage syscalls to interact with it.
```rust theme={null}
#[starknet::interface]
pub trait IWriteToAnySlots<TContractState> {
fn write_slot(ref self: TContractState, value: u32);
fn read_slot(self: @TContractState) -> u32;
}
#[starknet::contract]
pub mod WriteToAnySlot {
use starknet::syscalls::{storage_read_syscall, storage_write_syscall};
use core::poseidon::poseidon_hash_span;
use starknet::StorageAddress;
#[storage]
struct Storage {}
const SLOT_NAME: felt252 = 'test_slot';
#[abi(embed_v0)]
impl WriteToAnySlot of super::IWriteToAnySlots<ContractState> {
fn write_slot(ref self: ContractState, value: u32) {
storage_write_syscall(0, get_address_from_name(SLOT_NAME), value.into()).unwrap();
}
fn read_slot(self: @ContractState) -> u32 {
storage_read_syscall(0, get_address_from_name(SLOT_NAME)).unwrap().try_into().unwrap()
}
}
pub fn get_address_from_name(variable_name: felt252) -> StorageAddress {
let mut data: Array<felt252> = array![];
data.append(variable_name);
let hashed_name: felt252 = poseidon_hash_span(data.span());
let MASK_250: u256 = 0x03ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
// By taking the 250 least significant bits of the hash output, we get a valid 250bits
// storage address.
let result: felt252 = (hashed_name.into() & MASK_250).try_into().unwrap();
let result: StorageAddress = result.try_into().unwrap();
result
}
}
```
# Advanced factory
Source: https://docs.starknet.io/build/starknet-by-example/applications/advanced-factory
This is an example of an advanced factory contract that manages crowdfunding Campaign contracts created in the ["Crowdfunding" chapter](./crowdfunding). The advanced factory allows for a centralized creation and management of `Campaign` contracts on the Starknet blockchain, ensuring that they adhere to a standard interface and can be easily upgraded.
Key Features
1. **Campaign Creation**: Users can create new crowdfunding campaigns with specific details such as title, description, goal, and duration.
2. **Campaign Management**: The factory contract stores and manages the campaigns, allowing for upgrades and tracking.
3. **Upgrade Mechanism**: The factory owner can update the implementation of the campaign contract, ensuring that all campaigns benefit from improvements and bug fixes.
* the factory only updates it's `Campaign` class hash and emits an event to notify any listeners, but the `Campaign` creators are in the end responsible for actually upgrading their contracts.
```rust theme={null}
pub use starknet::{ContractAddress, ClassHash};
#[starknet::interface]
pub trait ICampaignFactory<TContractState> {
fn create_campaign(
ref self: TContractState,
title: ByteArray,
description: ByteArray,
goal: u256,
start_time: u64,
end_time: u64,
token_address: ContractAddress,
) -> ContractAddress;
fn get_campaign_class_hash(self: @TContractState) -> ClassHash;
fn update_campaign_class_hash(ref self: TContractState, new_class_hash: ClassHash);
fn upgrade_campaign(
ref self: TContractState, campaign_address: ContractAddress, new_end_time: Option<u64>,
);
}
#[starknet::contract]
pub mod CampaignFactory {
use core::num::traits::Zero;
use starknet::{ContractAddress, ClassHash, syscalls::deploy_syscall, get_caller_address};
use crowdfunding::campaign::{ICampaignDispatcher, ICampaignDispatcherTrait};
use components::ownable::ownable_component;
use starknet::storage::{
Map, StorageMapReadAccess, StorageMapWriteAccess, StoragePointerReadAccess,
StoragePointerWriteAccess,
};
component!(path: ownable_component, storage: ownable, event: OwnableEvent);
#[abi(embed_v0)]
impl OwnableImpl = ownable_component::Ownable<ContractState>;
impl OwnableInternalImpl = ownable_component::OwnableInternalImpl<ContractState>;
#[storage]
struct Storage {
#[substorage(v0)]
ownable: ownable_component::Storage,
/// Store all of the created campaign instances' addresses and their class hashes
campaigns: Map<(ContractAddress, ContractAddress), ClassHash>,
/// Store the class hash of the contract to deploy
campaign_class_hash: ClassHash,
}
#[event]
#[derive(Drop, starknet::Event)]
pub enum Event {
#[flat]
OwnableEvent: ownable_component::Event,
CampaignClassHashUpgraded: CampaignClassHashUpgraded,
CampaignCreated: CampaignCreated,
ClassHashUpdated: ClassHashUpdated,
}
#[derive(Drop, starknet::Event)]
pub struct ClassHashUpdated {
pub new_class_hash: ClassHash,
}
#[derive(Drop, starknet::Event)]
pub struct CampaignClassHashUpgraded {
pub campaign: ContractAddress,
}
#[derive(Drop, starknet::Event)]
pub struct CampaignCreated {
pub creator: ContractAddress,
pub contract_address: ContractAddress,
}
pub mod Errors {
pub const CLASS_HASH_ZERO: felt252 = "Class hash cannot be zero";
pub const ZERO_ADDRESS: felt252 = "Zero address";
pub const SAME_IMPLEMENTATION: felt252 = "Implementation is unchanged";
pub const CAMPAIGN_NOT_FOUND: felt252 = "Campaign not found";
}
#[constructor]
fn constructor(ref self: ContractState, class_hash: ClassHash) {
assert(class_hash.is_non_zero(), Errors::CLASS_HASH_ZERO);
self.campaign_class_hash.write(class_hash);
self.ownable._init(get_caller_address());
}
#[abi(embed_v0)]
impl CampaignFactory of super::ICampaignFactory<ContractState> {
fn create_campaign(
ref self: ContractState,
title: ByteArray,
description: ByteArray,
goal: u256,
start_time: u64,
end_time: u64,
token_address: ContractAddress,
) -> ContractAddress {
let creator = get_caller_address();
// Create constructor arguments
let mut constructor_calldata: Array::<felt252> = array![];
((creator, title, description, goal), start_time, end_time, token_address)
.serialize(ref constructor_calldata);
// Contract deployment
let (contract_address, _) = deploy_syscall(
self.campaign_class_hash.read(), 0, constructor_calldata.span(), false,
)
.unwrap();
// track new campaign instance
self.campaigns.write((creator, contract_address), self.campaign_class_hash.read());
self.emit(Event::CampaignCreated(CampaignCreated { creator, contract_address }));
contract_address
}
fn get_campaign_class_hash(self: @ContractState) -> ClassHash {
self.campaign_class_hash.read()
}
fn update_campaign_class_hash(ref self: ContractState, new_class_hash: ClassHash) {
self.ownable._assert_only_owner();
assert(new_class_hash.is_non_zero(), Errors::CLASS_HASH_ZERO);
self.campaign_class_hash.write(new_class_hash);
self.emit(Event::ClassHashUpdated(ClassHashUpdated { new_class_hash }));
}
fn upgrade_campaign(
ref self: ContractState, campaign_address: ContractAddress, new_end_time: Option<u64>,
) {
assert(campaign_address.is_non_zero(), Errors::ZERO_ADDRESS);
let creator = get_caller_address();
let old_class_hash = self.campaigns.read((creator, campaign_address));
assert(old_class_hash.is_non_zero(), Errors::CAMPAIGN_NOT_FOUND);
assert(old_class_hash != self.campaign_class_hash.read(), Errors::SAME_IMPLEMENTATION);
let campaign = ICampaignDispatcher { contract_address: campaign_address };
campaign.upgrade(self.campaign_class_hash.read(), new_end_time프로젝트로 돌아가기