介绍
What is Cairo?
Cairo is a programming language designed for a virtual CPU of the same name. The unique aspect of this processor is that it was not created for the physical constraints of our world but for cryptographic ones, making it capable of efficiently proving the execution of any program running on it. This means that you can perform time consuming operations on a machine you don't trust, and check the result very quickly on a cheaper machine. While Cairo 0 used to be directly compiled to CASM, the Cairo CPU assembly, Cairo 1 is a higher level language. It first compiles to Sierra, an intermediate representation of Cairo which will compile later down to a safe subset of CASM. The point of Sierra is to ensure your CASM will always be provable, even when the computation fails.
What Can you Do with It?
Cairo允许你在不被信任的机器上计算值得信任的值。一个主要的用例是Starknet,这是一个针对Ethereum扩展的解决方案。以太坊是一个去中心化的区块链平台,它可以创建去中心化的应用程序,用户和d-app之间的每一次交互都会被所有参与者验证。Starknet是一个建立在以太坊之上的Layer 2。不同于以太坊让网络的所有参与者来验证所有的用户的交互,Starknet只让一个被称为验证者(prover)的节点来执行程序,并生成计算正确的证明。这些证明再由以太坊智能合约来验证,与执行交互本身相比,需要的计算能力要少得多。这种方法增加了吞吐量和降低交易成本,但保留了以太坊的安全性。
What Are the Differences with Other Programming Languages?
Cairo与传统的编程语言,尤其是在额外的性能开销和语言的主要优势方面,有很大不同。你的程序可以通过两种不同的方式执行:
-
When executed by the prover, it is similar to any other language. Because Cairo is virtualized, and because the operations were not specifically designed for maximum efficiency, this can lead to some performance overhead but it is not the most relevant part to optimize.
-
When the generated proof is verified by a verifier, it is a bit different. This has to be as cheap as possible since it could potentially be verified on many very small machines. Fortunately verifying is faster than computing and Cairo has some unique advantages to improve it even more. A notable one is non-determinism. This is a topic you will cover in more detail later in this book, but the idea is that you can theoretically use a different algorithm for verifying than for computing. Currently, writing custom non-deterministic code is not supported for the developers, but the standard library leverages non-determinism for improved performance. For example sorting an array in Cairo costs the same price as copying it. Because the verifier doesn't sort the array, it just checks that it is sorted, which is cheaper.
使该语言与众不同的另一个方面是其内存模型。在Cairo中,内存访问是不可改变的,这意味着一旦一个值被写入内存,它就不能被改变。Cairo 1提供了帮助开发者处理这些约束的抽象,但它并没有完全模拟可变性。因此,开发人员必须仔细考虑如何在他们的程序中管理内存和数据结构以优化性能。
References
- Cairo CPU Architecture: https://eprint.iacr.org/2021/1063
- Cairo, Sierra and Casm: https://medium.com/nethermind-eth/under-the-hood-of-cairo-1-0-exploring-sierra-7f32808421f5
- State of non determinism: https://twitter.com/PapiniShahar/status/1638203716535713798