Starknet 백서

Starknet

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 73쪽 중 18쪽

of super::IMathUtils<ContractState> { fn add(ref self: ContractState, x: u32, y: u32) -> u32 { IMathUtilsLibraryDispatcher { class_hash: self.lib_class_hash.read() }.add(x, y) } #[abi(embed_v0)] fn set_class_hash(ref self: ContractState, class_hash: starknet::ClassHash) { self.lib_class_hash.write(class_hash); } } } ``` # Plugins Source: https://docs.starknet.io/build/starknet-by-example/advanced/plugins Compiler plugins in Cairo are a way to generate additional code for specific items during the compilation process. There are already a set of core plugins that you may have already used, such as `#[derive]`, `#[cfg]`, `#[generate_trait]`, etc. It is possible to create your own plugins in Cairo. You can learn more about how to do that in the [hello-cairo-plugin](https://github.com/piwonskp/hello-cairo-plugin) repository. # Understanding Sierra: From High-Level Cairo to Safe CASM Source: https://docs.starknet.io/build/starknet-by-example/advanced/sierra-ir Sierra (Safe Intermediate REpresentAtion) is a linear intermediate representation of Cairo instructions, designed to bridge the gap between high-level Cairo 1 intermdiate and low-level Cairo Assembly (CASM). Sierra can be compiled to a subset of CASM, known as `Safe CASM{:md}`. Sierra ensures that programs are always **provable** by preventing the compilation of programs with infinite loops or invalid constraints. ### From Cairo 1 to Sierra Before Starknet Alpha v0.11.0, developers wrote contracts in Cairo 0, which compiled directly to Cairo Assembly (CASM), and contract classes were submitted to the sequencer via `DECLARE` transactions. This approach had risks, as the sequencer could not determine whether a given transaction would fail without executing it, and therefore could not charge fees for failed transactions. Cairo 1 introduced contract class compilation to this new Sierra intermediate representation instead of directly compiling to CASM. The Sierra code is then submitted to the sequencer, compiled down to CASM, and finally executed by the Starknet OS. Using Sierra ensures that all transactions (including failed ones) are provable, and allows sequencers to charge fees for all submitted transactions, making DoS attacks significantly more expensive. ### Compilation Pipeline ``` Cairo 1.0 Source (High-level) | | with Cairo-to-Sierra Compiler V Sierra IR (Safe, Provable Code) | | with Sierra-to-CASM Compiler (Run by Sequencer) V CASM (Cairo Assembly) | | with CairoVM Execution V STARK Proofs (Proof Generation) ``` At its core, Sierra's compilation process is focused on safety and efficiency. Cairo 1 uses a linear type system and a non-deterministic, immutable, contiguous memory model, which guarantees that dereferencing never fails. Sierra transforms loops into recursion and keeps track of gas usage, which prevents infinite loops. <Note> If you're interested in really understanding how the compilation works under the hood, check out the [cairo-compiler-workshop](https://github.com/software-mansion-labs/cairo-compiler-workshop). </Note> ### Anatomy of a Sierra Program ### Type Declarations Sierra, as a Cairo representation, also uses a **linear type system**, where each value **must be used exactly once**. During the compilation, a unique identifier is assigned to each type. When types can safely be used multiple times, they need to be duplicated using the `dup` instruction, which will assign two new identifiers to preserve linearity. Type declaration is done with the following syntax: ```rust theme={null} type type_id = concrete_type; ``` <Info> In addition, each type has a set of attributes that describe how it can be used: * storable * droppable * duplicatable * zero\_sized They are added in the type declaration: ```rust theme={null} type type_id = concrete_type [storable: bool, drop: bool, dup: bool, zero_sized: bool] ``` </Info> ### Library Function Declarations Sierra comes with a set of built-in functions (`libfuncs`) that represent the call to low-level units of code known to be safe. After type declarations, a Sierra program must define all the libfuncs used in the program along with their expected input types. Libfunc declaration is done with the following syntax: ```rust theme={null} libfunc libfunc_id = libfunc_name<input_types>; ``` <Note> While this section is generic, Starknet uses an allowed [list](https://github.com/starkware-libs/cairo/tree/main/crates/cairo-lang-starknet-classes/src/allowed_libfuncs_lists) of libfuncs. </Note> ### Statements This section shows the sequence of operations that occur during execution, describing the actual logic of the program. A statement either invokes a libfunc or returns a value. Statements are declared with the following syntax: ```rust theme={null} libfunc_id<input_types>(input_variables) -> (output_variables); ``` To return a value, we use the `return(variable_id)` statement. ### User Defined Functions Declarations At the end of a Sierra program, each user-defined function is declared with a unique identifier and the statement index where the function starts. This provides information about the function, such as its signature, while the implementation is defined in the statements section. An user defined function is declared with the following syntax: ```rust theme={null} function_id@statement_index(parameters: types) -> (return_types); ``` ## Simple Sierra Program Breakdown Let's go through the following Cairo program: ```rust theme={null} fn add_numbers(a: felt252, b: felt252) -> felt252 { a + b } ``` It compiles to the following Sierra code: ```rust theme={null} type felt252 = felt252 [storable: true, drop: true, dup: true, zero_sized: false]; libfunc felt252_add = felt252_add; libfunc store_temp<felt252> = store_temp<felt252>; felt252_add([0], [1]) -> ([2]); // 0 store_temp<felt252>([2]) -> ([2]); // 1 return([2]); // 2 sierra_ir::add_numbers@0([0]: felt252, [1]: felt252) -> (felt252); ``` Type Declarations: * `felt252`: Represents the field element type Libfunc Declarations: * `felt252_add`: Performs addition on field elements * `store_temp<felt252>`: Temporarily stores the result Statements Section: * Statement 0: calls the `felt252_add` libfunc to add the values from memory cells 0 and 1, storing the result in memory cell 2 * Statement 1: calls the `store_temp<felt252>` libfunc to prepare the result for the return statement * Statement 2: returns the value from memory cell 2 User Defined Functions: * `add_numbers`: Takes two `felt252` types in memory cells 0 and 1 and returns a `felt252` value by starting at statement 0 <Info> To enable Sierra code generation in a human-readable format, add the `sierra-text` flag to the library target in your `Scarb.toml{:md}` file: ```toml theme={null} [lib] sierra-text = true ``` </Info> ### Storage Variables Smart Contract Sierra Code You can find a more complex example of the [compiled Sierra code](./sierra_ir_storage_contract) of the [Storage Variables Example](../basic/variables#storage-variables). ## Further Reading * [Under the hood of Cairo 1.0: Exploring Sierra](https://www.nethermind.io/blog/under-the-hood-of-cairo-1-0-exploring-sierra-part-1) * [Under the hood of Cairo 2.0: Exploring Sierra](https://www.nethermind.io/blog/under-the-hood-of-cairo-1-0-exploring-sierra-part-2) * [Under the hood of Cairo 1.0: Exploring Sierra](https://www.nethermind.io/blog/under-the-hood-of-cairo-1-0-exploring-sierra-part-3) * [Cairo and Sierra](https://docs.starknet.io/architecture-and-learn/architecture/smart-contracts/cairo-and-sierra/) * [Sierra - Deep Dive](https://www.starknet.io/blog/sierra-deep-dive-video/) * [Cairo and MLIR](https://blog.lambdaclass.com/cairo-and-mlir/) # ECDSA verification Source: https://docs.starknet.io/build/starknet-by-example/advanced/signature-verification This is the Cairo adaptation of the [Solidity by Example - Verifying Signature](https://solidity-by-example.org/signature/). Messages can be signed off chain and then verified on chain using a smart contract. ```rust theme={null} use core::starknet::eth_address::EthAddress; use starknet::secp256_trait::{Signature}; // How to Sign and Verify // # Signing // 1. Create message to sign // 2. Hash the message // 3. Sign the hash (off chain, keep your private key secret) #[starknet::interface] trait IVerifySignature<TContractState> { fn get_signature(self: @TContractState, r: u256, s: u256, v: u32) -> Signature; fn verify_eth_signature( self: @TContractState, eth_address: EthAddress, msg_hash: u256, r: u256, s: u256, v: u32, ); fn recover_public_key( self: @TContractState, eth_address: EthAddress, msg_hash: u256, r: u256, s: u256, v: u32, ); } #[starknet::contract] mod verifySignature { use super::IVerifySignature; use core::starknet::eth_address::EthAddress; use starknet::secp256k1::Secp256k1Point; use starknet::secp256_trait::{Signature, signature_from_vrs, recover_public_key}; use starknet::eth_signature::{verify_eth_signature, public_key_point_to_eth_address}; #[storage] struct Storage { msg_hash: u256, signature: Signature, eth_address: EthAddress, } #[abi(embed_v0)] impl VerifySignature of IVerifySignature<ContractState> { /// This function returns the signature struct for the given parameters. /// /// # Arguments /// /// * `r` - The R component of the signature. /// * `s` - The S component of the signature. /// * `v` - The V component of the signature. /// /// # Returns /// /// * `Signature` - The signature struct. fn get_signature(self: @ContractState, r: u256, s: u256, v: u32) -> Signature { // Create a Signature object from the given v, r, and s values. let signature: Signature = signature_from_vrs(v, r, s); signature } /// Verifies an Ethereum signature. /// /// # Arguments /// /// * `eth_address` - The Ethereum address to verify the signature against. /// * `msg_hash` - The hash of the message that was signed. /// * `r` - The R component of the signature. /// * `s` - The S component of the signature. /// * `v` - The V component of the signature. fn verify_eth_signature( self: @ContractState, eth_address: EthAddress, msg_hash: u256, r: u256, s: u256, v: u32, ) { let signature = self.get_signature(r, s, v); verify_eth_signature(:msg_hash, :signature, :eth_address); } /// Recovers the public key from an Ethereum signature and verifies that it matches the /// given Ethereum address. /// /// # Arguments /// /// * `eth_address` - The Ethereum address to verify the signature against. /// * `msg_hash` - The hash of the message that was signed. /// * `r` - The R component of the signature. /// * `s` - The S component of the signature. /// * `v` - The V component of the signature. fn recover_public_key( self: @ContractState, eth_address: EthAddress, msg_hash: u256, r: u256, s: u256, v: u32, ) { let signature = self.get_signature(r, s, v); let public_key_point = recover_public_key::<Secp256k1Point>(msg_hash, signature) .unwrap(); let calculated_eth_address = public_key_point_to_eth_address(:public_key_point); assert(calculated_eth_address == eth_address, 'Invalid Address'); } } } ``` # Storage optimisation Source: https://docs.starknet.io/build/starknet-by-example/advanced/store-using-packing A smart contract has a limited amount of **storage slots**. Each slot can store a single `felt252` value. Writing to a storage slot has a cost, so we want to use as few storage slots as possible. In Cairo, every type is derived from the `felt252` type, which uses 252 bits to store a value. This design is quite simple, but it does have a drawback: it is not storage efficient. For example, if we want to store a `u8` value, we need to use an entire slot, even though we only need 8 bits. ## Packing When storing multiple values, we can use a technique called **packing**. Packing is a technique that allows us to store multiple values in a single `felt252` value. This is done by using the bits of the `felt252` value to store multiple values. For example, if we want to store two `u8` values, we can use the first 8 bits of the `felt252` value to store the first `u8` value, and the last 8 bits to store the second `u8` value. This way, we can store two `u8` values in a single `felt252` value. Cairo provides a built-in store using packing that you can use with the `StorePacking` trait. ```rust theme={null} trait StorePacking<T, PackedT> { fn pack(value: T) -> PackedT; fn unpack(value: PackedT) -> T; } ``` This allows us to store the type `T` by first packing it into the type `PackedT` with the `pack` function, and then storing the `PackedT` value with it's `Store` implementation. When reading the value, we first retrieve the `PackedT` value, and then unpack it into the type `T` using the `unpack` function. Here's an example of storing a `Time` struct with two `u8` values using the `StorePacking` trait: ```rust theme={null} #[derive(Copy, Serde, Drop)] pub struct Time { pub hour: u8, pub minute: u8, } #[starknet::interface] pub trait ITime<TContractState> { fn set(ref self: TContractState, value: Time); fn get(self: @TContractState) -> Time; } #[starknet::contract] mod TimeContract { use starknet::storage::{StoragePointerWriteAccess, StoragePointerReadAccess}; use super::Time; use starknet::storage_access::StorePacking; #[storage] struct Storage { time: Time, } impl TimePackable of StorePacking<Time, felt252> { fn pack(value: Time) -> felt252 { let msb: felt252 = 256 * value.hour.into(); let lsb: felt252 = value.minute.into(); msb + lsb } fn unpack(value: felt252) -> Time { let value: u16 = value.try_into().unwrap(); let (q, r) = DivRem::div_rem(value, 256_u16.try_into().unwrap()); let hour: u8 = Into::<u16, felt252>::into(q).try_into().unwrap(); let minute: u8 = Into::<u16, felt252>::into(r).try_into().unwrap(); Time { hour, minute } } } #[abi(embed_v0)] impl TimeContract of super::ITime<ContractState> { fn set(ref self: ContractState, value: Time) { // This will call the pack method of the TimePackable trait // and store the resulting felt252 self.time.write(value); } fn get(self: @ContractState) -> Time { // This will read the felt252 value from storage // and return the result of the unpack method of the TimePackable trait return self.time.read(); } } } ``` # Structs as mapping keys Source: https://docs.starknet.io/build/starknet-by-example/advanced/struct-mapping-key In order to use structs as mapping keys, you can use `#[derive(Hash)]` on the struct definition. This will automatically generate a hash function for the struct that can be used to represent the struct as a key in a `Map`. Consider the following example in which we would like to use an object of type `Pet` as a key in a `Map`. The `Pet` struct has three fields: `name`, `age` and `owner`. We consider that the combination of these three fields uniquely identifies a pet. ```rust theme={null} #[derive(Copy, Drop, Serde, Hash)] pub struct Pet { pub name: felt252, pub age: u8, pub owner: felt252, } #[starknet::interface] pub trait IPetRegistry<TContractState> { fn register_pet(ref self: TContractState, key: Pet, timestamp: u64); fn get_registration_date(self: @TContractState, key: Pet) -> u64; } #[starknet::contract] pub mod PetRegistry { use super::Pet; use starknet::storage::{Map, StorageMapReadAccess, StorageMapWriteAccess}; #[storage] struct Storage { registration_time: Map::<Pet, u64>, } #[abi(embed_v0)] impl PetRegistry of super::IPetRegistry<ContractState> { fn register_pet(ref self: ContractState, key: Pet, timestamp: u64) { self.registration_time.write(key, timestamp); } fn get_registration_date(self: @TContractState, key: Pet) -> u64 { self.registration_time.read(key) } } } ``` # Verifying ZK proofs Source: https://docs.starknet.io/build/starknet-by-example/advanced/verify-proofs This example shows how to verify SNARK proofs on Starknet using a practical example of a token minting system that requires proof of knowledge of a secret. ## ZK-SNARKs **zk-SNARKs** (Zero-Knowledge Succinct Non-Interactive Arguments of Knowledge) are cryptographic proofs that enable one party (the *prover*) to demonstrate knowledge of specific information to another party (the *verifier*) without revealing the information itself. * **Zero-Knowledge (Privacy)**: Ensures computation inputs remain private while proving correctness. The proof only reveals the statement's validity, not the underlying data. * **Succinctness**: Proofs remain small regardless of statement complexity, with verification being computationally cheaper than proof generation. This enables efficient verification of large computations. * **Non-Interactivity**: Proofs require no further communication between prover and verifier after generation, ideal for decentralized environments. * **Integrity**: Guarantees computation correctness without requiring re-execution. ### Common Use Cases * **Identity Verification**: Prove attributes (age, nationality, membership) without revealing actual details. Enables trustless verification without storing sensitive data. * **Scalable Rollups**: Bundle multiple transaction proofs into a single proof, eliminating the need for re-execution. * **Proof of Reserves**: Demonstrate sufficient funds for service eligibility without disclosing actual balances. ## Example: Proof of Secret with Replay Attack Protection This example shows how to implement a token minting system where users can mint tokens by proving knowledge of a secret password without revealing it. The system includes protection against replay attacks, ensuring each proof is unique to its generator. We will use the following: * **Circom**: Domain-specific language for defining arithmetic circuits, the foundation of zk-SNARKs. * **Groth16**: A pairing-based zk-SNARK system that provides the mathematical framework for proof generation and verification. * **Snarkjs**: JavaScript library for generating and verifying zk-SNARK proofs. * **Garaga**: Enables efficient elliptic curve operations on Starknet, including Groth16 smart contract verifier generation. ### 1. Circuit Definition Create a circuit that: * Takes 3 inputs: * User address (public) * Password hash (public) * Password in plain text (private) * Computes the hash of the plain text password * Compares it with the public hash * Generates a user-specific proof to prevent replay attacks ```solidity theme={null} pragma circom 2.0.0; include "../node_modules/circomlib/circuits/poseidon.circom"; template PasswordCheck() { // Public inputs signal input userAddress; signal input pwdHash; // Private input signal input pwd; // (Public) output signal output uniqueToUser; // Make sure password is the correct one by comparing its hash to the expected known hash component hasher = Poseidon(1); hasher.inputs[0] <== pwd; hasher.out === pwdHash; // Compute a number unique to user so that other users can't simply copy and use same proof // but instead have to execute this circuit to generate a proof unique to them component uniqueHasher = Poseidon(2); uniqueHasher.inputs[0] <== pwdHash; uniqueHasher.inputs[1] <== userAddress; uniqueToUser <== uniqueHasher.out; } component main {public [userAddress, pwdHash]} = PasswordCheck(); ``` ### 2. Circuit Compilation The circuit computes the hash of the plain text password and compares the result to the publicly known hash of the password. This equality assertion is one of the constraints set by the circuit. The rest of the code is to generate a proof unique to the user to avoid replay attacks (more about it later). ```bash [Terminal] theme={null} mkdir target circom src/circuit/circuit.circom -l node_modules --r1cs --wasm --output target ``` ### 3. Trusted Setup The **trusted setup** is a phase in the zk-SNARK protocol where cryptographic parameters, known as a *proving key* and a *verification key*, are generated. The
프로젝트로 돌아가기