• Stars
    star
    514
  • Rank 86,040 (Top 2 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created over 2 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

cairo-vm is a Rust implementation of the Cairo VM. Cairo (CPU Algebraic Intermediate Representation) is a programming language for writing provable programs, where one party can prove to another that a certain computation was executed correctly without the need for this party to re-execute the same program.

โšก Cairo-vm โšก

A faster and safer implementation of the Cairo VM in Rust

Report Bug ยท Request Feature

rust codecov license pr-welcome Telegram Chat

Table of Contents

๐Ÿ“– About

Cairo VM is the virtual machine for the Cairo language.

Previously, there was a version of Cairo VM written in Python, which was used in production.

This repository contains the newer version, written in Rust. It's faster and has safer and more expressive typing. Now in production, it has replaced the older Python version to become the primary Cairo VM.

The Cairo language

Cairo is the first production-grade platform for generating STARK proofs for general computation.

It's Turing-complete and it was created by Starkware as part of the Starknet ecosystem.

๐ŸŒ… Getting Started

Dependencies

Required

These are needed in order to compile and use the project.

Optional

These dependencies are only necessary in order to run the original VM, compile Cairo programs, and run tests.

  • make
  • PyEnv

Installation script

You can install all of the required and optional dependencies by running the script install.sh while in the repository root.

Installing project dependencies

In order to compile programs you need to install the cairo-lang package.

Running the make deps (or the make deps-macos if you are runnning in MacOS) command will create a virtual environment with all the required dependencies.

You can then activate this environment by running

. cairo-vm-env/bin/activate

๐Ÿš€ Usage

Adding cairo-vm as a dependency

You can add the following to your rust project's Cargo.toml:

cairo-vm = { version = '0.7.0'}

Running cairo-vm from CLI

To run programs from the command line, first compile the repository from the cairo-vm-cli folder:

cd cairo-vm-cli; cargo build --release; cd ..

Once the binary is built, it can be found in target/release/ under the name cairo-vm-cli.

In order to compile Cairo programs you need to activate the environment created while installing dependencies. To start it, run:

. cairo-vm-env/bin/activate

To compile a program, use cairo-compile [path_to_the_.cairo_file] --output [desired_path_of_the_compiled_.json_file]. For example:

cairo-compile cairo_programs/abs_value_array.cairo --output cairo_programs/abs_value_array_compiled.json

To run a compiled .json program through the VM, call the executable giving it the path and name of the file to be executed. For example:

target/release/cairo-vm-cli cairo_programs/abs_value_array_compiled.json --layout all_cairo

The flag --layout determines which builtins can be used. More info about layouts here.

To sum up, the following code will get you from zero to running a Cairo program:

git clone https://github.com/lambdaclass/cairo-vm.git

cd cairo-vm

cargo build --release

. cairo-vm-env/bin/activate

cairo-compile cairo_programs/abs_value_array.cairo --output cairo_programs/abs_value_array_compiled.json

target/release/cairo-vm-cli cairo_programs/abs_value_array_compiled.json --layout all_cairo

Other CLI arguments

The cairo-vm-cli supports the following optional arguments:

  • --trace_file <TRACE_FILE>: Receives the name of a file and outputs the relocated trace into it

  • --memory_file <MEMORY_FILE> : Receives the name of a file and outputs the relocated memory into it

  • --print_output : Prints the program output

  • --proof_mode: Runs the program in proof_mode

  • --secure_run: Runs security checks after execution. Enabled by default when not in proof_mode.

  • --air_public_input <AIR_PUBLIC_INPUT>: Receives the name of a file and outputs the AIR public inputs into it. Can only be used if proof_mode is also enabled.

  • --air_private_input <AIR_PRIVATE_INPUT>: Receives the name of a file and outputs the AIR private inputs into it. Can only be used if proof_mode, trace_file & memory_file are also enabled.

  • --cairo_pie_output <CAIRO_PIE_OUTPUT>: Receives the name of a file and outputs the Cairo PIE into it. Can only be used if proof_mode, is not enabled.

  • --allow_missing_builtins: Disables the check that all builtins used by the program need to be included in the selected layout. Enabled by default when in proof_mode.

For example, to obtain the air public inputs from a fibonacci program run, we can run :

  target/release/cairo-vm-cli cairo_programs/proof_programs/fibonacci.json --layout all_cairo --proof_mode --air_public_input fibonacci_public_input.json

Using hints

Currently, as this VM is under construction, it's missing some of the features of the original VM. Notably, this VM only implements a limited number of Python hints at the moment, while the Python Cairo VM allows users to run any Python code.

There are two ways to use non-standard hints in this VM:

  • Extend the cairo-vm code and build your own binary using the interface HintProcessor.
  • Use cairo-vm-py which supports running any hint in a Python interpreter.

Running a function in a Cairo program with arguments

When running a Cairo program directly using the Cairo-vm repository you would first need to prepare a couple of things.

  1. Specify the Cairo program you want to run
let program =
        Program::from_file(Path::new(&file_path), None);
  1. Instantiate the VM, the cairo_runner, the hint processor, and the entrypoint
let mut vm = VirtualMachine::new(false);

let mut cairo_runner = CairoRunner::new(&program, LayoutName::all_cairo, false);

let mut hint_processor = BuiltinHintProcessor::new_empty();

let entrypoint = program
        .identifiers
        .get(&format!("__main__.{}", &func_name))?
        .pc;
  1. Lastly, initialize the builtins and segments.
cairo_runner.initialize_builtins(&mut vm)?;
cairo_runner.initialize_segments(&mut vm, None);

When using cairo-vm with the Starknet devnet there are additional parameters that are part of the OS context passed on to the run_from_entrypoint method that we do not have here when using it directly. These parameters are, for example, initial stacks of the builtins, which are the base of each of them and are needed as they are the implicit arguments of the function.

 let _var = cairo_runner.run_from_entrypoint(
            entrypoint,
            vec![
                &MaybeRelocatable::from(2).into(),  //this is the entry point selector
                &MaybeRelocatable::from((2,0)).into() //this would be the output_ptr for example if our cairo function uses it
                ],
            false,
            &mut vm,
            &mut hint_processor,
        );

Running cairo 1 programs

To run a cairo 1 program enter in the folder cd cairo1-run and follow the cairo1-run documentation

WebAssembly Demo

A demo on how to use cairo-vm with WebAssembly can be found in examples/wasm-demo

Testing

To run the test suite you'll need cargo-llvm-cov dependency so make sure to run this command beforehand:

make deps

Now that you have the dependencies necessary to run the test suite you can run:

make test

Tracer

Cairo-vm offers a tracer which gives you a visualization of how your memory and registers change line after line as the VM executes the code. You can read more about it here

๐Ÿ“Š Benchmarks

Running a Cairo program that gets the 1.5 millionth Fibonacci number we got the following benchmarks:

Note before running the benchmark suite: the benchmark named iai_benchmark depends on Valgrind. Please make sure it is installed prior to running the iai_benchmark benchmark.

Run the complete benchmark suite with cargo:

cargo bench

Run only the criterion_benchmark benchmark suite with cargo:

cargo bench --bench criterion_benchmark

Run only the iai_benchmark benchmark suite with cargo:

cargo bench --bench iai_benchmark

Benchmark the cairo-vm in a hyper-threaded environment with the examples/hyper_threading/ crate

make hyper-threading-benchmarks

๐Ÿ“œ Changelog

Keeps track of the latest changes here.

๐Ÿ›  Contributing

The open-source community is a fantastic place for learning, inspiration, and creation, and this is all thanks to contributions from people like you. Your contributions are greatly appreciated.

If you have any suggestions for how to improve the project, please feel free to fork the repo and create a pull request, or open an issue with the tag 'enhancement'.

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feat/AmazingFeature)
  3. Commit your Changes (git commit -m 'feat: add some AmazingFeature')
  4. Push to the Branch (git push origin feat/AmazingFeature)
  5. Open a Pull Request

And don't forget to give the project a star! โญ Thank you again for your support.

You can find more detailed instructions in the CONTRIBUTING.md document.

๐ŸŒž Related Projects

  • starknet_in_rust: implementation of Starknet in Rust, powered by the cairo-vm.
  • cairo-vm-py: Bindings for using cairo-vm from Python code.

๐Ÿ“š Documentation

Cairo

Original Cairo VM Internals

We wrote a document explaining how the Cairo VM works. It can be found here.

Compilers and Interpreters

This is a list of recommended books to learn how to implement a compiler or an interpreter.

StarkNet

Computational Integrity and Zero Knowledge Proofs

Basics

ZK SNARKs

STARKs

Introduction:

Vitalik Buterin's blog series on zk-STARKs:

Alan Szepieniec's STARK tutorial:

StarkWare's STARK Math blog series:

โš–๏ธ License

This project is licensed under the Apache 2.0 license.

See LICENSE for more information.

More Repositories

1

lambdaworks

lambdaworks offers implementations for both SNARKs and STARKs provers, along with the flexibility to leverage their individual components for constructing customized SNARKs.
Rust
607
star
2

lambdaclass_hacking_learning_path

LambdaClass Hobby Club, hacking learning path handbook. The journey starts here!
224
star
3

starknet_in_rust

A Rust implementation of Starknet execution logic
Rust
171
star
4

erlings

Small exercises to get you used to reading and writing Erlang code
Erlang
164
star
5

options_backtester

Simple backtesting software for options
Jupyter Notebook
159
star
6

merkle_patricia_tree

Patricia Merkle Tree implementation in Rust
Rust
154
star
7

riak_core_tutorial

An up to date riak_core tutorial, using basho's riak_core, Erlang/OTP 23-24-25 and rebar3.
Erlang
149
star
8

STARK101-rs

STARK 101 Workshop in Rust ๐Ÿบ๐Ÿฆ€
Jupyter Notebook
131
star
9

sparkling_water_bootcamp

Public repository for excersices, challenges and all the needs of the Sparkling Water Bootcamp
123
star
10

concrete

Concrete is a simple programming language specifically crafted for creating highly scalable systems that are reliable, efficient, and easy to maintain.
Rust
123
star
11

cairo_native

A compiler to convert Cairo's intermediate representation "Sierra" code to MLIR.
Rust
115
star
12

ethereum_rust

Lambda Ethereum Rust Execution client
Rust
113
star
13

lambda_ethereum_consensus

Elixir implementation of an Ethereum consensus client, which offers high reliance & fault tolerance
Elixir
97
star
14

finance_playground

Juypter notebooks playground to explore and analyse economy and finance ideas
Jupyter Notebook
95
star
15

webrtc-server

Signaling and ICE servers for WebRTC in Erlang
Erlang
91
star
16

lambdaworks_stark_platinum

STARK Cairo prover using lambdaworks. Cairo (CPU Algebraic Intermediate Representation) is a programming language for writing provable programs, where one party can prove to another that a certain computation was executed correctly. Cairo and similar proof systems can be used to provide scalability to blockchains.
77
star
17

mina_bridge

Bridge from Mina to Ethereum
Solidity
76
star
18

evm_mlir

An EVM written with MLIR
Rust
73
star
19

AES_zero_knowledge_proof_circuit

Rust
70
star
20

holiday_pinger

Erlang + ClojureScript app to send holiday reminders
Erlang
69
star
21

stark_compass_explorer

Stark Compass: the only open source explorer
Elixir
68
star
22

mirra_backend

Multiplayer 2D physics engine, matchmaking, market and leaderboard for 2D and 3D Games
Elixir
61
star
23

erlang-katana

๐Ÿ‘Œ erlang grab bag of useful functions. it should have been called swiss army knife but katanas are more deadlier ;)
Erlang
61
star
24

cairo-vm_in_go

cairo-vm_in_go is a Go implementation of the Cairo VM. Cairo (CPU Algebraic Intermediate Representation) is a programming language for writing provable programs, where one party can prove to another that a certain computation was executed correctly without the need for this party to re-execute the same program.
Go
56
star
25

libtorrent-rs

A Rust implementation of the BitTorrent V2 protocol
Rust
55
star
26

yet-another-swap

YAS is Yet Another Swap on Starknet but bringing the best prices and yield to Degens.
Cairo
54
star
27

starknet_tendermint_sequencer

Starknet sequencer built with Tendermint Core
Rust
53
star
28

zksync_era_precompiles

Yul precompile library to speedup elliptic curves operations.
Rust
51
star
29

champions_of_mirra

Champions of Mirra game codebase
C#
42
star
30

circom_export_to_cairo

Export Circom verifier to Cairo
Solidity
42
star
31

starknet_stack

Starknet Stack let's you easily create new Cairo Starknet chains with their own sequencers, provers and verifiers
Rust
42
star
32

throttle

Erlang/OTP application to rate limit resource access
Erlang
40
star
33

cairo-by-example

cairo-by-example.com
Shell
38
star
34

pinocchio_lambda_vm

Zero Knowledge Virtual Machine from scratch implementing Pinocchio
Rust
36
star
35

buzzconf

A conference by devs for devs. Functional Programming, Distributed Systems, Big Data and Machine Learning Conference in Buenos Aires, Argentina
HTML
34
star
36

zksync-web3-rs

Rust
33
star
37

julia_koans

Small exercises to get you used to reading and writing Julia code!
Julia
31
star
38

noir_backend_using_gnark

A Noir's backend implementation using Gnark
Go
31
star
39

cairo-vm-py

cairo-rs-py adds Python bindings to the cairo-rs Cairo VM
Rust
23
star
40

lambdaworks_kzg

An ABI compatible for KZG EIP-4844 in Rust
Rust
22
star
41

aleo_lambda_vm

Arkworks implementation of the VM of Aleo verifiable computing model built by LambdaClass
Rust
21
star
42

simpleworks

Arkworks made simple for us: the non cryptographer software plumbers
Rust
20
star
43

era_vm

EraVM implementation
Rust
19
star
44

cairo-vm.c

cairo-vm_in_C is a C implementation of the Cairo VM. Cairo (CPU Algebraic Intermediate Representation) is a programming language for writing provable programs, where one party can prove to another that a certain computation was executed correctly without the need for this party to re-execute the same program.
C++
19
star
45

programming_bitcoin_in_rust

Implementing the book "Programming Bitcoin" in Rust
Rust
17
star
46

tornado_cash_anonymity_tool

Anonymity Research Tools for TCash Users
Jupyter Notebook
17
star
47

aleo_lambda_blockchain

Tendermint implementation of the blockchain of Aleo verifiable computing model built by LambdaClass
Rust
16
star
48

starknet_prover

15
star
49

lambdaworks_exercises

Contains several examples and challenges to use Lambdaworks
Rust
14
star
50

austral.rs

An implementation of the Austral language compiler in Rust
Rust
14
star
51

aleo_minimum_anti_collusion_infrastructure

Aleo's Minimum Anti-Collusion Infrastructure / MACI
Rust
13
star
52

starknet_rollup_on_bitcoin

Soverign rollup based on Rollkit, Cairo VM for the application layer and Bitcoin as a DA layer
Rust
13
star
53

lambda_consensus

Ethereum Consensus Client
12
star
54

starknet_kraken

Kraken is a Starknet modular decentralized sequencer implementation.
Rust
11
star
55

cairo_karnak

Cairo bytecode compiler
10
star
56

data_etudes

LambdaClass statistics, machine learning and data science etudes
Jupyter Notebook
10
star
57

reconnections

We were tired of implementing a reconnection system for our database clients so we created this
Erlang
10
star
58

find_peers

Find other erlang peers in the same subnet
Erlang
9
star
59

PLONK101-rs

9
star
60

elephant_in_the_room

Simple wordpress replacement coded in Elixir + Phoenix + Ecto + PostgreSQL + Docker
CSS
9
star
61

zksync_local_stack

Makefile
9
star
62

game_of_life_wasm

Conway's Game of Life in Rust and WebAssembly
Rust
8
star
63

elixir_riak_core

Wrapper to Riak Core for Elixir
Elixir
8
star
64

cairo_codegen-rs

A Rust library providing a builder API to generate Cairo code
8
star
65

zkRust

Rust
8
star
66

lambda_msm_fpga

Low level (VHDL) hardware description for MSM acceleration over FPGA
Python
8
star
67

curse_of_mirra_assets

Open source game assets: 3D models, 2d concept art, lore, music and more!
8
star
68

pinpon

๐Ÿ“ lambdaclass ping pong tournament and player ranking
Python
7
star
69

ieeextreme

Course material for students who want to go from zero to participating in the IEEExtreme competence using Python
Jupyter Notebook
7
star
70

entropy_hacking_learning_path

Entropy1729's Learning path
7
star
71

metal_playground

A repo for learning how to parallelize computations in the GPU using Apple's Metal, in Rust.
Rust
7
star
72

aleo_roulette

Elixir
6
star
73

cairo_finance

Cairo finance utilities
Cairo
6
star
74

lager_logstash_backend

Send lager logs to logstash
Erlang
6
star
75

lambdaworks_plonk_prover

6
star
76

bonobot

accept the mystery
Python
6
star
77

beam_prometheus_exporter

Add this to your release to get standard erlang metrics in prometheus/grafana
Erlang
6
star
78

million_requests_per_second

Trying to achieve a few millions requests per second with different languages, libraries and protocol
Ruby
6
star
79

mithril-oxide

Bindings to MLIR using the full C++ API
Rust
6
star
80

fuzzing_examples

A collection of fuzzers built using Honggfuzz and Cargofuzz tools
Rust
5
star
81

data_science_exercise

Data science exercise
Jupyter Notebook
5
star
82

blockaderl

Blockade docker API wrapper written in Erlang
Erlang
5
star
83

starknet_orb

5
star
84

ethereum_war_game_tooling

We are slow while using the UI/UX of crypto wallets so we created our CLI version
Elixir
5
star
85

zk_stack_cli

CLI tool for ZKsync, built using zksync-ethers-rs SDK
Rust
5
star
86

erlang_log_to_kibana_example

Redirect Erlang shell output to kibana via logstash
Shell
5
star
87

cairo-rs-wasm

Rust
5
star
88

starknet-replay

Provides a way of reading a real Starknet State, so you can re-execute an existing transaction in any of the Starknet networks in an easy way
Rust
5
star
89

aggregation_aligned_layer

Rust
4
star
90

guidelines

Design and coding standards for LambdaClass
4
star
91

tendermint_consensus

Tendermint Consensus is a minimalistic implementation of the BFT consensus algorithm to securely replicate state machines on multiple machines.
4
star
92

go-http-ipfs

HTTP server in Go to interact with a local IPFS node
Go
4
star
93

cairo_wnn

Cairo Weightless Neural Network
4
star
94

chaos_monkey_ex

A Chaos Monkey for Elixir that kills random processes
Elixir
3
star
95

wasm2cairo

3
star
96

merkletree_leo

3
star
97

concrete-ml-fuzzer

A differential fuzzer for `concrete-ml` and `scikit-learn`
Python
3
star
98

consensus-workbench

Proof of concept Rust implementations for various distributed systems protocols
Rust
3
star
99

lambcast

A Farcaster client implementation in Elixir
Elixir
3
star
100

zksync_seaport

Seaport implementation on zkSync Era. Seaport is a marketplace protocol for safely and efficiently buying and selling NFTs.
Solidity
3
star