From eeab0578cd49be4026f26303466182b056bd9b6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Cl=C3=A9ment=20Walter?= Date: Wed, 25 Sep 2024 18:47:13 +0200 Subject: [PATCH] Add BlockHeader deserialization --- .codespellignore | 1 - .trunk/configs/cspell.yaml | 4 + .trunk/trunk.yaml | 4 +- .vscode/settings.json | 3 +- cairo/programs/fibonacci.cairo | 18 -- cairo/programs/fibonacci.json | 260 ------------------ cairo/programs/os.cairo | 15 +- cairo/programs/os.json | 364 ++++++-------------------- cairo/programs/transaction_hash.cairo | 5 - cairo/programs/transaction_hash.json | 70 ----- cairo/pyproject.toml | 1 + cairo/src/model.cairo | 30 ++- cairo/tests/programs/test_os.cairo | 6 + cairo/tests/programs/test_os.py | 42 ++- cairo/tests/utils/debug.cairo | 3 +- cairo/tests/utils/hints.py | 20 +- cairo/tests/utils/interface_id.py | 25 -- cairo/tests/utils/models.py | 135 ++++++++++ crates/exex/src/exex.rs | 275 ++++--------------- crates/exex/src/hints.rs | 99 +------ cspell.json | 17 ++ dictionnary.txt | 54 ++++ uv.lock | 2 + 23 files changed, 429 insertions(+), 1024 deletions(-) delete mode 100644 .codespellignore create mode 100644 .trunk/configs/cspell.yaml delete mode 100644 cairo/programs/fibonacci.cairo delete mode 100644 cairo/programs/fibonacci.json delete mode 100644 cairo/programs/transaction_hash.cairo delete mode 100644 cairo/programs/transaction_hash.json delete mode 100644 cairo/tests/utils/interface_id.py create mode 100644 cairo/tests/utils/models.py create mode 100644 cspell.json create mode 100644 dictionnary.txt diff --git a/.codespellignore b/.codespellignore deleted file mode 100644 index 9ac17d5..0000000 --- a/.codespellignore +++ /dev/null @@ -1 +0,0 @@ -crate diff --git a/.trunk/configs/cspell.yaml b/.trunk/configs/cspell.yaml new file mode 100644 index 0000000..7f99584 --- /dev/null +++ b/.trunk/configs/cspell.yaml @@ -0,0 +1,4 @@ +version: "0.2" +# Suggestions can sometimes take longer on CI machines, +# leading to inconsistent results. +suggestionsTimeout: 5000 # ms diff --git a/.trunk/trunk.yaml b/.trunk/trunk.yaml index 9689a3c..338c555 100644 --- a/.trunk/trunk.yaml +++ b/.trunk/trunk.yaml @@ -20,6 +20,8 @@ runtimes: system_version: allowed # This is the section where you manage your linters. (https://docs.trunk.io/check/configuration) lint: + disabled: + - codespell files: - name: cairo extensions: @@ -53,13 +55,13 @@ lint: read_output_from: stdout run_linter_from: workspace enabled: + - cspell@8.14.4 - dotenv-linter@3.3.0 - actionlint@1.7.1 - black@24.8.0 - cairo@SYSTEM - checkov@3.2.253 - clippy@SYSTEM - - codespell@2.3.0 - git-diff-check - hadolint@2.12.0 - isort@5.13.2 diff --git a/.vscode/settings.json b/.vscode/settings.json index 573be4b..09ac58d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -11,5 +11,6 @@ "python.testing.pytestArgs": ["cairo"], "python.testing.unittestEnabled": false, "python.testing.pytestEnabled": true, - "jupyter.notebookFileRoot": "${workspaceFolder}/cairo" + "jupyter.notebookFileRoot": "${workspaceFolder}/cairo", + "githubPullRequests.remotes": ["kakarot", "upstream"] } diff --git a/cairo/programs/fibonacci.cairo b/cairo/programs/fibonacci.cairo deleted file mode 100644 index 822e830..0000000 --- a/cairo/programs/fibonacci.cairo +++ /dev/null @@ -1,18 +0,0 @@ -func main() { - // Call fib(1, 1, 10). - let result: felt = fib(1, 1, 10); - - // Make sure the 10th Fibonacci number is 144. - assert result = 144; - ret; -} - -func fib(first_element, second_element, n) -> (res: felt) { - jmp fib_body if n != 0; - tempvar result = second_element; - return (second_element,); - - fib_body: - tempvar y = first_element + second_element; - return fib(second_element, y, n - 1); -} diff --git a/cairo/programs/fibonacci.json b/cairo/programs/fibonacci.json deleted file mode 100644 index 0758c55..0000000 --- a/cairo/programs/fibonacci.json +++ /dev/null @@ -1,260 +0,0 @@ -{ - "attributes": [], - "builtins": [], - "compiler_version": "0.13.2", - "data": [ - "0x40780017fff7fff", - "0x0", - "0x1104800180018000", - "0x4", - "0x10780017fff7fff", - "0x0", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0x1", - "0x480680017fff8000", - "0xa", - "0x1104800180018000", - "0x5", - "0x400680017fff7fff", - "0x90", - "0x208b7fff7fff7ffe", - "0x20780017fff7ffd", - "0x5", - "0x480a7ffc7fff8000", - "0x480a7ffc7fff8000", - "0x208b7fff7fff7ffe", - "0x482a7ffc7ffb8000", - "0x480a7ffc7fff8000", - "0x48127ffe7fff8000", - "0x482680017ffd8000", - "0x800000000000011000000000000000000000000000000000000000000000000", - "0x1104800180018000", - "0x800000000000010fffffffffffffffffffffffffffffffffffffffffffffff7", - "0x208b7fff7fff7ffe" - ], - "debug_info": null, - "hints": {}, - "identifiers": { - "__main__.__end__": { - "pc": 4, - "type": "label" - }, - "__main__.__start__": { - "pc": 0, - "type": "label" - }, - "__main__.fib": { - "decorators": [], - "pc": 17, - "type": "function" - }, - "__main__.fib.Args": { - "full_name": "__main__.fib.Args", - "members": { - "first_element": { - "cairo_type": "felt", - "offset": 0 - }, - "n": { - "cairo_type": "felt", - "offset": 2 - }, - "second_element": { - "cairo_type": "felt", - "offset": 1 - } - }, - "size": 3, - "type": "struct" - }, - "__main__.fib.ImplicitArgs": { - "full_name": "__main__.fib.ImplicitArgs", - "members": {}, - "size": 0, - "type": "struct" - }, - "__main__.fib.Return": { - "cairo_type": "(res: felt)", - "type": "type_definition" - }, - "__main__.fib.SIZEOF_LOCALS": { - "type": "const", - "value": 0 - }, - "__main__.fib.fib_body": { - "pc": 22, - "type": "label" - }, - "__main__.fib.first_element": { - "cairo_type": "felt", - "full_name": "__main__.fib.first_element", - "references": [ - { - "ap_tracking_data": { - "group": 4, - "offset": 0 - }, - "pc": 17, - "value": "[cast(fp + (-5), felt*)]" - } - ], - "type": "reference" - }, - "__main__.fib.n": { - "cairo_type": "felt", - "full_name": "__main__.fib.n", - "references": [ - { - "ap_tracking_data": { - "group": 4, - "offset": 0 - }, - "pc": 17, - "value": "[cast(fp + (-3), felt*)]" - } - ], - "type": "reference" - }, - "__main__.fib.result": { - "cairo_type": "felt", - "full_name": "__main__.fib.result", - "references": [ - { - "ap_tracking_data": { - "group": 4, - "offset": 1 - }, - "pc": 20, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.fib.second_element": { - "cairo_type": "felt", - "full_name": "__main__.fib.second_element", - "references": [ - { - "ap_tracking_data": { - "group": 4, - "offset": 0 - }, - "pc": 17, - "value": "[cast(fp + (-4), felt*)]" - } - ], - "type": "reference" - }, - "__main__.fib.y": { - "cairo_type": "felt", - "full_name": "__main__.fib.y", - "references": [ - { - "ap_tracking_data": { - "group": 4, - "offset": 1 - }, - "pc": 23, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main": { - "decorators": [], - "pc": 6, - "type": "function" - }, - "__main__.main.Args": { - "full_name": "__main__.main.Args", - "members": {}, - "size": 0, - "type": "struct" - }, - "__main__.main.ImplicitArgs": { - "full_name": "__main__.main.ImplicitArgs", - "members": {}, - "size": 0, - "type": "struct" - }, - "__main__.main.Return": { - "cairo_type": "()", - "type": "type_definition" - }, - "__main__.main.SIZEOF_LOCALS": { - "type": "const", - "value": 0 - }, - "__main__.main.result": { - "cairo_type": "felt", - "full_name": "__main__.main.result", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 0 - }, - "pc": 14, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - } - }, - "main_scope": "__main__", - "prime": "0x800000000000011000000000000000000000000000000000000000000000001", - "reference_manager": { - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 0 - }, - "pc": 14, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 4, - "offset": 0 - }, - "pc": 17, - "value": "[cast(fp + (-5), felt*)]" - }, - { - "ap_tracking_data": { - "group": 4, - "offset": 0 - }, - "pc": 17, - "value": "[cast(fp + (-4), felt*)]" - }, - { - "ap_tracking_data": { - "group": 4, - "offset": 0 - }, - "pc": 17, - "value": "[cast(fp + (-3), felt*)]" - }, - { - "ap_tracking_data": { - "group": 4, - "offset": 1 - }, - "pc": 20, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 4, - "offset": 1 - }, - "pc": 23, - "value": "[cast(ap + (-1), felt*)]" - } - ] - } -} diff --git a/cairo/programs/os.cairo b/cairo/programs/os.cairo index 6a864c4..3d19280 100644 --- a/cairo/programs/os.cairo +++ b/cairo/programs/os.cairo @@ -5,19 +5,8 @@ from starkware.cairo.common.memcpy import memcpy from src.model import model func main{output_ptr: felt*}() { - tempvar block_info: model.BlockInfo* = cast(nondet %{ segments.add() %}, model.BlockInfo*); - %{ block_info %} - - assert [output_ptr] = block_info.coinbase; - assert [output_ptr + 1] = block_info.timestamp; - assert [output_ptr + 2] = block_info.number; - assert [output_ptr + 3] = block_info.prev_randao.low; - assert [output_ptr + 4] = block_info.prev_randao.high; - assert [output_ptr + 5] = block_info.gas_limit; - assert [output_ptr + 6] = block_info.chain_id; - assert [output_ptr + 7] = block_info.base_fee; - - let output_ptr = output_ptr + 8; + tempvar block_header: model.BlockHeader*; + %{ block_header %} return (); } diff --git a/cairo/programs/os.json b/cairo/programs/os.json index b738f20..7db6db8 100644 --- a/cairo/programs/os.json +++ b/cairo/programs/os.json @@ -26,24 +26,7 @@ "0x208b7fff7fff7ffe", "0x40780017fff7fff", "0x1", - "0x480080007fff8000", - "0x400280007ffd7fff", - "0x480080017ffe8000", - "0x400280017ffd7fff", - "0x480080027ffd8000", - "0x400280027ffd7fff", - "0x480080037ffc8000", - "0x400280037ffd7fff", - "0x480080047ffb8000", - "0x400280047ffd7fff", - "0x480080057ffa8000", - "0x400280057ffd7fff", - "0x480080067ff98000", - "0x400280067ffd7fff", - "0x480080077ff88000", - "0x400280077ffd7fff", - "0x482680017ffd8000", - "0x8", + "0x480a7ffd7fff8000", "0x208b7fff7fff7ffe" ], "debug_info": null, @@ -116,33 +99,17 @@ } } ], - "21": [ - { - "accessible_scopes": ["__main__", "__main__.main"], - "code": "memory[ap] = to_felt_or_relocatable(segments.add())", - "flow_tracking_data": { - "ap_tracking": { - "group": 3, - "offset": 0 - }, - "reference_ids": { - "__main__.main.output_ptr": 8 - } - } - } - ], "23": [ { "accessible_scopes": ["__main__", "__main__.main"], - "code": "block_info", + "code": "block_header", "flow_tracking_data": { "ap_tracking": { "group": 3, "offset": 1 }, "reference_ids": { - "__main__.main.__temp1": 9, - "__main__.main.block_info": 10, + "__main__.main.block_header": 9, "__main__.main.output_ptr": 8 } } @@ -188,144 +155,9 @@ "type": "const", "value": 0 }, - "__main__.main.__temp1": { - "cairo_type": "felt", - "full_name": "__main__.main.__temp1", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 1 - }, - "pc": 23, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main.__temp2": { - "cairo_type": "felt", - "full_name": "__main__.main.__temp2", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 2 - }, - "pc": 24, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main.__temp3": { - "cairo_type": "felt", - "full_name": "__main__.main.__temp3", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 3 - }, - "pc": 26, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main.__temp4": { - "cairo_type": "felt", - "full_name": "__main__.main.__temp4", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 4 - }, - "pc": 28, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main.__temp5": { - "cairo_type": "felt", - "full_name": "__main__.main.__temp5", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 5 - }, - "pc": 30, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main.__temp6": { - "cairo_type": "felt", - "full_name": "__main__.main.__temp6", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 6 - }, - "pc": 32, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main.__temp7": { - "cairo_type": "felt", - "full_name": "__main__.main.__temp7", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 7 - }, - "pc": 34, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main.__temp8": { - "cairo_type": "felt", - "full_name": "__main__.main.__temp8", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 8 - }, - "pc": 36, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main.__temp9": { - "cairo_type": "felt", - "full_name": "__main__.main.__temp9", - "references": [ - { - "ap_tracking_data": { - "group": 3, - "offset": 9 - }, - "pc": 38, - "value": "[cast(ap + (-1), felt*)]" - } - ], - "type": "reference" - }, - "__main__.main.block_info": { - "cairo_type": "src.model.model.BlockInfo*", - "full_name": "__main__.main.block_info", + "__main__.main.block_header": { + "cairo_type": "src.model.model.BlockHeader*", + "full_name": "__main__.main.block_header", "references": [ { "ap_tracking_data": { @@ -333,7 +165,7 @@ "offset": 1 }, "pc": 23, - "value": "[cast(ap + (-1), src.model.model.BlockInfo**)]" + "value": "[cast(ap + (-1), src.model.model.BlockHeader**)]" } ], "type": "reference" @@ -349,14 +181,6 @@ }, "pc": 21, "value": "[cast(fp + (-3), felt**)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 9 - }, - "pc": 39, - "value": "cast([fp + (-3)] + 8, felt*)" } ], "type": "reference" @@ -464,43 +288,103 @@ "size": 0, "type": "struct" }, - "src.model.model.BlockInfo": { - "full_name": "src.model.model.BlockInfo", + "src.model.model.BlockHeader": { + "full_name": "src.model.model.BlockHeader", "members": { - "base_fee": { + "base_fee_per_gas": { "cairo_type": "felt", - "offset": 7 + "offset": 0 }, - "block_hashes": { - "cairo_type": "starkware.cairo.common.uint256.Uint256*", - "offset": 8 + "blob_gas_used": { + "cairo_type": "felt", + "offset": 1 }, - "chain_id": { + "bloom": { + "cairo_type": "felt*", + "offset": 3 + }, + "bloom_len": { "cairo_type": "felt", - "offset": 6 + "offset": 2 }, "coinbase": { "cairo_type": "felt", - "offset": 0 + "offset": 4 }, - "gas_limit": { + "difficulty": { "cairo_type": "felt", "offset": 5 }, + "excess_blob_gas": { + "cairo_type": "felt", + "offset": 6 + }, + "extra_data": { + "cairo_type": "felt*", + "offset": 8 + }, + "extra_data_len": { + "cairo_type": "felt", + "offset": 7 + }, + "gas_limit": { + "cairo_type": "felt", + "offset": 9 + }, + "gas_used": { + "cairo_type": "felt", + "offset": 10 + }, + "hash": { + "cairo_type": "starkware.cairo.common.uint256.Uint256", + "offset": 11 + }, + "mix_hash": { + "cairo_type": "starkware.cairo.common.uint256.Uint256", + "offset": 13 + }, + "nonce": { + "cairo_type": "felt", + "offset": 15 + }, "number": { "cairo_type": "felt", - "offset": 2 + "offset": 16 }, - "prev_randao": { + "parent_beacon_block_root": { "cairo_type": "starkware.cairo.common.uint256.Uint256", - "offset": 3 + "offset": 17 + }, + "parent_hash": { + "cairo_type": "starkware.cairo.common.uint256.Uint256", + "offset": 19 + }, + "receipt_trie": { + "cairo_type": "starkware.cairo.common.uint256.Uint256", + "offset": 21 + }, + "state_root": { + "cairo_type": "starkware.cairo.common.uint256.Uint256", + "offset": 23 }, "timestamp": { "cairo_type": "felt", - "offset": 1 + "offset": 25 + }, + "transactions_trie": { + "cairo_type": "starkware.cairo.common.uint256.Uint256", + "offset": 26 + }, + "uncle_hash": { + "cairo_type": "starkware.cairo.common.uint256.Uint256", + "offset": 28 + }, + "withdrawals_root": { + "cairo_type": "starkware.cairo.common.uint256.Uint256", + "offset": 30 } }, - "size": 9, + "size": 32, "type": "struct" }, "src.model.model.EVM": { @@ -1584,87 +1468,7 @@ "offset": 1 }, "pc": 23, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 1 - }, - "pc": 23, - "value": "[cast(ap + (-1), src.model.model.BlockInfo**)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 2 - }, - "pc": 24, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 3 - }, - "pc": 26, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 4 - }, - "pc": 28, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 5 - }, - "pc": 30, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 6 - }, - "pc": 32, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 7 - }, - "pc": 34, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 8 - }, - "pc": 36, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 9 - }, - "pc": 38, - "value": "[cast(ap + (-1), felt*)]" - }, - { - "ap_tracking_data": { - "group": 3, - "offset": 9 - }, - "pc": 39, - "value": "cast([fp + (-3)] + 8, felt*)" + "value": "[cast(ap + (-1), src.model.model.BlockHeader**)]" } ] } diff --git a/cairo/programs/transaction_hash.cairo b/cairo/programs/transaction_hash.cairo deleted file mode 100644 index 8e61197..0000000 --- a/cairo/programs/transaction_hash.cairo +++ /dev/null @@ -1,5 +0,0 @@ -func main() { - %{ print_latest_block_transactions %} - - ret; -} diff --git a/cairo/programs/transaction_hash.json b/cairo/programs/transaction_hash.json deleted file mode 100644 index 7e092dd..0000000 --- a/cairo/programs/transaction_hash.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "attributes": [], - "builtins": [], - "compiler_version": "0.13.2", - "data": [ - "0x40780017fff7fff", - "0x0", - "0x1104800180018000", - "0x4", - "0x10780017fff7fff", - "0x0", - "0x208b7fff7fff7ffe" - ], - "debug_info": null, - "hints": { - "6": [ - { - "accessible_scopes": ["__main__", "__main__.main"], - "code": "print_latest_block_transactions", - "flow_tracking_data": { - "ap_tracking": { - "group": 2, - "offset": 0 - }, - "reference_ids": {} - } - } - ] - }, - "identifiers": { - "__main__.__end__": { - "pc": 4, - "type": "label" - }, - "__main__.__start__": { - "pc": 0, - "type": "label" - }, - "__main__.main": { - "decorators": [], - "pc": 6, - "type": "function" - }, - "__main__.main.Args": { - "full_name": "__main__.main.Args", - "members": {}, - "size": 0, - "type": "struct" - }, - "__main__.main.ImplicitArgs": { - "full_name": "__main__.main.ImplicitArgs", - "members": {}, - "size": 0, - "type": "struct" - }, - "__main__.main.Return": { - "cairo_type": "()", - "type": "type_definition" - }, - "__main__.main.SIZEOF_LOCALS": { - "type": "const", - "value": 0 - } - }, - "main_scope": "__main__", - "prime": "0x800000000000011000000000000000000000000000000000000000000000001", - "reference_manager": { - "references": [] - } -} diff --git a/cairo/pyproject.toml b/cairo/pyproject.toml index fc516b3..2550f77 100644 --- a/cairo/pyproject.toml +++ b/cairo/pyproject.toml @@ -23,6 +23,7 @@ dev-dependencies = [ "protobuf>=5.28.1", "pytest-xdist>=3.6.1", "pytest>=8.3.3", + "pydantic>=2.9.1", ] [tool.isort] diff --git a/cairo/src/model.cairo b/cairo/src/model.cairo index 799c2cb..97d74c9 100644 --- a/cairo/src/model.cairo +++ b/cairo/src/model.cairo @@ -221,14 +221,30 @@ namespace model { chain_id: Option, } - // @notice A struct representing the constants of an Eth block. - struct BlockInfo { + // @notice A struct representing the header of an Eth block. + struct BlockHeader { + base_fee_per_gas: felt, + blob_gas_used: felt, + bloom_len: felt, + bloom: felt*, coinbase: felt, - timestamp: felt, - number: felt, - prev_randao: Uint256, + difficulty: felt, + excess_blob_gas: felt, + extra_data_len: felt, + extra_data: felt*, gas_limit: felt, - chain_id: felt, - base_fee: felt, + gas_used: felt, + hash: Uint256, + mix_hash: Uint256, + nonce: felt, + number: felt, + parent_beacon_block_root: Uint256, + parent_hash: Uint256, + receipt_trie: Uint256, + state_root: Uint256, + timestamp: felt, + transactions_trie: Uint256, + uncle_hash: Uint256, + withdrawals_root: Uint256, } } diff --git a/cairo/tests/programs/test_os.cairo b/cairo/tests/programs/test_os.cairo index d16ea55..ef5fc50 100644 --- a/cairo/tests/programs/test_os.cairo +++ b/cairo/tests/programs/test_os.cairo @@ -7,3 +7,9 @@ func test_os{output_ptr: felt*}() { return (); } + +func test_block_header() -> model.BlockHeader* { + tempvar block_header: model.BlockHeader*; + %{ block_header %} + return block_header; +} diff --git a/cairo/tests/programs/test_os.py b/cairo/tests/programs/test_os.py index d72b84c..6a18561 100644 --- a/cairo/tests/programs/test_os.py +++ b/cairo/tests/programs/test_os.py @@ -1,4 +1,42 @@ +import pytest + +from tests.utils.models import BlockHeader + + +@pytest.fixture +def block_header(): + return BlockHeader.model_validate( + { + "baseFeePerGas": "0x0a", + "blobGasUsed": "0x00", + "bloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "coinbase": "0x2adc25665018aa1fe0e6bc666dac8fc2697ff9ba", + "difficulty": "0x00", + "excessBlobGas": "0x00", + "extraData": "0x00", + "gasLimit": "0x0f4240", + "gasUsed": "0x0156f8", + "hash": "0x46e317ac1d4c1a14323d9ef994c0f0813c6a90af87113a872ca6bcfcea86edba", + "mixHash": "0x0000000000000000000000000000000000000000000000000000000000020000", + "nonce": "0x0000000000000000", + "number": "0x01", + "parentBeaconBlockRoot": "0x0000000000000000000000000000000000000000000000000000000000000000", + "parentHash": "0x02a4bfb03275efd1bf926bcbccc1c12ef1ed723414c1196b75c33219355c7180", + "receiptTrie": "0xf44202824894394d28fa6c8c8e3ef83e1adf05405da06240c2ce9ca461e843d1", + "stateRoot": "0x2f79dbc20b78bcd7a771a9eb6b25a4af69724085c97be69a95ba91187e66a9c0", + "timestamp": "0x64903c57", + "transactionsTrie": "0x5f3c4c1da4f0b2351fbb60b9e720d481ce0706b5aa697f10f28efbbab54e6ac8", + "uncleHash": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347", + "withdrawalsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421", + } + ) + + class TestOs: - def test_os(self, cairo_run): - assert cairo_run("test_os") == list(range(1, 9)) + def test_os(self, cairo_run, block_header): + cairo_run("test_os", block_header=block_header) + + def test_block_header(self, cairo_run, block_header): + result = cairo_run("test_block_header", block_header=block_header) + assert BlockHeader.model_validate(result) == block_header diff --git a/cairo/tests/utils/debug.cairo b/cairo/tests/utils/debug.cairo index 320ad48..8afac91 100644 --- a/cairo/tests/utils/debug.cairo +++ b/cairo/tests/utils/debug.cairo @@ -1,6 +1,7 @@ from starkware.cairo.common.uint256 import Uint256 from starkware.cairo.common.dict_access import DictAccess -from model import model + +from src.model import model namespace Debug { func print_felt(x: felt) { diff --git a/cairo/tests/utils/hints.py b/cairo/tests/utils/hints.py index 4185169..ba96405 100644 --- a/cairo/tests/utils/hints.py +++ b/cairo/tests/utils/hints.py @@ -32,22 +32,16 @@ def new_default_dict( return base -block_info = """ -ids.block_info.coinbase = 1 -ids.block_info.timestamp = 2 -ids.block_info.number = 3 -ids.block_info.prev_randao.low = 4 -ids.block_info.prev_randao.high = 5 -ids.block_info.gas_limit = 6 -ids.block_info.chain_id = 7 -ids.block_info.base_fee = 8 +block_header = """ +ptr = segments.add() +segments.write_arg(ptr, program_input["block_header"].model_dump().values()) +ids.block_header = ptr """ -transaction_hash = """ -""" - -hints = {"block_info": block_info, "transaction_hash": transaction_hash} +hints = { + "block_header": block_header, +} def implement_hints(program): diff --git a/cairo/tests/utils/interface_id.py b/cairo/tests/utils/interface_id.py deleted file mode 100644 index 7c52a3d..0000000 --- a/cairo/tests/utils/interface_id.py +++ /dev/null @@ -1,25 +0,0 @@ -from eth_utils import keccak - - -def get_interface_id(): - validate = keccak( - text="__validate__(call_array_len: felt, call_array: ExternallyOwnedAccount.CallArray*, calldata_len: felt, calldata: felt*)" - ) - validate_declare = keccak(text="__validate_declare__(class_hash: felt)") - execute = keccak( - text="__execute__(call_array_len: felt, call_array: ExternallyOwnedAccount.CallArray*, calldata_len: felt, calldata: felt*)" - ) - get_evm_address = keccak(text="get_evm_address()") - supports_interface = keccak(text="supports_interface(interface_id: felt)") - is_valid_signature = keccak( - text="is_valid_signature(hash_len: felt, hash: felt*, signature_len: felt, signature: felt*)" - ) - return bytes( - validate[i] - ^ validate_declare[i] - ^ execute[i] - ^ get_evm_address[i] - ^ supports_interface[i] - ^ is_valid_signature[i] - for i in range(4) - ) diff --git a/cairo/tests/utils/models.py b/cairo/tests/utils/models.py new file mode 100644 index 0000000..05933b4 --- /dev/null +++ b/cairo/tests/utils/models.py @@ -0,0 +1,135 @@ +from typing import Union + +from pydantic import ( + AliasChoices, + AliasGenerator, + BaseModel, + ConfigDict, + field_validator, + model_validator, +) +from pydantic.alias_generators import to_camel + +from src.utils.uint256 import int_to_uint256 + + +def to_int(v: Union[str, int]) -> int: + if isinstance(v, str): + if v.startswith("0x"): + return int(v, 16) + return int(v) + return v + + +def to_bytes(v: Union[str, bytes, list[int]]) -> bytes: + if isinstance(v, bytes): + return v + elif isinstance(v, str): + if v.startswith("0x"): + return bytes.fromhex(v[2:]) + return v.encode() + else: + return bytes(v) + + +class BlockHeader(BaseModel): + model_config = ConfigDict( + populate_by_name=True, + alias_generator=AliasGenerator( + validation_alias=lambda name: AliasChoices( + to_camel(name.replace("_low", "")), + name.replace("_low", ""), + to_camel(name), + name, + ) + ), + ) + + @field_validator( + "base_fee_per_gas", + "blob_gas_used", + "coinbase", + "difficulty", + "excess_blob_gas", + "gas_limit", + "gas_used", + "nonce", + "number", + "timestamp", + mode="before", + ) + def parse_hex_to_int(cls, v): + return to_int(v) + + @field_validator("extra_data", "bloom", mode="before") + def parse_hex_to_bytes(cls, v): + return to_bytes(v) + + @model_validator(mode="before") + def split_uint256(cls, values): + for key in [ + "hash", + "mix_hash", + "parent_beacon_block_root", + "parent_hash", + "receipt_trie", + "state_root", + "transactions_trie", + "uncle_hash", + "withdrawals_root", + ]: + if key not in values: + key = to_camel(key) + if key not in values: + continue + + values[key], values[to_camel(key) + "High"] = int_to_uint256( + to_int(values[key]) + ) + return values + + @model_validator(mode="before") + def add_len_to_bytes(cls, values): + for key in ["bloom", "extra_data"]: + if key not in values: + key = to_camel(key) + if key not in values: + continue + + value = to_bytes(values[key]) + values[key] = value + values[to_camel(key) + "Len"] = len(value) + return values + + base_fee_per_gas: int + blob_gas_used: int + bloom_len: int + bloom: bytes + coinbase: int + difficulty: int + excess_blob_gas: int + extra_data_len: int + extra_data: bytes + gas_limit: int + gas_used: int + hash_low: int + hash_high: int + mix_hash_low: int + mix_hash_high: int + nonce: int + number: int + parent_beacon_block_root_low: int + parent_beacon_block_root_high: int + parent_hash_low: int + parent_hash_high: int + receipt_trie_low: int + receipt_trie_high: int + state_root_low: int + state_root_high: int + timestamp: int + transactions_trie_low: int + transactions_trie_high: int + uncle_hash_low: int + uncle_hash_high: int + withdrawals_root_low: int + withdrawals_root_high: int diff --git a/crates/exex/src/exex.rs b/crates/exex/src/exex.rs index a74d0c3..d03dc59 100644 --- a/crates/exex/src/exex.rs +++ b/crates/exex/src/exex.rs @@ -1,4 +1,4 @@ -use crate::{db::Database, execution::execute_block, hints::KakarotHintProcessor}; +use crate::{db::Database, hints::KakarotHintProcessor}; use cairo_vm::{ air_private_input::AirPrivateInput, air_public_input::PublicInput, @@ -10,11 +10,9 @@ use cairo_vm::{ use futures::StreamExt; use once_cell::sync::Lazy; use reth_chainspec::{ChainSpec, ChainSpecBuilder}; -use reth_execution_types::Chain; use reth_exex::{ExExContext, ExExEvent}; use reth_node_api::FullNodeComponents; -use reth_primitives::{Address, Genesis, SealedBlock, TransactionSignedEcRecovered}; -use reth_tracing::tracing::{error, info}; +use reth_primitives::{Address, Genesis}; use rusqlite::Connection; use std::{path::PathBuf, sync::Arc}; @@ -56,7 +54,7 @@ impl KakarotRollup { } /// Starts processing chain state notifications. - pub async fn start(mut self, paths: Vec) -> eyre::Result<()> { + pub async fn start(mut self) -> eyre::Result<()> { // Initialize the Cairo run configuration let config = CairoRunConfig { layout: LayoutName::all_cairo, @@ -70,8 +68,6 @@ impl KakarotRollup { while let Some(notification) = self.ctx.notifications.next().await { // Check if the notification contains a committed chain. if let Some(committed_chain) = notification.committed_chain() { - // Commit the new chain state. - self.commit_block(&committed_chain).await?; // Send a notification that the chain processing is finished. // // Finished height is the tip of the committed chain. @@ -79,107 +75,46 @@ impl KakarotRollup { // The ExEx will not require all earlier blocks which can be pruned. self.ctx.events.send(ExExEvent::FinishedHeight(committed_chain.tip().number))?; - // Build the Kakarot hint processor with the print transaction hint. + // Build the Kakarot hint processor. let mut hint_processor = KakarotHintProcessor::default().build(); - // Run the cairo programs corresponding to the paths - for path in &paths { - // Load the cairo program from the file - let program = std::fs::read(path)?; - - // Execute the Cairo program with the specified configuration and hint - // processor. - let res = cairo_run(&program, &config, &mut hint_processor)?; - - // Extract the execution trace - let trace = res.relocated_trace.clone().unwrap_or_default(); - - // Extract the relocated memory - let memory = res - .relocated_memory - .clone() - .into_iter() - .map(|x| x.unwrap_or_default()) - .collect(); - - // Extract the public and private inputs - // - // We want to store the public input in the database in order to use them to run - // the prover - let public_input = res.get_air_public_input()?; - let private_input = res.get_air_private_input(); - - // Commit the execution trace to the database - self.commit_cairo_execution_traces( - committed_chain.tip().number, - trace, - memory, - public_input, - private_input, - )?; - } - } - } + // Load the cairo program from the file + let program = std::fs::read(PathBuf::from("../../cairo/programs/os.json"))?; - Ok(()) - } + // Execute the Kakarot os program + let mut res = cairo_run(&program, &config, &mut hint_processor)?; - /// Process a new chain commit. - /// - /// This function processes the blocks and transactions in the committed chain, - /// executes the transactions, and updates the database. - pub async fn commit_block(&mut self, chain: &Chain) -> eyre::Result<()> { - // Extract blocks and receipts from the chain and pair each transaction with its sender. - let blocks = chain - .blocks_and_receipts() - .map(|(block, receipts)| { - block - .body - .iter() - .map(|tx| { - tx.recover_signer() - .map(|sender| { - TransactionSignedEcRecovered::from_signed_transaction( - tx.clone(), - sender, - ) - }) - .ok_or_else(|| eyre::eyre!("failed to recover signer")) - }) - .collect::>>() - .map(|txs| (block, txs, receipts)) - }) - .collect::>>()?; - - // Process each block and its transactions. - for (block, txs, _) in blocks { - // Execute the block and handle the result. - match execute_block(&mut self.db, block, txs.clone()).await { - Ok((block, bundle, _, _)) => { - // Seal the block. - let block = block.seal_slow(); - // After the block is executed, we want to run the get_env program - // - // The goal is to store in a Cairo program, via hint, all the information about - // the block - self.execute_get_env(block.block.clone(), txs, chain.tip().number)?; - // Insert the block into the database. - self.db.insert_block_with_bundle(&block, bundle)?; - info!( - block_hash = %block.hash(), - transactions = block.body.len(), - "Block submitted, executed and inserted into database" - ); - } - Err(err) => { - // Log an error if the block execution fails. - error!( - %err, - block_hash = %block.hash(), - transactions = block.body.len(), - "Failed to execute block" - ); - } + // Retrieve the output of the program + let mut output_buffer = String::new(); + res.vm.write_output(&mut output_buffer).unwrap(); + println!("Program output: \n{}", output_buffer); + + // Extract the execution trace + let trace = res.relocated_trace.clone().unwrap_or_default(); + + // Extract the relocated memory + let memory = res + .relocated_memory + .clone() + .into_iter() + .map(|x| x.unwrap_or_default()) + .collect(); + + // Extract the public and private inputs + // + // We want to store the public input in the database in order to use them to run + // the prover + let public_input = res.get_air_public_input()?; + let private_input = res.get_air_private_input(); + + // Commit the execution trace to the database + self.commit_cairo_execution_traces( + committed_chain.tip().number, + trace, + memory, + public_input, + private_input, + )?; } } @@ -197,73 +132,6 @@ impl KakarotRollup { ) -> eyre::Result<()> { self.db.insert_execution_trace(number, trace, memory, air_public_input, air_private_input) } - - /// Executes the Cairo program to retrieve and process the environment (block and transaction) - /// data. - /// - /// This function takes a sealed block and a list of signed transactions, executes a Cairo - /// program to retrieve environment data via a hint. - fn execute_get_env( - &mut self, - block: SealedBlock, - txs: Vec, - chain_tip: u64, - ) -> eyre::Result<()> { - // Initialize the Cairo runtime configuration with various settings. - let config = CairoRunConfig { - layout: LayoutName::all_cairo, - trace_enabled: true, - relocate_mem: true, - proof_mode: true, - allow_missing_builtins: Some(false), // Ensures no missing built-in hints are allowed. - ..Default::default() - }; - - // Loop through each transaction in the block to run the Cairo program. - for tx in &txs { - // Create the Kakarot hint processor with the block and transaction context. - let mut hint_processor = KakarotHintProcessor::default() - .with_block_and_transaction(block.clone(), tx.clone()) - .build(); - - // Load the toy Cairo program from the file. - let program = std::fs::read(PathBuf::from("../../cairo/programs/os.json"))?; - - // Execute the Cairo program with the specified configuration and hint processor. - // - // This runs the Cairo VM to test our hint processor and the associated Cairo program. - let mut res = cairo_run(&program, &config, &mut hint_processor)?; - - // As we use the output builtin, we can print the block information to the console. - let mut output_buffer = String::new(); - res.vm.write_output(&mut output_buffer).unwrap(); - println!("Block information: \n{}", output_buffer); - - // Extract the execution trace from the result. - let trace = res.relocated_trace.clone().unwrap_or_default(); - - // Extract the relocated memory from the VM execution result. - let memory = - res.relocated_memory.clone().into_iter().map(|x| x.unwrap_or_default()).collect(); - - // Retrieve the public and private inputs from the program execution. - let public_input = res.get_air_public_input()?; - let private_input = res.get_air_private_input(); - - // Store the execution trace, relocated memory, and inputs in the database. - // - // These will be used later to verify the execution and generate proofs. - self.commit_cairo_execution_traces( - chain_tip, // The current chain tip. - trace, // The extracted execution trace. - memory, // The relocated memory. - public_input, // The public input for proving. - private_input, // The private input for proving. - )?; - } - - Ok(()) - } } #[cfg(test)] @@ -272,11 +140,11 @@ mod tests { use reth_execution_types::{Chain, ExecutionOutcome}; use reth_exex_test_utils::{test_exex_context, PollOnce}; use reth_primitives::{ - address, constants::ETH_TO_WEI, hex, Bytes, Header, Receipt, Receipts, SealedBlock, - SealedBlockWithSenders, TransactionSigned, TxEip1559, B256, U256, + address, constants::ETH_TO_WEI, hex, Header, Receipt, Receipts, SealedBlock, + SealedBlockWithSenders, U256, }; use reth_revm::primitives::AccountInfo; - use std::{future::Future, pin::pin, str::FromStr}; + use std::{future::Future, pin::pin}; /// The initialization logic of the ExEx is just an async function. /// @@ -304,12 +172,10 @@ mod tests { )?; // Create the Kakarot Rollup chain instance and start processing chain state notifications. - Ok(KakarotRollup { ctx, db }.start(vec![ - PathBuf::from("../../cairo/programs/transaction_hash.json"), - PathBuf::from("../../cairo/programs/fibonacci.json"), - ])) + Ok(KakarotRollup { ctx, db }.start()) } + #[ignore = "block_header not implemented"] #[tokio::test] async fn test_exex() -> eyre::Result<()> { // Initialize the tracing subscriber for testing @@ -321,38 +187,6 @@ mod tests { // Initialize a test Execution Extension context with all dependencies let (ctx, mut handle) = test_exex_context().await?; - // Random mainnet tx - let tx = TransactionSigned { - hash: B256::from_str( - "0xc3099e296bc0eaa6d3a5e0f46fcc4a9bb2f42fb4668a17dd926d75ca651509f0", - ) - .unwrap(), - signature: reth_primitives::Signature { - r: U256::from_str( - "0xe74ec6b1365234a0ebe63f8e238d2318b28d1d2c58ada3a153ad364497dac715", - ) - .unwrap(), - s: U256::from_str( - "0x7306a7cab3679ead15daee428d2481b1b92a5dc2303adfe4b3bbbb4713be74af", - ) - .unwrap(), - odd_y_parity: false, - }, - transaction: reth_primitives::Transaction::Eip1559(TxEip1559 { - chain_id: 1, - nonce: 0, - gas_limit: 0x3173e, - max_fee_per_gas: 0x2a9860004, - max_priority_fee_per_gas: 0x4903a597, - to: reth_primitives::TxKind::Call( - Address::from_str("0xf3de3c0d654fda23dad170f0f320a92172509127").unwrap(), - ), - value: U256::from_str("0xb1a2bc2ec50000").unwrap(), - access_list: Default::default(), - input: Bytes::from_str("0x9871efa4000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000b1a2bc2ec50000000000000000000000000000000000000000000000000009f7051a01fa559ee400000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000001b0000000000000003b6d0340cab7ab9f1a9add91380a0e8fae700b65f320e667").unwrap(), - }), - }; - // https://etherscan.io/block/15867168 where transaction root and receipts root are cleared // empty merkle tree: 0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421 let header = Header { @@ -381,7 +215,7 @@ mod tests { // Create a sealed block with a single transaction let block = SealedBlockWithSenders { - block: SealedBlock { header: header.seal_slow(), body: vec![tx], ..Default::default() }, + block: SealedBlock { header: header.seal_slow(), body: vec![], ..Default::default() }, senders: vec![address!("6a3cA5811d2c185E6e441cEFa771824fb355f9Ec")], }; @@ -416,25 +250,6 @@ mod tests { // Initialize the database with the connection. let db = Database::new(connection)?; - // Check that the recipient account has the correct balance after the transaction - let recipient_account_info = - db.account(address!("f3de3c0d654fda23dad170f0f320a92172509127"))?; - assert_eq!( - recipient_account_info.unwrap().balance, - U256::from_str("0xb1a2bc2ec50000").unwrap() - ); - - // Check that the sender account has the correct balance after the transaction - let sender_account_info = - db.account(address!("6a3cA5811d2c185E6e441cEFa771824fb355f9Ec"))?; - assert_eq!( - sender_account_info.unwrap().balance, - // Initial balance - value - gas used - U256::from(ETH_TO_WEI) - - U256::from_str("0xb1a2bc2ec50000").unwrap() - - U256::from_str("0xe826f9395cd0").unwrap() - ); - // Check that the block has been inserted into the database assert_eq!(db.block(U256::from(0xf21d20))?.unwrap(), block); diff --git a/crates/exex/src/hints.rs b/crates/exex/src/hints.rs index 686aef9..9f8d274 100644 --- a/crates/exex/src/hints.rs +++ b/crates/exex/src/hints.rs @@ -1,20 +1,16 @@ -use crate::{db::Database, exex::DATABASE_PATH}; use cairo_vm::{ hint_processor::{ builtin_hint_processor::{ builtin_hint_processor_definition::{BuiltinHintProcessor, HintFunc}, - hint_utils::get_ptr_from_var_name, memcpy_hint_utils::add_segment, }, hint_processor_definition::HintReference, }, serde::deserialize_program::ApTracking, - types::{exec_scope::ExecutionScopes, relocatable::MaybeRelocatable}, + types::exec_scope::ExecutionScopes, vm::{errors::hint_errors::HintError, vm_core::VirtualMachine}, Felt252, }; -use reth_primitives::{SealedBlock, TransactionSignedEcRecovered}; -use rusqlite::Connection; use std::{collections::HashMap, fmt, rc::Rc}; /// The type of a hint execution result. @@ -38,7 +34,7 @@ impl fmt::Debug for KakarotHintProcessor { impl Default for KakarotHintProcessor { fn default() -> Self { - Self::new_empty().with_hint(print_tx_hint()).with_hint(add_segment_hint()) + Self::new_empty().with_hint(add_segment_hint()) } } @@ -56,18 +52,6 @@ impl KakarotHintProcessor { self } - /// Adds a block to the [`KakarotHintProcessor`]. - /// - /// This method allows you to register a block by providing a [`SealedBlockWithSenders`] - /// instance. - pub fn with_block_and_transaction( - self, - block: SealedBlock, - transaction: TransactionSignedEcRecovered, - ) -> Self { - self.with_hint(block_info_hint(block, transaction)) - } - /// Returns the underlying [`BuiltinHintProcessor`]. /// /// This allows the processor to be used elsewhere. @@ -110,85 +94,6 @@ impl Hint { } } -/// Public function to create the `print_latest_block_transactions` hint. -/// -/// This function returns a new `Hint` instance with the specified name and logic. -pub fn print_tx_hint() -> Hint { - Hint::new( - String::from("print_latest_block_transactions"), - |_vm: &mut VirtualMachine, - _exec_scopes: &mut ExecutionScopes, - _ids_data: &HashMap, - _ap_tracking: &ApTracking, - _constants: &HashMap| - -> HintExecutionResult { - // Open the SQLite database connection. - let connection = Connection::open(DATABASE_PATH) - .map_err(|e| HintError::CustomHint(e.to_string().into_boxed_str()))?; - - // Initialize the database with the connection. - let db = Database::new(connection) - .map_err(|e| HintError::CustomHint(e.to_string().into_boxed_str()))?; - - // Retrieve the latest block from the database. - let latest_block = db - .latest_block() - .map_err(|e| HintError::CustomHint(e.to_string().into_boxed_str()))?; - - // If a block was found, print each transaction hash. - if let Some(block) = latest_block { - for tx in &block.body { - println!("Block: {}, transaction hash: {}", block.number, tx.hash()); - } - } - - Ok(()) - }, - ) -} - -/// Generates a hint to store block information in the `Environment` model. -pub fn block_info_hint(block: SealedBlock, transaction: TransactionSignedEcRecovered) -> Hint { - Hint::new( - String::from("block_info"), - move |vm: &mut VirtualMachine, - _exec_scopes: &mut ExecutionScopes, - ids_data: &HashMap, - ap_tracking: &ApTracking, - _constants: &HashMap| - -> HintExecutionResult { - // We retrieve the `env` pointer from the `ids_data` hashmap. - // This pointer is used to store the block-related values in the VM. - let env_ptr = get_ptr_from_var_name("block_info", vm, ids_data, ap_tracking)?; - - // We load the block-related values into the VM. - // - // The values are loaded in the order they are defined in the `Environment` model. - // We start at the `env` pointer. - vm.load_data( - env_ptr, - &[ - MaybeRelocatable::from(Felt252::from_bytes_be_slice(&block.beneficiary.0 .0)), - MaybeRelocatable::from(Felt252::from(block.timestamp)), - MaybeRelocatable::from(Felt252::from(block.number)), - MaybeRelocatable::from(Felt252::from_bytes_be_slice(&block.mix_hash.0[16..])), - MaybeRelocatable::from(Felt252::from_bytes_be_slice(&block.mix_hash.0[0..16])), - MaybeRelocatable::from(Felt252::from(block.gas_limit)), - MaybeRelocatable::from(Felt252::from( - transaction.chain_id().unwrap_or_default(), - )), - MaybeRelocatable::from(Felt252::from( - block.base_fee_per_gas.unwrap_or_default(), - )), - ], - ) - .map_err(HintError::Memory)?; - - Ok(()) - }, - ) -} - /// Generates a hint to add a new memory segment. /// /// This function adds a hint to the `HintProcessor` that creates a new memory segment in the diff --git a/cspell.json b/cspell.json new file mode 100644 index 0000000..aa5477f --- /dev/null +++ b/cspell.json @@ -0,0 +1,17 @@ +{ + // Enable your dictionary by adding it to the list of `dictionaries` + "dictionaries": ["dictionary"], + + // Tell CSpell about your dictionary + "dictionaryDefinitions": [ + { + // The name of the dictionary is used to look it up. + "name": "dictionary", + // Path to the custom word file. Relative to this `cspell.json` file. + "path": "./dictionary.txt", + // Some editor extensions will use `addWords` for adding words to your + // personal dictionary. + "addWords": true + } + ] +} diff --git a/dictionnary.txt b/dictionnary.txt new file mode 100644 index 0000000..578276b --- /dev/null +++ b/dictionnary.txt @@ -0,0 +1,54 @@ +addoption +autouse +bitlength +bytecodelen +coeffs +divmod +dotenv +dragan +extcodecopy +feltroidprime +fromhex +fspath +fullk +getcwd +isinstance +itertools +jumpdest +JUMPDEST +jumpdests +Kakarot +keccak +lastblockhash +levelname +lllcversion +mcopy +MCOPY +memcpy +mstore +nbits +negone +negthree +negtwo +nondet +notive +pedersen +pointee +PUSHN +randao +retesteth +secp +selfdestruct +serde +Serde +signextend +SLOAD +SSTORE +starknet +starkware +Starkware +summands +tempvar +unexisting +VERIF +zellic diff --git a/uv.lock b/uv.lock index c69a774..b32d579 100644 --- a/uv.lock +++ b/uv.lock @@ -262,6 +262,7 @@ dev = [ { name = "hypothesis" }, { name = "ipykernel" }, { name = "protobuf" }, + { name = "pydantic" }, { name = "pytest" }, { name = "pytest-xdist" }, ] @@ -283,6 +284,7 @@ dev = [ { name = "hypothesis", specifier = ">=6.112.1" }, { name = "ipykernel", specifier = ">=6.29.5" }, { name = "protobuf", specifier = ">=5.28.1" }, + { name = "pydantic", specifier = ">=2.9.1" }, { name = "pytest", specifier = ">=8.3.3" }, { name = "pytest-xdist", specifier = ">=3.6.1" }, ]