-
Notifications
You must be signed in to change notification settings - Fork 14
/
.cursorrules
499 lines (386 loc) · 12.9 KB
/
.cursorrules
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
The following files define the rule and spirit of the Keth codebase.
When implementing any feature or making any change, follow the patterns described here.
# Keth codebase architecture
This codebase is an EVM implementation written in Cairo Zero.
## Overview
The architecture system bridges Python and Cairo through three components:
1. Type Generation (`args_gen.py`): Converts Python values to Cairo memory
layout according to Cairo's memory model and type system rules.
2. Serialization (`serde.py`): Interprets Cairo memory segments and reconstructs
equivalent Python values, enabling bidirectional conversion.
3. Test Runner (`runner.py`): Orchestrates program execution, manages memory
segments, and handles type conversions for function outputs between Python
and Cairo.
## Type System Design
Adding new types to the Cairo type system requires implementing both the Cairo
memory representation and Python conversion logic. The Cairo implementation must
follow the established patterns for memory layout and pointer relationships,
while the Python side requires bidirectional conversion handling.
When implementing the Cairo equivalent of a python type, you should always map
the cairo type to the python type in `_cairo_struct_to_python_type` inside
`args_gen.py`.
### Error Types Pattern
Error types should:
1. Be defined in the separate `cairo/ethereum/cancun/vm/exceptions.cairo` file.
2. Follow the Bytes pattern for error messages:
```cairo
from ethereum_types.bytes import Bytes
struct StackUnderflowError {
value: Bytes,
}
struct StackOverflowError {
value: Bytes,
}
```
3. Return `cast(0, ErrorType*)` for success cases
4. Create a new Bytes with message for error cases. The error message can be
empty.
```cairo
tempvar err = StackUnderflowError(Bytes(new BytesStruct(cast(0, felt*), 0)));
```
### Implicit Arguments Pattern
When working with mutable data structures (stack, memory, state, etc.):
1. Use implicit arguments for the structure being modified
2. Return the error type if the operation can fail
Example:
````cairo
func push{stack: Stack}(value: U256) -> StackOverflowError {
# Only return error
}
3. Return the error type as the last element of the tuple if the operation can either return a value or fail
Example:
```cairo
func pop{stack: Stack}() -> (U256, StackUnderflowError) {
# Return both value and error
}
### Test Structure Pattern
Tests should:
1. Be organized in classes (e.g. `TestStack`)
2. Use the `cairo_run` fixture to run Cairo functions
3. Compare Python and Cairo implementations for equivalence
4. Use hypothesis for property-based testing
5. Test both success and error cases
6. Have the same path in the tests folder as the source file (e.g.
`ethereum/crypto/hash.cairo` -> `tests/ethereum/crypto/test_hash.py`)
To run tests, use pytest with `uv`: `uv run pytest -k <test_name>`.
Example:
```python
class TestFeature:
@given(...)
def test_operation(self, cairo_run, ...):
# Test success case
result_cairo = cairo_run("operation", ...)
result_py = operation(...)
assert result_cairo == result_py
@given(...)
def test_error(self, cairo_run, ...):
# Test error case
with pytest.raises(ErrorType):
cairo_run("operation", ...)
with pytest.raises(ErrorType):
operation(...)
````
### Type Wrapping Pattern
Complex types use pointer-based structures for consistent memory allocation. Two
main variants exist:
1. Simple wrapper (fixed-size):
```cairo
struct Bytes0 {
value: felt,
}
```
2. Complex wrapper (variable-size):
```cairo
struct Bytes {
value: BytesStruct*,
}
struct BytesStruct {
data: felt*,
len: felt,
}
```
### Optional Values Pattern
Null values implementation uses pointer semantics:
1. Simple types (direct value):
```cairo
struct U64 {
value: felt
}
```
A `null` U64 is represented by a U64 pointer with a value of 0.
2. Complex types (pointer-based):
```cairo
struct U256 {
value: U256Struct*, // null when pointer is 0
}
```
A `null` U256 is represented by the inner U256Struct\* having a value of 0.
When integrating optional values in other types, we thus have two cases:
1. (simple type) We represent the option as a pointer to the value, with a value
of 0 representing a null value.
2. (complex type) We represent the option as the type itself, as it is already a
pointer-based type.
To make it clear to the reader, we define a type alias
`using OptionalAddress = Address*` (simple type) and
`using OptionalBytes = Bytes` (complex type).
```cairo
using OptionalAddress = Address*;
using OptionalEvm = Evm;
struct MessageStruct {
// ... other fields ...
code_address: OptionalAddress,
parent_evm: OptionalEvm,
}
```
### Union Types Pattern
Unions implement a pointer-based variant system. Real example from RLP encoding,
`Union[Sequence["Simple"], bytes]` and
`Union[Sequence["Extended"], bytearray, bytes, uint, FixedUnsigned, str, bool]`:
```cairo
// Simple variant with two possibilities
struct Simple {
value: SimpleEnum*,
}
struct SimpleEnum {
sequence: SequenceSimple, // First variant
bytes: Bytes, // Second variant
}
// Extended variant with multiple possibilities
struct Extended {
value: ExtendedEnum*,
}
struct ExtendedEnum {
sequence: SequenceExtended,
bytearray: Bytes,
bytes: Bytes,
uint: Uint*,
fixed_uint: Uint*,
str: String,
bool: Bool*,
}
```
Implementation pattern:
1. Outer struct contains pointer to enum struct
2. Enum struct contains all possible variants.
3. Only one variant is active (non-zero) at a time
4. Variant construction uses explicit constructors:
```cairo
// Example constructor for a variant
func bytes(value: Bytes) -> Extended {
tempvar extended = Extended(
new ExtendedEnum(
sequence=SequenceExtended(cast(0, SequenceExtendedStruct*)),
bytearray=Bytes(cast(0, BytesStruct*)),
bytes=value, // Active variant
uint=cast(0, Uint*),
fixed_uint=cast(0, Uint*),
str=String(cast(0, StringStruct*)),
bool=cast(0, Bool*),
),
);
return extended;
}
```
### Write-once Collections Pattern
The inner struct is a struct with two fields: a pointer to the collection's data
segment, and the length of the collection.
```cairo
struct Bytes {
value: BytesStruct*,
}
struct BytesStruct {
data: felt*,
len: felt
}
```
We can also make collections of collections, like a tuple of bytes.
```cairo
struct TupleBytesStruct {
data: Bytes*, // Tuple data
len: felt, // Number of elements in the tuple
}
struct TupleBytes {
value: TupleBytesStruct*,
}
```
### Mappings Pattern
Implementation using DictAccess pattern from the standard library. For the
`Mapping[Bytes, Bytes]` type, the corresponding Cairo struct is:
```cairo
struct BytesBytesDictAccess {
key: Bytes,
prev_value: Bytes,
new_value: Bytes,
}
struct MappingBytesBytesStruct {
dict_ptr_start: BytesBytesDictAccess*,
dict_ptr: BytesBytesDictAccess*,
}
struct MappingBytesBytes {
value: MappingBytesBytesStruct*,
}
```
Key implementation notes:
- Keys are stored as pointers, thus querying a key is a pointer equality check,
not a value equality check.
- In the future, we consider using key hashes for content-based comparison
rather than pointer comparison.
### Mutable Collections Pattern
Cairo's write-once memory model necessitates implementing mutable collections
through a dictionary-based state tracking system. The implementation uses a
two-pointer dictionary structure to maintain state changes while preserving the
functional programming paradigm.
The base structure consists of an outer pointer wrapper and an inner struct
containing dictionary pointers and length:
```cairo
struct MutableCollection {
value: CollectionStruct*,
}
struct CollectionStruct {
dict_ptr_start: CollectionDictAccess*,
dict_ptr: CollectionDictAccess*,
len: felt,
}
struct CollectionDictAccess {
key: KeyType,
prev_value: ValueType,
new_value: ValueType,
}
```
The dictionary implementation maintains state through a series of memory
segments. Each mutation operation creates a new dictionary entry rather than
modifying existing memory. The `dict_ptr_start` maintains a reference to the
initial state while `dict_ptr` advances with each mutation, creating a
modification history in the memory segment between these pointers.
For example, the Stack implementation for the EVM uses this pattern to maintain
a mutable stack of U256 values:
```cairo
struct Stack {
value: StackStruct*,
}
struct StackStruct {
dict_ptr_start: StackDictAccess*,
dict_ptr: StackDictAccess*,
len: felt,
}
struct StackDictAccess {
key: felt, // Stack index
prev_value: U256, // Previous value at index
new_value: U256, // New value at index
}
```
Mutation operations create new dictionary entries through the Cairo dictionary
API:
```cairo
func push{stack: Stack}(value: U256) {
let len = stack.value.len;
dict_write(len, cast(value.value, felt));
tempvar stack = Stack(
new StackStruct(
dict_ptr_start=stack.value.dict_ptr_start,
dict_ptr=new_dict_ptr,
len=len + 1
)
);
# `stack` is returned implicitly
}
```
### Real-World Example: TransientStorage Implementation
The TransientStorage implementation demonstrates how these patterns come
together in a real-world component. TransientStorage is a key part of the EVM,
managing temporary storage that persists between message calls within a
transaction. We will base our implementation on the `ethereum/execution-specs`
repository, in `ethereum/cancun/state.py`.
In Python, TransientStorage is a dataclass with two fields:
- `_tries`: A dictionary mapping addresses to tries
- `_snapshots`: A list of dictionaries for state history
```python
@dataclass
class TransientStorage:
"""
Contains all information that is preserved between message calls
within a transaction.
"""
_tries: Dict[Address, Trie[Bytes, U256]] = field(default_factory=dict)
_snapshots: List[Dict[Address, Trie[Bytes, U256]]] = field(default_factory=list)
```
Here is the Cairo implementation:
1. Type Wrapping Pattern: Following the complex wrapper pattern, we define the
TransientStorage structure with nested pointer-based types:
```cairo:cairo/ethereum/cancun/state.cairo
struct TransientStorage {
value: TransientStorageStruct*,
}
struct TransientStorageStruct {
_tries: MappingAddressTrieBytesU256, // Dict[Address, Trie[Bytes, U256]]
_snapshots: TransientStorageSnapshots, // List[Dict[Address, Trie[Bytes, U256]]]
}
```
2. Mappings Pattern: The `_tries` field uses the dictionary-based mapping
pattern to store key-value pairs for each address:
```cairo:cairo/ethereum/cancun/state.cairo
struct AddressTrieBytesU256DictAccess {
key: Address,
prev_value: TrieBytesU256,
new_value: TrieBytesU256,
}
struct MappingAddressTrieBytesU256Struct {
dict_ptr_start: AddressTrieBytesU256DictAccess*,
dict_ptr: AddressTrieBytesU256DictAccess*,
}
struct MappingAddressTrieBytesU256 {
value: MappingAddressTrieBytesU256Struct*,
}
```
3. Write-once Collections Pattern: The `_snapshots` field uses the collection
pattern to maintain a history of storage states:
```cairo:cairo/ethereum/cancun/state.cairo
struct TransientStorageSnapshotsStruct {
data: MappingAddressTrieBytesU256*, // Array of mappings
len: felt,
}
struct TransientStorageSnapshots {
value: TransientStorageSnapshotsStruct*,
}
```
4. Python Integration:
We integrate the new external types to the Cairo <> Python type mapping:
```python:tests/utils/args_gen.py
_cairo_struct_to_python_type: Dict[Tuple[str, ...], Any] = {
# ... existing mappings ...
("ethereum", "cancun", "state", "TransientStorage"): TransientStorage,
("ethereum", "cancun", "state", "MappingAddressTrieBytesU256"): Mapping[
Address, Trie[Bytes, U256]
],
("ethereum", "cancun", "state", "TransientStorageSnapshots"): List[
Dict[Address, Trie[Bytes, U256]]
],
}
```
5. Testing Pattern: We're only adding a type without functions, so we only need
to add the new types to `test_serde.py`.
```python:tests/test_serde.py
def test_type(
self,
to_cairo_type,
segments,
serde,
gen_arg,
b: Union[
# ... existing types ...
TransientStorage,
MappingAddressTrieBytesU256,
TransientStorageSnapshots,
],
):
# ... existing test logic ...
```
This implementation demonstrates:
- Complex type wrapping with pointer-based structures
- Dictionary-based mappings for key-value storage
- Write-once collections for state history
- Automatic Python-Cairo type bridging
- Testing for serialization and deserialization
The TransientStorage component shows how Cairo's memory model and type system
can be used to implement complex, stateful data structures while maintaining
type safety and immutability guarantees.